context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright 2017 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 // // 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 UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; public class masterControl : MonoBehaviour { public static masterControl instance; public UnityEngine.Audio.AudioMixer masterMixer; public static float versionNumber = .76f; public enum platform { Vive, NoVR, Oculus }; public platform currentPlatform = platform.Vive; public Color tipColor = new Color(88 / 255f, 114 / 255f, 174 / 255f); public AudioSource backgroundAudio, metronomeClick; public GameObject exampleSetups; public UnityEngine.UI.Toggle muteEnvToggle; public float bpm = 120; public float curCycle = 0; public double measurePeriod = 4; public int curMic = 0; public string currentScene = ""; public delegate void BeatUpdateEvent(float t); public BeatUpdateEvent beatUpdateEvent; public delegate void BeatResetEvent(); public BeatResetEvent beatResetEvent; public bool showEnvironment = true; double _sampleDuration; double _measurePhase; public SENaturalBloomAndDirtyLens mainGlowShader; public float glowVal = 1; public string SaveDir; public bool handlesEnabled = true; public bool jacksEnabled = true; void Awake() { instance = this; _measurePhase = 0; _sampleDuration = 1.0 / AudioSettings.outputSampleRate; if (!PlayerPrefs.HasKey("glowVal")) PlayerPrefs.SetFloat("glowVal", 1); if (!PlayerPrefs.HasKey("envSound")) PlayerPrefs.SetInt("envSound", 1); glowVal = PlayerPrefs.GetFloat("glowVal"); setGlowLevel(glowVal); if (PlayerPrefs.GetInt("envSound") == 0) { MuteBackgroundSFX(true); muteEnvToggle.isOn = true; } SaveDir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + Path.DirectorySeparatorChar + "SoundStage"; ReadFileLocConfig(); Directory.CreateDirectory(SaveDir + Path.DirectorySeparatorChar + "Saves"); Directory.CreateDirectory(SaveDir + Path.DirectorySeparatorChar + "Samples"); beatUpdateEvent += beatUpdateEventLocal; beatResetEvent += beatResetEventLocal; setBPM(120); GetComponent<sampleManager>().Init(); } public void toggleInstrumentVolume(bool on) { masterMixer.SetFloat("instrumentVolume", on ? 0 : -18); } void ReadFileLocConfig() { if(File.Exists(Application.dataPath + Path.DirectorySeparatorChar + "fileloc.cfg")) { string _txt = File.ReadAllText(Application.dataPath + Path.DirectorySeparatorChar + "fileloc.cfg"); if (_txt != @"x:/put/custom/dir/here" && _txt != "") { _txt = Path.GetFullPath(_txt); if (Directory.Exists(_txt)) SaveDir = _txt; } } } public void toggleHandles(bool on) { handlesEnabled = on; handle[] handles = FindObjectsOfType<handle>(); for (int i = 0; i < handles.Length; i++) { handles[i].toggleHandles(on); } } public void toggleJacks(bool on) { jacksEnabled = on; omniJack[] jacks = FindObjectsOfType<omniJack>(); for (int i = 0; i < jacks.Length; i++) { jacks[i].GetComponent<Collider>().enabled = on; } omniPlug[] plugs = FindObjectsOfType<omniPlug>(); for (int i = 0; i < plugs.Length; i++) { plugs[i].GetComponent<Collider>().enabled = on; } } drumDeviceInterface mostRecentDrum; public void newDrum(drumDeviceInterface d) { if (mostRecentDrum != null) mostRecentDrum.displayDrumsticks(false); mostRecentDrum = d; d.displayDrumsticks(true); } public void setGlowLevel(float t) { glowVal = t; PlayerPrefs.SetFloat("glowVal", glowVal); mainGlowShader.bloomIntensity = Mathf.Lerp(0, .05f, t); } public bool tooltipsOn = true; public bool toggleTooltips() { tooltipsOn = !tooltipsOn; touchpad[] pads = FindObjectsOfType<touchpad>(); for (int i = 0; i < pads.Length; i++) { pads[i].buttonContainers[0].SetActive(tooltipsOn); } tooltips[] tips = FindObjectsOfType<tooltips>(); for (int i = 0; i < tips.Length; i++) { tips[i].ShowTooltips(tooltipsOn); } return tooltipsOn; } public bool examplesOn = true; public bool toggleExamples() { examplesOn = !examplesOn; exampleSetups.SetActive(examplesOn); if (!examplesOn) { GameObject prevParent = GameObject.Find("exampleParent"); if (prevParent != null) Destroy(prevParent); } return examplesOn; } public bool dialUsed = false; public void MicChange(int val) { curMic = val; } public void MuteBackgroundSFX(bool mute) { PlayerPrefs.SetInt("envSound", mute ? 0 : 1); if (mute) { backgroundAudio.volume = 0; } else backgroundAudio.volume = .02f; } void beatUpdateEventLocal(float t) { } void beatResetEventLocal() { } public void setBPM(float b) { bpm = Mathf.RoundToInt(b); measurePeriod = 480f / bpm; _measurePhase = curCycle * measurePeriod; } public void resetClock() { _measurePhase = 0; curCycle = 0; beatResetEvent(); } bool beatUpdateRunning = true; public void toggleBeatUpdate(bool on) { beatUpdateRunning = on; } int lastBeat = -1; void Update() { if (lastBeat != Mathf.FloorToInt(curCycle * 8f)) { metronomeClick.Play(); lastBeat = Mathf.FloorToInt(curCycle * 8f); } } private void OnAudioFilterRead(float[] buffer, int channels) { if (!beatUpdateRunning) return; double dspTime = AudioSettings.dspTime; for (int i = 0; i < buffer.Length; i += channels) { beatUpdateEvent(curCycle); _measurePhase += _sampleDuration; if (_measurePhase > measurePeriod) _measurePhase -= measurePeriod; curCycle = (float)(_measurePhase / measurePeriod); } } public void openRecordings() { System.Diagnostics.Process.Start("explorer.exe", "/root," + SaveDir + Path.DirectorySeparatorChar + "Samples" + Path.DirectorySeparatorChar + "Recordings" + Path.DirectorySeparatorChar); } public void openSavedScenes() { System.Diagnostics.Process.Start("explorer.exe", "/root," + SaveDir + Path.DirectorySeparatorChar + "Saves" + Path.DirectorySeparatorChar); } public void openVideoTutorials() { Application.OpenURL("https://www.youtube.com/playlist?list=PL9oPBUaRjJEwjy7glYUvOMqw66QrtTxZD"); } public string GetFileURL(string path) { return (new System.Uri(path)).AbsoluteUri; } public enum BinauralMode { None, Speaker, All }; public BinauralMode BinauralSetting = BinauralMode.None; public void updateBinaural(int num) { if (BinauralSetting == (BinauralMode)num) { return; } BinauralSetting = (BinauralMode)num; speakerDeviceInterface[] standaloneSpeakers = FindObjectsOfType<speakerDeviceInterface>(); for (int i = 0; i < standaloneSpeakers.Length; i++) { if (BinauralSetting == BinauralMode.None) standaloneSpeakers[i].audio.spatialize = false; else standaloneSpeakers[i].audio.spatialize = true; } embeddedSpeaker[] embeddedSpeakers = FindObjectsOfType<embeddedSpeaker>(); for (int i = 0; i < embeddedSpeakers.Length; i++) { if (BinauralSetting == BinauralMode.All) embeddedSpeakers[i].audio.spatialize = true; else embeddedSpeakers[i].audio.spatialize = false; } } public enum WireMode { Curved, Straight, Invisible }; public WireMode WireSetting = WireMode.Curved; public void updateWireSetting(int num) { if (WireSetting == (WireMode)num) { return; } WireSetting = (WireMode)num; omniPlug[] plugs = FindObjectsOfType<omniPlug>(); for (int i = 0; i < plugs.Length; i++) { plugs[i].updateLineType(WireSetting); } } }
#region --- License --- /* Copyright (c) 2006 - 2008 The Open Toolkit library. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.Runtime.InteropServices; using System.ComponentModel; namespace Duality { /// <summary> /// Represents a Quaternion. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct Quaternion : IEquatable<Quaternion> { /// <summary> /// Defines the identity quaternion. /// </summary> public static readonly Quaternion Identity = new Quaternion(0, 0, 0, 1); private Vector3 xyz; private float w; /// <summary> /// Gets or sets an OpenTK.Vector3 with the X, Y and Z components of this instance. /// </summary> public Vector3 Xyz { get { return this.xyz; } set { this.xyz = value; } } /// <summary> /// Gets or sets the X component of this instance. /// </summary> public float X { get { return this.xyz.X; } set { this.xyz.X = value; } } /// <summary> /// Gets or sets the Y component of this instance. /// </summary> public float Y { get { return this.xyz.Y; } set { this.xyz.Y = value; } } /// <summary> /// Gets or sets the Z component of this instance. /// </summary> public float Z { get { return this.xyz.Z; } set { this.xyz.Z = value; } } /// <summary> /// Gets or sets the W component of this instance. /// </summary> public float W { get { return this.w; } set { this.w = value; } } /// <summary> /// Gets the length (magnitude) of the quaternion. /// </summary> /// <seealso cref="LengthSquared"/> public float Length { get { return (float)System.Math.Sqrt(this.W * this.W + this.Xyz.LengthSquared); } } /// <summary> /// Gets the square of the quaternion length (magnitude). /// </summary> public float LengthSquared { get { return this.W * this.W + this.Xyz.LengthSquared; } } /// <summary> /// Construct a new Quaternion from vector and w components /// </summary> /// <param name="v">The vector part</param> /// <param name="w">The w part</param> public Quaternion(Vector3 v, float w) { this.xyz = v; this.w = w; } /// <summary> /// Construct a new Quaternion /// </summary> /// <param name="x">The x component</param> /// <param name="y">The y component</param> /// <param name="z">The z component</param> /// <param name="w">The w component</param> public Quaternion(float x, float y, float z, float w) : this(new Vector3(x, y, z), w) { } /// <summary> /// Convert the current quaternion to axis angle representation /// </summary> /// <param name="axis">The resultant axis</param> /// <param name="angle">The resultant angle</param> public void ToAxisAngle(out Vector3 axis, out float angle) { Vector4 result = ToAxisAngle(); axis = result.Xyz; angle = result.W; } /// <summary> /// Convert this instance to an axis-angle representation. /// </summary> /// <returns>A Vector4 that is the axis-angle representation of this quaternion.</returns> public Vector4 ToAxisAngle() { Quaternion q = this; if (Math.Abs(q.W) > 1.0f) q.Normalize(); Vector4 result = new Vector4(); result.W = 2.0f * (float)System.Math.Acos(q.W); // angle float den = (float)System.Math.Sqrt(1.0 - q.W * q.W); if (den > 0.0001f) { result.Xyz = q.Xyz / den; } else { // This occurs when the angle is zero. // Not a problem: just set an arbitrary normalized axis. result.Xyz = Vector3.UnitX; } return result; } /// <summary> /// Reverses the rotation angle of this Quaterniond. /// </summary> public void Invert() { this.W = -this.W; } /// <summary> /// Scales the Quaternion to unit length. /// </summary> public void Normalize() { float scale = 1.0f / this.Length; this.Xyz *= scale; this.W *= scale; } /// <summary> /// Inverts the Vector3 component of this Quaternion. /// </summary> public void Conjugate() { this.Xyz = -this.Xyz; } /// <summary> /// Returns a copy of the Quaternion scaled to unit length. /// </summary> public Quaternion Normalized() { Quaternion q = this; q.Normalize(); return q; } /// <summary> /// Returns a copy of this Quaterniond with its rotation angle reversed. /// </summary> public Quaternion Inverted() { var q = this; q.Invert(); return q; } /// <summary> /// Add two quaternions /// </summary> /// <param name="left">The first operand</param> /// <param name="right">The second operand</param> /// <returns>The result of the addition</returns> public static Quaternion Add(Quaternion left, Quaternion right) { return new Quaternion( left.Xyz + right.Xyz, left.W + right.W); } /// <summary> /// Add two quaternions /// </summary> /// <param name="left">The first operand</param> /// <param name="right">The second operand</param> /// <param name="result">The result of the addition</param> public static void Add(ref Quaternion left, ref Quaternion right, out Quaternion result) { result = new Quaternion( left.Xyz + right.Xyz, left.W + right.W); } /// <summary> /// Subtracts two instances. /// </summary> /// <param name="left">The left instance.</param> /// <param name="right">The right instance.</param> /// <returns>The result of the operation.</returns> public static Quaternion Sub(Quaternion left, Quaternion right) { return new Quaternion( left.Xyz - right.Xyz, left.W - right.W); } /// <summary> /// Subtracts two instances. /// </summary> /// <param name="left">The left instance.</param> /// <param name="right">The right instance.</param> /// <param name="result">The result of the operation.</param> public static void Sub(ref Quaternion left, ref Quaternion right, out Quaternion result) { result = new Quaternion( left.Xyz - right.Xyz, left.W - right.W); } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>A new instance containing the result of the calculation.</returns> public static Quaternion Multiply(Quaternion left, Quaternion right) { Quaternion result; Multiply(ref left, ref right, out result); return result; } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <param name="result">A new instance containing the result of the calculation.</param> public static void Multiply(ref Quaternion left, ref Quaternion right, out Quaternion result) { result = new Quaternion( right.W * left.Xyz + left.W * right.Xyz + Vector3.Cross(left.Xyz, right.Xyz), left.W * right.W - Vector3.Dot(left.Xyz, right.Xyz)); } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="quaternion">The instance.</param> /// <param name="scale">The scalar.</param> /// <param name="result">A new instance containing the result of the calculation.</param> public static void Multiply(ref Quaternion quaternion, float scale, out Quaternion result) { result = new Quaternion(quaternion.X * scale, quaternion.Y * scale, quaternion.Z * scale, quaternion.W * scale); } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="quaternion">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>A new instance containing the result of the calculation.</returns> public static Quaternion Multiply(Quaternion quaternion, float scale) { return new Quaternion(quaternion.X * scale, quaternion.Y * scale, quaternion.Z * scale, quaternion.W * scale); } /// <summary> /// Get the conjugate of the given quaternion /// </summary> /// <param name="q">The quaternion</param> /// <returns>The conjugate of the given quaternion</returns> public static Quaternion Conjugate(Quaternion q) { return new Quaternion(-q.Xyz, q.W); } /// <summary> /// Get the conjugate of the given quaternion /// </summary> /// <param name="q">The quaternion</param> /// <param name="result">The conjugate of the given quaternion</param> public static void Conjugate(ref Quaternion q, out Quaternion result) { result = new Quaternion(-q.Xyz, q.W); } /// <summary> /// Get the inverse of the given quaternion /// </summary> /// <param name="q">The quaternion to invert</param> /// <returns>The inverse of the given quaternion</returns> public static Quaternion Invert(Quaternion q) { Quaternion result; Invert(ref q, out result); return result; } /// <summary> /// Get the inverse of the given quaternion /// </summary> /// <param name="q">The quaternion to invert</param> /// <param name="result">The inverse of the given quaternion</param> public static void Invert(ref Quaternion q, out Quaternion result) { float lengthSq = q.LengthSquared; if (lengthSq != 0.0) { float i = 1.0f / lengthSq; result = new Quaternion(q.Xyz * -i, q.W * i); } else { result = q; } } /// <summary> /// Scale the given quaternion to unit length /// </summary> /// <param name="q">The quaternion to normalize</param> /// <returns>The normalized quaternion</returns> public static Quaternion Normalize(Quaternion q) { Quaternion result; Normalize(ref q, out result); return result; } /// <summary> /// Scale the given quaternion to unit length /// </summary> /// <param name="q">The quaternion to normalize</param> /// <param name="result">The normalized quaternion</param> public static void Normalize(ref Quaternion q, out Quaternion result) { float scale = 1.0f / q.Length; result = new Quaternion(q.Xyz * scale, q.W * scale); } /// <summary> /// Build a quaternion from the given axis and angle /// </summary> /// <param name="axis">The axis to rotate about</param> /// <param name="angle">The rotation angle in radians</param> /// <returns>The equivalent quaternion</returns> public static Quaternion FromAxisAngle(Vector3 axis, float angle) { if (axis.LengthSquared == 0.0f) return Identity; Quaternion result = Identity; angle *= 0.5f; axis.Normalize(); result.Xyz = axis * (float)System.Math.Sin(angle); result.W = (float)System.Math.Cos(angle); return Normalize(result); } /// <summary> /// Builds a quaternion from the given rotation matrix /// </summary> /// <param name="matrix">A rotation matrix</param> /// <returns>The equivalent quaternion</returns> public static Quaternion FromMatrix(Matrix3 matrix) { Quaternion result; FromMatrix(ref matrix, out result); return result; } /// <summary> /// Builds a quaternion from the given rotation matrix /// </summary> /// <param name="matrix">A rotation matrix</param> /// <param name="result">The equivalent quaternion</param> public static void FromMatrix(ref Matrix3 matrix, out Quaternion result) { float trace = matrix.Trace; if (trace > 0) { float s = (float)Math.Sqrt(trace + 1) * 2; float invS = 1f / s; result.w = s * 0.25f; result.xyz.X = (matrix.Row2.Y - matrix.Row1.Z) * invS; result.xyz.Y = (matrix.Row0.Z - matrix.Row2.X) * invS; result.xyz.Z = (matrix.Row1.X - matrix.Row0.Y) * invS; } else { float m00 = matrix.Row0.X, m11 = matrix.Row1.Y, m22 = matrix.Row2.Z; if (m00 > m11 && m00 > m22) { float s = (float)Math.Sqrt(1 + m00 - m11 - m22) * 2; float invS = 1f / s; result.w = (matrix.Row2.Y - matrix.Row1.Z) * invS; result.xyz.X = s * 0.25f; result.xyz.Y = (matrix.Row0.Y + matrix.Row1.X) * invS; result.xyz.Z = (matrix.Row0.Z + matrix.Row2.X) * invS; } else if (m11 > m22) { float s = (float)Math.Sqrt(1 + m11 - m00 - m22) * 2; float invS = 1f / s; result.w = (matrix.Row0.Z - matrix.Row2.X) * invS; result.xyz.X = (matrix.Row0.Y + matrix.Row1.X) * invS; result.xyz.Y = s * 0.25f; result.xyz.Z = (matrix.Row1.Z + matrix.Row2.Y) * invS; } else { float s = (float)Math.Sqrt(1 + m22 - m00 - m11) * 2; float invS = 1f / s; result.w = (matrix.Row1.X - matrix.Row0.Y) * invS; result.xyz.X = (matrix.Row0.Z + matrix.Row2.X) * invS; result.xyz.Y = (matrix.Row1.Z + matrix.Row2.Y) * invS; result.xyz.Z = s * 0.25f; } } } /// <summary> /// Do Spherical linear interpolation between two quaternions /// </summary> /// <param name="q1">The first quaternion</param> /// <param name="q2">The second quaternion</param> /// <param name="blend">The blend factor</param> /// <returns>A smooth blend between the given quaternions</returns> public static Quaternion Slerp(Quaternion q1, Quaternion q2, float blend) { // if either input is zero, return the other. if (q1.LengthSquared == 0.0f) { if (q2.LengthSquared == 0.0f) { return Identity; } return q2; } else if (q2.LengthSquared == 0.0f) { return q1; } float cosHalfAngle = q1.W * q2.W + Vector3.Dot(q1.Xyz, q2.Xyz); if (cosHalfAngle >= 1.0f || cosHalfAngle <= -1.0f) { // angle = 0.0f, so just return one input. return q1; } else if (cosHalfAngle < 0.0f) { q2.Xyz = -q2.Xyz; q2.W = -q2.W; cosHalfAngle = -cosHalfAngle; } float blendA; float blendB; if (cosHalfAngle < 0.99f) { // do proper slerp for big angles float halfAngle = (float)System.Math.Acos(cosHalfAngle); float sinHalfAngle = (float)System.Math.Sin(halfAngle); float oneOverSinHalfAngle = 1.0f / sinHalfAngle; blendA = (float)System.Math.Sin(halfAngle * (1.0f - blend)) * oneOverSinHalfAngle; blendB = (float)System.Math.Sin(halfAngle * blend) * oneOverSinHalfAngle; } else { // do lerp if angle is really small. blendA = 1.0f - blend; blendB = blend; } Quaternion result = new Quaternion(blendA * q1.Xyz + blendB * q2.Xyz, blendA * q1.W + blendB * q2.W); if (result.LengthSquared > 0.0f) return Normalize(result); else return Identity; } /// <summary> /// Adds two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>The result of the calculation.</returns> public static Quaternion operator +(Quaternion left, Quaternion right) { left.Xyz += right.Xyz; left.W += right.W; return left; } /// <summary> /// Subtracts two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>The result of the calculation.</returns> public static Quaternion operator -(Quaternion left, Quaternion right) { left.Xyz -= right.Xyz; left.W -= right.W; return left; } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>The result of the calculation.</returns> public static Quaternion operator *(Quaternion left, Quaternion right) { Multiply(ref left, ref right, out left); return left; } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="quaternion">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>A new instance containing the result of the calculation.</returns> public static Quaternion operator *(Quaternion quaternion, float scale) { Multiply(ref quaternion, scale, out quaternion); return quaternion; } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="quaternion">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>A new instance containing the result of the calculation.</returns> public static Quaternion operator *(float scale, Quaternion quaternion) { return new Quaternion(quaternion.X * scale, quaternion.Y * scale, quaternion.Z * scale, quaternion.W * scale); } /// <summary> /// Compares two instances for equality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left equals right; false otherwise.</returns> public static bool operator ==(Quaternion left, Quaternion right) { return left.Equals(right); } /// <summary> /// Compares two instances for inequality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left does not equal right; false otherwise.</returns> public static bool operator !=(Quaternion left, Quaternion right) { return !left.Equals(right); } /// <summary> /// Returns a System.String that represents the current Quaternion. /// </summary> public override string ToString() { return string.Format("V: {0}, W: {1}", this.Xyz, this.W); } /// <summary> /// Compares this object instance to another object for equality. /// </summary> /// <param name="other">The other object to be used in the comparison.</param> /// <returns>True if both objects are Quaternions of equal value. Otherwise it returns false.</returns> public override bool Equals(object other) { if (other is Quaternion == false) return false; return this == (Quaternion)other; } /// <summary> /// Provides the hash code for this object. /// </summary> /// <returns>A hash code formed from the bitwise XOR of this objects members.</returns> public override int GetHashCode() { return this.Xyz.GetHashCode() ^ this.W.GetHashCode(); } /// <summary> /// Compares this Quaternion instance to another Quaternion for equality. /// </summary> /// <param name="other">The other Quaternion to be used in the comparison.</param> /// <returns>True if both instances are equal; false otherwise.</returns> public bool Equals(Quaternion other) { return this.Xyz == other.Xyz && this.W == other.W; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure; using Microsoft.Azure.Management.Network; using Microsoft.Azure.Management.Network.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Network { /// <summary> /// The Network Resource Provider API includes operations for managing the /// subnets for your subscription. /// </summary> internal partial class SubnetOperations : IServiceOperations<NetworkResourceProviderClient>, ISubnetOperations { /// <summary> /// Initializes a new instance of the SubnetOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal SubnetOperations(NetworkResourceProviderClient client) { this._client = client; } private NetworkResourceProviderClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Network.NetworkResourceProviderClient. /// </summary> public NetworkResourceProviderClient Client { get { return this._client; } } /// <summary> /// The Put Subnet operation creates/updates a subnet in thespecified /// virtual network /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// Required. The name of the virtual network. /// </param> /// <param name='subnetName'> /// Required. The name of the subnet. /// </param> /// <param name='subnetParameters'> /// Required. Parameters supplied to the create/update Subnet operation /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for PutSubnet Api service call /// </returns> public async Task<SubnetPutResponse> BeginCreateOrUpdatingAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (virtualNetworkName == null) { throw new ArgumentNullException("virtualNetworkName"); } if (subnetName == null) { throw new ArgumentNullException("subnetName"); } if (subnetParameters == null) { throw new ArgumentNullException("subnetParameters"); } if (subnetParameters.AddressPrefix == null) { throw new ArgumentNullException("subnetParameters.AddressPrefix"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("subnetName", subnetName); tracingParameters.Add("subnetParameters", subnetParameters); TracingAdapter.Enter(invocationId, this, "BeginCreateOrUpdatingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Network"; url = url + "/virtualnetworks/"; url = url + Uri.EscapeDataString(virtualNetworkName); url = url + "/subnets/"; url = url + Uri.EscapeDataString(subnetName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject subnetJsonFormatValue = new JObject(); requestDoc = subnetJsonFormatValue; JObject propertiesValue = new JObject(); subnetJsonFormatValue["properties"] = propertiesValue; propertiesValue["addressPrefix"] = subnetParameters.AddressPrefix; if (subnetParameters.NetworkSecurityGroup != null) { JObject networkSecurityGroupValue = new JObject(); propertiesValue["networkSecurityGroup"] = networkSecurityGroupValue; if (subnetParameters.NetworkSecurityGroup.Id != null) { networkSecurityGroupValue["id"] = subnetParameters.NetworkSecurityGroup.Id; } } if (subnetParameters.RouteTable != null) { JObject routeTableValue = new JObject(); propertiesValue["routeTable"] = routeTableValue; if (subnetParameters.RouteTable.Id != null) { routeTableValue["id"] = subnetParameters.RouteTable.Id; } } if (subnetParameters.IpConfigurations != null) { if (subnetParameters.IpConfigurations is ILazyCollection == false || ((ILazyCollection)subnetParameters.IpConfigurations).IsInitialized) { JArray ipConfigurationsArray = new JArray(); foreach (ResourceId ipConfigurationsItem in subnetParameters.IpConfigurations) { JObject resourceIdValue = new JObject(); ipConfigurationsArray.Add(resourceIdValue); if (ipConfigurationsItem.Id != null) { resourceIdValue["id"] = ipConfigurationsItem.Id; } } propertiesValue["ipConfigurations"] = ipConfigurationsArray; } } if (subnetParameters.ProvisioningState != null) { propertiesValue["provisioningState"] = subnetParameters.ProvisioningState; } if (subnetParameters.Name != null) { subnetJsonFormatValue["name"] = subnetParameters.Name; } if (subnetParameters.Etag != null) { subnetJsonFormatValue["etag"] = subnetParameters.Etag; } if (subnetParameters.Id != null) { subnetJsonFormatValue["id"] = subnetParameters.Id; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result SubnetPutResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new SubnetPutResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Subnet subnetInstance = new Subnet(); result.Subnet = subnetInstance; JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { JToken addressPrefixValue = propertiesValue2["addressPrefix"]; if (addressPrefixValue != null && addressPrefixValue.Type != JTokenType.Null) { string addressPrefixInstance = ((string)addressPrefixValue); subnetInstance.AddressPrefix = addressPrefixInstance; } JToken networkSecurityGroupValue2 = propertiesValue2["networkSecurityGroup"]; if (networkSecurityGroupValue2 != null && networkSecurityGroupValue2.Type != JTokenType.Null) { ResourceId networkSecurityGroupInstance = new ResourceId(); subnetInstance.NetworkSecurityGroup = networkSecurityGroupInstance; JToken idValue = networkSecurityGroupValue2["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); networkSecurityGroupInstance.Id = idInstance; } } JToken routeTableValue2 = propertiesValue2["routeTable"]; if (routeTableValue2 != null && routeTableValue2.Type != JTokenType.Null) { ResourceId routeTableInstance = new ResourceId(); subnetInstance.RouteTable = routeTableInstance; JToken idValue2 = routeTableValue2["id"]; if (idValue2 != null && idValue2.Type != JTokenType.Null) { string idInstance2 = ((string)idValue2); routeTableInstance.Id = idInstance2; } } JToken ipConfigurationsArray2 = propertiesValue2["ipConfigurations"]; if (ipConfigurationsArray2 != null && ipConfigurationsArray2.Type != JTokenType.Null) { foreach (JToken ipConfigurationsValue in ((JArray)ipConfigurationsArray2)) { ResourceId resourceIdInstance = new ResourceId(); subnetInstance.IpConfigurations.Add(resourceIdInstance); JToken idValue3 = ipConfigurationsValue["id"]; if (idValue3 != null && idValue3.Type != JTokenType.Null) { string idInstance3 = ((string)idValue3); resourceIdInstance.Id = idInstance3; } } } JToken provisioningStateValue = propertiesValue2["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); subnetInstance.ProvisioningState = provisioningStateInstance; } } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); subnetInstance.Name = nameInstance; } JToken etagValue = responseDoc["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); subnetInstance.Etag = etagInstance; } JToken idValue4 = responseDoc["id"]; if (idValue4 != null && idValue4.Type != JTokenType.Null) { string idInstance4 = ((string)idValue4); subnetInstance.Id = idInstance4; } JToken errorValue = responseDoc["error"]; if (errorValue != null && errorValue.Type != JTokenType.Null) { Error errorInstance = new Error(); result.Error = errorInstance; JToken codeValue = errorValue["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = errorValue["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = errorValue["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } JToken detailsArray = errorValue["details"]; if (detailsArray != null && detailsArray.Type != JTokenType.Null) { foreach (JToken detailsValue in ((JArray)detailsArray)) { ErrorDetails errorDetailsInstance = new ErrorDetails(); errorInstance.Details.Add(errorDetailsInstance); JToken codeValue2 = detailsValue["code"]; if (codeValue2 != null && codeValue2.Type != JTokenType.Null) { string codeInstance2 = ((string)codeValue2); errorDetailsInstance.Code = codeInstance2; } JToken targetValue2 = detailsValue["target"]; if (targetValue2 != null && targetValue2.Type != JTokenType.Null) { string targetInstance2 = ((string)targetValue2); errorDetailsInstance.Target = targetInstance2; } JToken messageValue2 = detailsValue["message"]; if (messageValue2 != null && messageValue2.Type != JTokenType.Null) { string messageInstance2 = ((string)messageValue2); errorDetailsInstance.Message = messageInstance2; } } } JToken innerErrorValue = errorValue["innerError"]; if (innerErrorValue != null && innerErrorValue.Type != JTokenType.Null) { string innerErrorInstance = ((string)innerErrorValue); errorInstance.InnerError = innerErrorInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Azure-AsyncOperation")) { result.AzureAsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The delete subnet operation deletes the specified subnet. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// Required. The name of the virtual network. /// </param> /// <param name='subnetName'> /// Required. The name of the subnet. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// If the resource provide needs to return an error to any operation, /// it should return the appropriate HTTP error code and a message /// body as can be seen below.The message should be localized per the /// Accept-Language header specified in the original request such /// thatit could be directly be exposed to users /// </returns> public async Task<UpdateOperationResponse> BeginDeletingAsync(string resourceGroupName, string virtualNetworkName, string subnetName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (virtualNetworkName == null) { throw new ArgumentNullException("virtualNetworkName"); } if (subnetName == null) { throw new ArgumentNullException("subnetName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("subnetName", subnetName); TracingAdapter.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Network"; url = url + "/virtualnetworks/"; url = url + Uri.EscapeDataString(virtualNetworkName); url = url + "/subnets/"; url = url + Uri.EscapeDataString(subnetName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result UpdateOperationResponse result = null; // Deserialize Response result = new UpdateOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Azure-AsyncOperation")) { result.AzureAsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Put Subnet operation creates/updates a subnet in thespecified /// virtual network /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// Required. The name of the virtual network. /// </param> /// <param name='subnetName'> /// Required. The name of the subnet. /// </param> /// <param name='subnetParameters'> /// Required. Parameters supplied to the create/update Subnet operation /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async Task<AzureAsyncOperationResponse> CreateOrUpdateAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, CancellationToken cancellationToken) { NetworkResourceProviderClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("subnetName", subnetName); tracingParameters.Add("subnetParameters", subnetParameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); SubnetPutResponse response = await client.Subnets.BeginCreateOrUpdatingAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); AzureAsyncOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != Microsoft.Azure.Management.Network.Models.OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// The delete subnet operation deletes the specified subnet. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// Required. The name of the virtual network. /// </param> /// <param name='subnetName'> /// Required. The name of the subnet. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string virtualNetworkName, string subnetName, CancellationToken cancellationToken) { NetworkResourceProviderClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("subnetName", subnetName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); UpdateOperationResponse response = await client.Subnets.BeginDeletingAsync(resourceGroupName, virtualNetworkName, subnetName, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); AzureAsyncOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != Microsoft.Azure.Management.Network.Models.OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// The Get subnet operation retreives information about the specified /// subnet. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// Required. The name of the virtual network. /// </param> /// <param name='subnetName'> /// Required. The name of the subnet. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for GetSubnet Api service call /// </returns> public async Task<SubnetGetResponse> GetAsync(string resourceGroupName, string virtualNetworkName, string subnetName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (virtualNetworkName == null) { throw new ArgumentNullException("virtualNetworkName"); } if (subnetName == null) { throw new ArgumentNullException("subnetName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("subnetName", subnetName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Network"; url = url + "/virtualnetworks/"; url = url + Uri.EscapeDataString(virtualNetworkName); url = url + "/subnets/"; url = url + Uri.EscapeDataString(subnetName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result SubnetGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new SubnetGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Subnet subnetInstance = new Subnet(); result.Subnet = subnetInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JToken addressPrefixValue = propertiesValue["addressPrefix"]; if (addressPrefixValue != null && addressPrefixValue.Type != JTokenType.Null) { string addressPrefixInstance = ((string)addressPrefixValue); subnetInstance.AddressPrefix = addressPrefixInstance; } JToken networkSecurityGroupValue = propertiesValue["networkSecurityGroup"]; if (networkSecurityGroupValue != null && networkSecurityGroupValue.Type != JTokenType.Null) { ResourceId networkSecurityGroupInstance = new ResourceId(); subnetInstance.NetworkSecurityGroup = networkSecurityGroupInstance; JToken idValue = networkSecurityGroupValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); networkSecurityGroupInstance.Id = idInstance; } } JToken routeTableValue = propertiesValue["routeTable"]; if (routeTableValue != null && routeTableValue.Type != JTokenType.Null) { ResourceId routeTableInstance = new ResourceId(); subnetInstance.RouteTable = routeTableInstance; JToken idValue2 = routeTableValue["id"]; if (idValue2 != null && idValue2.Type != JTokenType.Null) { string idInstance2 = ((string)idValue2); routeTableInstance.Id = idInstance2; } } JToken ipConfigurationsArray = propertiesValue["ipConfigurations"]; if (ipConfigurationsArray != null && ipConfigurationsArray.Type != JTokenType.Null) { foreach (JToken ipConfigurationsValue in ((JArray)ipConfigurationsArray)) { ResourceId resourceIdInstance = new ResourceId(); subnetInstance.IpConfigurations.Add(resourceIdInstance); JToken idValue3 = ipConfigurationsValue["id"]; if (idValue3 != null && idValue3.Type != JTokenType.Null) { string idInstance3 = ((string)idValue3); resourceIdInstance.Id = idInstance3; } } } JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); subnetInstance.ProvisioningState = provisioningStateInstance; } } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); subnetInstance.Name = nameInstance; } JToken etagValue = responseDoc["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); subnetInstance.Etag = etagInstance; } JToken idValue4 = responseDoc["id"]; if (idValue4 != null && idValue4.Type != JTokenType.Null) { string idInstance4 = ((string)idValue4); subnetInstance.Id = idInstance4; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The List subnets opertion retrieves all the subnets in a virtual /// network. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// Required. The name of the virtual network. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for ListSubnets Api service callRetrieves all subnet that /// belongs to a virtual network /// </returns> public async Task<SubnetListResponse> ListAsync(string resourceGroupName, string virtualNetworkName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (virtualNetworkName == null) { throw new ArgumentNullException("virtualNetworkName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Network"; url = url + "/virtualnetworks/"; url = url + Uri.EscapeDataString(virtualNetworkName); url = url + "/subnets"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result SubnetListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new SubnetListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Subnet subnetJsonFormatInstance = new Subnet(); result.Subnets.Add(subnetJsonFormatInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JToken addressPrefixValue = propertiesValue["addressPrefix"]; if (addressPrefixValue != null && addressPrefixValue.Type != JTokenType.Null) { string addressPrefixInstance = ((string)addressPrefixValue); subnetJsonFormatInstance.AddressPrefix = addressPrefixInstance; } JToken networkSecurityGroupValue = propertiesValue["networkSecurityGroup"]; if (networkSecurityGroupValue != null && networkSecurityGroupValue.Type != JTokenType.Null) { ResourceId networkSecurityGroupInstance = new ResourceId(); subnetJsonFormatInstance.NetworkSecurityGroup = networkSecurityGroupInstance; JToken idValue = networkSecurityGroupValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); networkSecurityGroupInstance.Id = idInstance; } } JToken routeTableValue = propertiesValue["routeTable"]; if (routeTableValue != null && routeTableValue.Type != JTokenType.Null) { ResourceId routeTableInstance = new ResourceId(); subnetJsonFormatInstance.RouteTable = routeTableInstance; JToken idValue2 = routeTableValue["id"]; if (idValue2 != null && idValue2.Type != JTokenType.Null) { string idInstance2 = ((string)idValue2); routeTableInstance.Id = idInstance2; } } JToken ipConfigurationsArray = propertiesValue["ipConfigurations"]; if (ipConfigurationsArray != null && ipConfigurationsArray.Type != JTokenType.Null) { foreach (JToken ipConfigurationsValue in ((JArray)ipConfigurationsArray)) { ResourceId resourceIdInstance = new ResourceId(); subnetJsonFormatInstance.IpConfigurations.Add(resourceIdInstance); JToken idValue3 = ipConfigurationsValue["id"]; if (idValue3 != null && idValue3.Type != JTokenType.Null) { string idInstance3 = ((string)idValue3); resourceIdInstance.Id = idInstance3; } } } JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); subnetJsonFormatInstance.ProvisioningState = provisioningStateInstance; } } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); subnetJsonFormatInstance.Name = nameInstance; } JToken etagValue = valueValue["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); subnetJsonFormatInstance.Etag = etagInstance; } JToken idValue4 = valueValue["id"]; if (idValue4 != null && idValue4.Type != JTokenType.Null) { string idInstance4 = ((string)idValue4); subnetJsonFormatInstance.Id = idInstance4; } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// 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.Composition; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { [ExportWorkspaceServiceFactory(typeof(ITemporaryStorageService), ServiceLayer.Host), Shared] internal partial class TemporaryStorageServiceFactory : IWorkspaceServiceFactory { public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { var textFactory = workspaceServices.GetService<ITextFactoryService>(); return new TemporaryStorageService(textFactory); } /// <summary> /// Temporarily stores text and streams in memory mapped files. /// </summary> internal class TemporaryStorageService : ITemporaryStorageService { private readonly ITextFactoryService _textFactory; private readonly MemoryMappedFileManager _memoryMappedFileManager = new MemoryMappedFileManager(); public TemporaryStorageService(ITextFactoryService textFactory) { _textFactory = textFactory; } public ITemporaryTextStorage CreateTemporaryTextStorage(CancellationToken cancellationToken) { return new TemporaryTextStorage(this); } public ITemporaryStreamStorage CreateTemporaryStreamStorage(CancellationToken cancellationToken) { return new TemporaryStreamStorage(this); } private class TemporaryTextStorage : ITemporaryTextStorage { private readonly TemporaryStorageService _service; private Encoding _encoding; private MemoryMappedInfo _memoryMappedInfo; public TemporaryTextStorage(TemporaryStorageService service) { _service = service; } public void Dispose() { if (_memoryMappedInfo != null) { // Destructors of SafeHandle and FileStream in MemoryMappedFile // will eventually release resources if this Dispose is not called // explicitly _memoryMappedInfo.Dispose(); _memoryMappedInfo = null; } if (_encoding != null) { _encoding = null; } } public SourceText ReadText(CancellationToken cancellationToken) { if (_memoryMappedInfo == null) { throw new InvalidOperationException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadText, cancellationToken)) { using (var stream = _memoryMappedInfo.CreateReadableStream()) using (var reader = CreateTextReaderFromTemporaryStorage((ISupportDirectMemoryAccess)stream, (int)stream.Length, cancellationToken)) { // we pass in encoding we got from original source text even if it is null. return _service._textFactory.CreateText(reader, _encoding, cancellationToken); } } } public Task<SourceText> ReadTextAsync(CancellationToken cancellationToken) { // There is a reason for implementing it like this: proper async implementation // that reads the underlying memory mapped file stream in an asynchronous fashion // doesn't actually work. Windows doesn't offer // any non-blocking way to read from a memory mapped file; the underlying memcpy // may block as the memory pages back in and that's something you have to live // with. Therefore, any implementation that attempts to use async will still // always be blocking at least one threadpool thread in the memcpy in the case // of a page fault. Therefore, if we're going to be blocking a thread, we should // just block one thread and do the whole thing at once vs. a fake "async" // implementation which will continue to requeue work back to the thread pool. return Task.Factory.StartNew(() => ReadText(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); } public void WriteText(SourceText text, CancellationToken cancellationToken) { if (_memoryMappedInfo != null) { throw new InvalidOperationException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteText, cancellationToken)) { _encoding = text.Encoding; // the method we use to get text out of SourceText uses Unicode (2bytes per char). var size = Encoding.Unicode.GetMaxByteCount(text.Length); _memoryMappedInfo = _service._memoryMappedFileManager.CreateViewInfo(size); // Write the source text out as Unicode. We expect that to be cheap. using (var stream = _memoryMappedInfo.CreateWritableStream()) { using (var writer = new StreamWriter(stream, Encoding.Unicode)) { text.Write(writer, cancellationToken); } } } } public Task WriteTextAsync(SourceText text, CancellationToken cancellationToken = default(CancellationToken)) { // See commentary in ReadTextAsync for why this is implemented this way. return Task.Factory.StartNew(() => WriteText(text, cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); } private unsafe TextReader CreateTextReaderFromTemporaryStorage(ISupportDirectMemoryAccess accessor, int streamLength, CancellationToken cancellationToken) { char* src = (char*)accessor.GetPointer(); // BOM: Unicode, little endian // Skip the BOM when creating the reader Debug.Assert(*src == 0xFEFF); return new DirectMemoryAccessStreamReader(src + 1, streamLength / sizeof(char) - 1); } private unsafe class DirectMemoryAccessStreamReader : TextReader { private char* _position; private readonly char* _end; public DirectMemoryAccessStreamReader(char* src, int length) { Debug.Assert(src != null); Debug.Assert(length >= 0); _position = src; _end = _position + length; } public override int Read() { if (_position >= _end) { return -1; } return *_position++; } public override int Read(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (index < 0 || index >= buffer.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } if (count < 0 || (index + count) > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(count)); } count = Math.Min(count, (int)(_end - _position)); if (count > 0) { Marshal.Copy((IntPtr)_position, buffer, index, count); _position += count; } return count; } } } private class TemporaryStreamStorage : ITemporaryStreamStorage { private readonly TemporaryStorageService _service; private MemoryMappedInfo _memoryMappedInfo; public TemporaryStreamStorage(TemporaryStorageService service) { _service = service; } public void Dispose() { if (_memoryMappedInfo != null) { // Destructors of SafeHandle and FileStream in MemoryMappedFile // will eventually release resources if this Dispose is not called // explicitly _memoryMappedInfo.Dispose(); _memoryMappedInfo = null; } } public Stream ReadStream(CancellationToken cancellationToken) { if (_memoryMappedInfo == null) { throw new InvalidOperationException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadStream, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return _memoryMappedInfo.CreateReadableStream(); } } public Task<Stream> ReadStreamAsync(CancellationToken cancellationToken = default(CancellationToken)) { // See commentary in ReadTextAsync for why this is implemented this way. return Task.Factory.StartNew(() => ReadStream(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); } public void WriteStream(Stream stream, CancellationToken cancellationToken = default(CancellationToken)) { // The Wait() here will not actually block, since with useAsync: false, the // entire operation will already be done when WaitStreamMaybeAsync completes. WriteStreamMaybeAsync(stream, useAsync: false, cancellationToken: cancellationToken).GetAwaiter().GetResult(); } public Task WriteStreamAsync(Stream stream, CancellationToken cancellationToken = default(CancellationToken)) { return WriteStreamMaybeAsync(stream, useAsync: true, cancellationToken: cancellationToken); } private async Task WriteStreamMaybeAsync(Stream stream, bool useAsync, CancellationToken cancellationToken) { if (_memoryMappedInfo != null) { throw new InvalidOperationException(WorkspacesResources.Temporary_storage_cannot_be_written_more_than_once); } if (stream.Length == 0) { throw new ArgumentOutOfRangeException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteStream, cancellationToken)) { var size = stream.Length; _memoryMappedInfo = _service._memoryMappedFileManager.CreateViewInfo(size); using (var viewStream = _memoryMappedInfo.CreateWritableStream()) { var buffer = SharedPools.ByteArray.Allocate(); try { while (true) { int count; if (useAsync) { count = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); } else { count = stream.Read(buffer, 0, buffer.Length); } if (count == 0) { break; } viewStream.Write(buffer, 0, count); } } finally { SharedPools.ByteArray.Free(buffer); } } } } } } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Transactions; using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli.CommandLine; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.ShellShim; using Microsoft.DotNet.ToolPackage; using Microsoft.DotNet.Tools.Tool.Install; using Microsoft.DotNet.Tools.Tool.Uninstall; using Microsoft.Extensions.EnvironmentAbstractions; namespace Microsoft.DotNet.Tools.Tool.Update { internal delegate IShellShimRepository CreateShellShimRepository(DirectoryPath? nonGlobalLocation = null); internal delegate (IToolPackageStore, IToolPackageInstaller) CreateToolPackageStoreAndInstaller( DirectoryPath? nonGlobalLocation = null); internal class ToolUpdateCommand : CommandBase { private readonly IReporter _reporter; private readonly IReporter _errorReporter; private readonly CreateShellShimRepository _createShellShimRepository; private readonly CreateToolPackageStoreAndInstaller _createToolPackageStoreAndInstaller; private readonly PackageId _packageId; private readonly string _configFilePath; private readonly string _framework; private readonly string[] _additionalFeeds; private readonly bool _global; private readonly string _verbosity; private readonly string _toolPath; public ToolUpdateCommand(AppliedOption appliedCommand, ParseResult parseResult, CreateToolPackageStoreAndInstaller createToolPackageStoreAndInstaller = null, CreateShellShimRepository createShellShimRepository = null, IReporter reporter = null) : base(parseResult) { if (appliedCommand == null) { throw new ArgumentNullException(nameof(appliedCommand)); } _packageId = new PackageId(appliedCommand.Arguments.Single()); _configFilePath = appliedCommand.ValueOrDefault<string>("configfile"); _framework = appliedCommand.ValueOrDefault<string>("framework"); _additionalFeeds = appliedCommand.ValueOrDefault<string[]>("source-feed"); _global = appliedCommand.ValueOrDefault<bool>("global"); _verbosity = appliedCommand.SingleArgumentOrDefault("verbosity"); _toolPath = appliedCommand.SingleArgumentOrDefault("tool-path"); _createToolPackageStoreAndInstaller = createToolPackageStoreAndInstaller ?? ToolPackageFactory.CreateToolPackageStoreAndInstaller; _createShellShimRepository = createShellShimRepository ?? ShellShimRepositoryFactory.CreateShellShimRepository; _reporter = (reporter ?? Reporter.Output); _errorReporter = (reporter ?? Reporter.Error); } public override int Execute() { ValidateArguments(); DirectoryPath? toolPath = null; if (_toolPath != null) { toolPath = new DirectoryPath(_toolPath); } (IToolPackageStore toolPackageStore, IToolPackageInstaller toolPackageInstaller) = _createToolPackageStoreAndInstaller(toolPath); IShellShimRepository shellShimRepository = _createShellShimRepository(toolPath); IToolPackage oldPackage; try { oldPackage = toolPackageStore.EnumeratePackageVersions(_packageId).SingleOrDefault(); if (oldPackage == null) { throw new GracefulException( messages: new[] { string.Format( LocalizableStrings.ToolNotInstalled, _packageId), }, isUserError: false); } } catch (InvalidOperationException) { throw new GracefulException( messages: new[] { string.Format( LocalizableStrings.ToolHasMultipleVersionsInstalled, _packageId), }, isUserError: false); } FilePath? configFile = null; if (_configFilePath != null) { configFile = new FilePath(_configFilePath); } using (var scope = new TransactionScope( TransactionScopeOption.Required, TimeSpan.Zero)) { RunWithHandlingUninstallError(() => { foreach (CommandSettings command in oldPackage.Commands) { shellShimRepository.RemoveShim(command.Name); } oldPackage.Uninstall(); }); RunWithHandlingInstallError(() => { IToolPackage newInstalledPackage = toolPackageInstaller.InstallPackage( packageId: _packageId, targetFramework: _framework, nugetConfig: configFile, additionalFeeds: _additionalFeeds, verbosity: _verbosity); foreach (CommandSettings command in newInstalledPackage.Commands) { shellShimRepository.CreateShim(command.Executable, command.Name); } PrintSuccessMessage(oldPackage, newInstalledPackage); }); scope.Complete(); } return 0; } private void ValidateArguments() { if (string.IsNullOrWhiteSpace(_toolPath) && !_global) { throw new GracefulException( LocalizableStrings.UpdateToolCommandNeedGlobalOrToolPath); } if (!string.IsNullOrWhiteSpace(_toolPath) && _global) { throw new GracefulException( LocalizableStrings.UpdateToolCommandInvalidGlobalAndToolPath); } if (_configFilePath != null && !File.Exists(_configFilePath)) { throw new GracefulException( string.Format( LocalizableStrings.NuGetConfigurationFileDoesNotExist, Path.GetFullPath(_configFilePath))); } } private void RunWithHandlingInstallError(Action installAction) { try { installAction(); } catch (Exception ex) when (InstallToolCommandLowLevelErrorConverter.ShouldConvertToUserFacingError(ex)) { var message = new List<string> { string.Format(LocalizableStrings.UpdateToolFailed, _packageId) }; message.AddRange( InstallToolCommandLowLevelErrorConverter.GetUserFacingMessages(ex, _packageId)); throw new GracefulException( messages: message, verboseMessages: new[] { ex.ToString() }, isUserError: false); } } private void RunWithHandlingUninstallError(Action uninstallAction) { try { uninstallAction(); } catch (Exception ex) when (ToolUninstallCommandLowLevelErrorConverter.ShouldConvertToUserFacingError(ex)) { var message = new List<string> { string.Format(LocalizableStrings.UpdateToolFailed, _packageId) }; message.AddRange( ToolUninstallCommandLowLevelErrorConverter.GetUserFacingMessages(ex, _packageId)); throw new GracefulException( messages: message, verboseMessages: new[] { ex.ToString() }, isUserError: false); } } private void PrintSuccessMessage(IToolPackage oldPackage, IToolPackage newInstalledPackage) { if (oldPackage.Version != newInstalledPackage.Version) { _reporter.WriteLine( string.Format( LocalizableStrings.UpdateSucceeded, newInstalledPackage.Id, oldPackage.Version.ToNormalizedString(), newInstalledPackage.Version.ToNormalizedString()).Green()); } else { _reporter.WriteLine( string.Format( LocalizableStrings.UpdateSucceededVersionNoChange, newInstalledPackage.Id, newInstalledPackage.Version).Green()); } } } }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Threading; using System.Xml; using ServiceStack.Text; namespace ServiceStack { public static class PlatformExtensions { [Obsolete("Use type.IsInterface")] public static bool IsInterface(this Type type) => type.IsInterface; [Obsolete("Use type.IsArray")] public static bool IsArray(this Type type) => type.IsArray; [Obsolete("Use type.IsValueType")] public static bool IsValueType(this Type type) => type.IsValueType; [Obsolete("Use type.IsGenericType")] public static bool IsGeneric(this Type type) => type.IsGenericType; [Obsolete("Use type.BaseType")] public static Type BaseType(this Type type) => type.BaseType; [Obsolete("Use pi.ReflectedType")] public static Type ReflectedType(this PropertyInfo pi) => pi.ReflectedType; [Obsolete("Use fi.ReflectedType")] public static Type ReflectedType(this FieldInfo fi) => fi.ReflectedType; [Obsolete("Use type.GetGenericTypeDefinition()")] public static Type GenericTypeDefinition(this Type type) => type.GetGenericTypeDefinition(); [Obsolete("Use type.GetInterfaces()")] public static Type[] GetTypeInterfaces(this Type type) => type.GetInterfaces(); [Obsolete("Use type.GetGenericArguments()")] public static Type[] GetTypeGenericArguments(this Type type) => type.GetGenericArguments(); [Obsolete("Use type.GetConstructor(Type.EmptyTypes)")] public static ConstructorInfo GetEmptyConstructor(this Type type) => type.GetConstructor(Type.EmptyTypes); [Obsolete("Use type.GetConstructors()")] public static IEnumerable<ConstructorInfo> GetAllConstructors(this Type type) => type.GetConstructors(); [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static PropertyInfo[] GetTypesPublicProperties(this Type subType) { return subType.GetProperties( BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static PropertyInfo[] GetTypesProperties(this Type subType) { return subType.GetProperties( BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); } [Obsolete("Use type.Assembly")] public static Assembly GetAssembly(this Type type) => type.Assembly; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static FieldInfo[] Fields(this Type type) { return type.GetFields( BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static PropertyInfo[] Properties(this Type type) { return type.GetProperties( BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static FieldInfo[] GetAllFields(this Type type) => type.IsInterface ? TypeConstants.EmptyFieldInfoArray : type.Fields(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static FieldInfo[] GetPublicFields(this Type type) => type.IsInterface ? TypeConstants.EmptyFieldInfoArray : type.GetFields(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance).ToArray(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static MemberInfo[] GetPublicMembers(this Type type) => type.GetMembers(BindingFlags.Public | BindingFlags.Instance); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static MemberInfo[] GetAllPublicMembers(this Type type) => type.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static MethodInfo GetStaticMethod(this Type type, string methodName) => type.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static MethodInfo GetInstanceMethod(this Type type, string methodName) => type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); [Obsolete("Use fn.Method")] public static MethodInfo Method(this Delegate fn) => fn.Method; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool HasAttribute<T>(this Type type) => type.AllAttributes().Any(x => x.GetType() == typeof(T)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool HasAttribute<T>(this PropertyInfo pi) => pi.AllAttributes().Any(x => x.GetType() == typeof(T)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool HasAttribute<T>(this FieldInfo fi) => fi.AllAttributes().Any(x => x.GetType() == typeof(T)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool HasAttribute<T>(this MethodInfo mi) => mi.AllAttributes().Any(x => x.GetType() == typeof(T)); private static readonly ConcurrentDictionary<Tuple<MemberInfo,Type>, bool> hasAttributeCache = new ConcurrentDictionary<Tuple<MemberInfo,Type>, bool>(); public static bool HasAttributeCached<T>(this MemberInfo memberInfo) { var key = new Tuple<MemberInfo,Type>(memberInfo, typeof(T)); if (hasAttributeCache.TryGetValue(key , out var hasAttr)) return hasAttr; hasAttr = memberInfo is Type t ? t.AllAttributes().Any(x => x.GetType() == typeof(T)) : memberInfo is PropertyInfo pi ? pi.AllAttributes().Any(x => x.GetType() == typeof(T)) : memberInfo is FieldInfo fi ? fi.AllAttributes().Any(x => x.GetType() == typeof(T)) : memberInfo is MethodInfo mi ? mi.AllAttributes().Any(x => x.GetType() == typeof(T)) : throw new NotSupportedException(memberInfo.GetType().Name); hasAttributeCache[key] = hasAttr; return hasAttr; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool HasAttributeNamed(this Type type, string name) { var normalizedAttr = name.Replace("Attribute", "").ToLower(); return type.AllAttributes().Any(x => x.GetType().Name.Replace("Attribute", "").ToLower() == normalizedAttr); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool HasAttributeNamed(this PropertyInfo pi, string name) { var normalizedAttr = name.Replace("Attribute", "").ToLower(); return pi.AllAttributes().Any(x => x.GetType().Name.Replace("Attribute", "").ToLower() == normalizedAttr); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool HasAttributeNamed(this FieldInfo fi, string name) { var normalizedAttr = name.Replace("Attribute", "").ToLower(); return fi.AllAttributes().Any(x => x.GetType().Name.Replace("Attribute", "").ToLower() == normalizedAttr); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool HasAttributeNamed(this MemberInfo mi, string name) { var normalizedAttr = name.Replace("Attribute", "").ToLower(); return mi.AllAttributes().Any(x => x.GetType().Name.Replace("Attribute", "").ToLower() == normalizedAttr); } const string DataContract = "DataContractAttribute"; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsDto(this Type type) { if (type == null) return false; return !Env.IsMono ? type.HasAttribute<DataContractAttribute>() : type.GetCustomAttributes(true).Any(x => x.GetType().Name == DataContract); } [Obsolete("Use pi.GetGetMethod(nonPublic)")] public static MethodInfo PropertyGetMethod(this PropertyInfo pi, bool nonPublic = false) => pi.GetGetMethod(nonPublic); [Obsolete("Use type.GetInterfaces()")] public static Type[] Interfaces(this Type type) => type.GetInterfaces(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static PropertyInfo[] AllProperties(this Type type) => type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); //Should only register Runtime Attributes on StartUp, So using non-ThreadSafe Dictionary is OK static Dictionary<string, List<Attribute>> propertyAttributesMap = new Dictionary<string, List<Attribute>>(); static Dictionary<Type, List<Attribute>> typeAttributesMap = new Dictionary<Type, List<Attribute>>(); public static void ClearRuntimeAttributes() { propertyAttributesMap = new Dictionary<string, List<Attribute>>(); typeAttributesMap = new Dictionary<Type, List<Attribute>>(); } internal static string UniqueKey(this PropertyInfo pi) { if (pi.DeclaringType == null) throw new ArgumentException("Property '{0}' has no DeclaringType".Fmt(pi.Name)); return pi.DeclaringType.Namespace + "." + pi.DeclaringType.Name + "." + pi.Name; } public static Type AddAttributes(this Type type, params Attribute[] attrs) { if (!typeAttributesMap.TryGetValue(type, out var typeAttrs)) typeAttributesMap[type] = typeAttrs = new List<Attribute>(); typeAttrs.AddRange(attrs); return type; } /// <summary> /// Add a Property attribute at runtime. /// <para>Not threadsafe, should only add attributes on Startup.</para> /// </summary> public static PropertyInfo AddAttributes(this PropertyInfo propertyInfo, params Attribute[] attrs) { var key = propertyInfo.UniqueKey(); if (!propertyAttributesMap.TryGetValue(key, out var propertyAttrs)) propertyAttributesMap[key] = propertyAttrs = new List<Attribute>(); propertyAttrs.AddRange(attrs); return propertyInfo; } /// <summary> /// Add a Property attribute at runtime. /// <para>Not threadsafe, should only add attributes on Startup.</para> /// </summary> public static PropertyInfo ReplaceAttribute(this PropertyInfo propertyInfo, Attribute attr) { var key = propertyInfo.UniqueKey(); if (!propertyAttributesMap.TryGetValue(key, out var propertyAttrs)) propertyAttributesMap[key] = propertyAttrs = new List<Attribute>(); propertyAttrs.RemoveAll(x => x.GetType() == attr.GetType()); propertyAttrs.Add(attr); return propertyInfo; } public static List<TAttr> GetAttributes<TAttr>(this PropertyInfo propertyInfo) { return !propertyAttributesMap.TryGetValue(propertyInfo.UniqueKey(), out var propertyAttrs) ? new List<TAttr>() : propertyAttrs.OfType<TAttr>().ToList(); } public static List<Attribute> GetAttributes(this PropertyInfo propertyInfo) { return !propertyAttributesMap.TryGetValue(propertyInfo.UniqueKey(), out var propertyAttrs) ? new List<Attribute>() : propertyAttrs.ToList(); } public static List<Attribute> GetAttributes(this PropertyInfo propertyInfo, Type attrType) { return !propertyAttributesMap.TryGetValue(propertyInfo.UniqueKey(), out var propertyAttrs) ? new List<Attribute>() : propertyAttrs.Where(x => attrType.IsInstanceOf(x.GetType())).ToList(); } public static object[] AllAttributes(this PropertyInfo propertyInfo) { var attrs = propertyInfo.GetCustomAttributes(true); var runtimeAttrs = propertyInfo.GetAttributes(); if (runtimeAttrs.Count == 0) return attrs; runtimeAttrs.AddRange(attrs.Cast<Attribute>()); return runtimeAttrs.Cast<object>().ToArray(); } public static object[] AllAttributes(this PropertyInfo propertyInfo, Type attrType) { var attrs = propertyInfo.GetCustomAttributes(attrType, true); var runtimeAttrs = propertyInfo.GetAttributes(attrType); if (runtimeAttrs.Count == 0) return attrs; runtimeAttrs.AddRange(attrs.Cast<Attribute>()); return runtimeAttrs.Cast<object>().ToArray(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static object[] AllAttributes(this ParameterInfo paramInfo) => paramInfo.GetCustomAttributes(true); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static object[] AllAttributes(this FieldInfo fieldInfo) => fieldInfo.GetCustomAttributes(true); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static object[] AllAttributes(this MemberInfo memberInfo) => memberInfo.GetCustomAttributes(true); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static object[] AllAttributes(this ParameterInfo paramInfo, Type attrType) => paramInfo.GetCustomAttributes(attrType, true); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static object[] AllAttributes(this MemberInfo memberInfo, Type attrType) { var prop = memberInfo as PropertyInfo; return prop != null ? prop.AllAttributes(attrType) : memberInfo.GetCustomAttributes(attrType, true); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static object[] AllAttributes(this FieldInfo fieldInfo, Type attrType) => fieldInfo.GetCustomAttributes(attrType, true); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static object[] AllAttributes(this Type type) => type.GetCustomAttributes(true).Union(type.GetRuntimeAttributes()).ToArray(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static object[] AllAttributes(this Type type, Type attrType) => type.GetCustomAttributes(attrType, true).Union(type.GetRuntimeAttributes(attrType)).ToArray(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static object[] AllAttributes(this Assembly assembly) => assembly.GetCustomAttributes(true).ToArray(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static TAttr[] AllAttributes<TAttr>(this ParameterInfo pi) => pi.AllAttributes(typeof(TAttr)).Cast<TAttr>().ToArray(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static TAttr[] AllAttributes<TAttr>(this MemberInfo mi) => mi.AllAttributes(typeof(TAttr)).Cast<TAttr>().ToArray(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static TAttr[] AllAttributes<TAttr>(this FieldInfo fi) => fi.AllAttributes(typeof(TAttr)).Cast<TAttr>().ToArray(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static TAttr[] AllAttributes<TAttr>(this PropertyInfo pi) => pi.AllAttributes(typeof(TAttr)).Cast<TAttr>().ToArray(); [MethodImpl(MethodImplOptions.AggressiveInlining)] static IEnumerable<T> GetRuntimeAttributes<T>(this Type type) => typeAttributesMap.TryGetValue(type, out var attrs) ? attrs.OfType<T>() : new List<T>(); [MethodImpl(MethodImplOptions.AggressiveInlining)] static IEnumerable<Attribute> GetRuntimeAttributes(this Type type, Type attrType = null) => typeAttributesMap.TryGetValue(type, out var attrs) ? attrs.Where(x => attrType == null || attrType.IsInstanceOf(x.GetType())) : new List<Attribute>(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static TAttr[] AllAttributes<TAttr>(this Type type) { return type.GetCustomAttributes(typeof(TAttr), true) .OfType<TAttr>() .Union(type.GetRuntimeAttributes<TAttr>()) .ToArray(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static TAttr FirstAttribute<TAttr>(this Type type) where TAttr : class { return (TAttr)type.GetCustomAttributes(typeof(TAttr), true) .FirstOrDefault() ?? type.GetRuntimeAttributes<TAttr>().FirstOrDefault(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static TAttribute FirstAttribute<TAttribute>(this MemberInfo memberInfo) { return memberInfo.AllAttributes<TAttribute>().FirstOrDefault(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static TAttribute FirstAttribute<TAttribute>(this ParameterInfo paramInfo) { return paramInfo.AllAttributes<TAttribute>().FirstOrDefault(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static TAttribute FirstAttribute<TAttribute>(this PropertyInfo propertyInfo) { return propertyInfo.AllAttributes<TAttribute>().FirstOrDefault(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Type FirstGenericTypeDefinition(this Type type) { var genericType = type.FirstGenericType(); return genericType != null ? genericType.GetGenericTypeDefinition() : null; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsDynamic(this Assembly assembly) => ReflectionOptimizer.Instance.IsDynamic(assembly); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static MethodInfo GetStaticMethod(this Type type, string methodName, Type[] types) { return types == null ? type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static) : type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static, null, types, null); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static MethodInfo GetMethodInfo(this Type type, string methodName, Type[] types = null) => types == null ? type.GetMethod(methodName) : type.GetMethod(methodName, types); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static object InvokeMethod(this Delegate fn, object instance, object[] parameters = null) => fn.Method.Invoke(instance, parameters ?? new object[] { }); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static FieldInfo GetPublicStaticField(this Type type, string fieldName) => type.GetField(fieldName, BindingFlags.Public | BindingFlags.Static); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Delegate MakeDelegate(this MethodInfo mi, Type delegateType, bool throwOnBindFailure = true) => Delegate.CreateDelegate(delegateType, mi, throwOnBindFailure); [Obsolete("Use type.GetGenericArguments()")] public static Type[] GenericTypeArguments(this Type type) => type.GetGenericArguments(); [Obsolete("Use type.GetConstructors()")] public static ConstructorInfo[] DeclaredConstructors(this Type type) => type.GetConstructors(); [Obsolete("Use type.IsAssignableFrom(fromType)")] public static bool AssignableFrom(this Type type, Type fromType) => type.IsAssignableFrom(fromType); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsStandardClass(this Type type) => type.IsClass && !type.IsAbstract && !type.IsInterface; [Obsolete("Use type.IsAbstract")] public static bool IsAbstract(this Type type) => type.IsAbstract; [Obsolete("Use type.GetProperty(propertyName)")] public static PropertyInfo GetPropertyInfo(this Type type, string propertyName) => type.GetProperty(propertyName); [Obsolete("Use type.GetField(fieldName)")] public static FieldInfo GetFieldInfo(this Type type, string fieldName) => type.GetField(fieldName); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static FieldInfo[] GetWritableFields(this Type type) => type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField); [Obsolete("Use pi.GetSetMethod(nonPublic)")] public static MethodInfo SetMethod(this PropertyInfo pi, bool nonPublic = true) => pi.GetSetMethod(nonPublic); [Obsolete("Use pi.GetGetMethod(nonPublic)")] public static MethodInfo GetMethodInfo(this PropertyInfo pi, bool nonPublic = true) => pi.GetGetMethod(nonPublic); [Obsolete("Use type.IsInstanceOfType(instance)")] public static bool InstanceOfType(this Type type, object instance) => type.IsInstanceOfType(instance); [Obsolete("Use type.IsAssignableFrom(fromType)")] public static bool IsAssignableFromType(this Type type, Type fromType) => type.IsAssignableFrom(fromType); [Obsolete("Use type.IsClass")] public static bool IsClass(this Type type) => type.IsClass; [Obsolete("Use type.IsEnum")] public static bool IsEnum(this Type type) => type.IsEnum; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsEnumFlags(this Type type) => type.IsEnum && type.FirstAttribute<FlagsAttribute>() != null; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsUnderlyingEnum(this Type type) => type.IsEnum || type.UnderlyingSystemType.IsEnum; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static MethodInfo[] GetInstanceMethods(this Type type) => type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); [Obsolete("Use type.GetMethods()")] public static MethodInfo[] GetMethodInfos(this Type type) => type.GetMethods(); [Obsolete("Use type.GetProperties()")] public static PropertyInfo[] GetPropertyInfos(this Type type) => type.GetProperties(); [Obsolete("Use type.IsGenericTypeDefinition")] public static bool IsGenericTypeDefinition(this Type type) => type.IsGenericTypeDefinition; [Obsolete("Use type.IsGenericType")] public static bool IsGenericType(this Type type) => type.IsGenericType; [Obsolete("Use type.ContainsGenericParameters")] public static bool ContainsGenericParameters(this Type type) => type.ContainsGenericParameters; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string GetDeclaringTypeName(this Type type) { if (type.DeclaringType != null) return type.DeclaringType.Name; if (type.ReflectedType != null) return type.ReflectedType.Name; return null; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string GetDeclaringTypeName(this MemberInfo mi) { if (mi.DeclaringType != null) return mi.DeclaringType.Name; return mi.ReflectedType.Name; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Delegate CreateDelegate(this MethodInfo methodInfo, Type delegateType) { return Delegate.CreateDelegate(delegateType, methodInfo); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Delegate CreateDelegate(this MethodInfo methodInfo, Type delegateType, object target) { return Delegate.CreateDelegate(delegateType, target, methodInfo); } [Obsolete("Use type.GetElementType()")] public static Type ElementType(this Type type) => type.GetElementType(); public static Type GetCollectionType(this Type type) { return type.GetElementType() ?? type.GetGenericArguments().LastOrDefault() //new[] { str }.Select(x => new Type()) => WhereSelectArrayIterator<string,Type> ?? (type.BaseType != null && type.BaseType != typeof(object) ? type.BaseType.GetCollectionType() : null); //e.g. ArrayOfString : List<string> } static Dictionary<string, Type> GenericTypeCache = new Dictionary<string, Type>(); public static Type GetCachedGenericType(this Type type, params Type[] argTypes) { if (!type.IsGenericTypeDefinition) throw new ArgumentException(type.FullName + " is not a Generic Type Definition"); if (argTypes == null) argTypes = TypeConstants.EmptyTypeArray; var sb = StringBuilderThreadStatic.Allocate() .Append(type.FullName); foreach (var argType in argTypes) { sb.Append('|') .Append(argType.FullName); } var key = StringBuilderThreadStatic.ReturnAndFree(sb); if (GenericTypeCache.TryGetValue(key, out var genericType)) return genericType; genericType = type.MakeGenericType(argTypes); Dictionary<string, Type> snapshot, newCache; do { snapshot = GenericTypeCache; newCache = new Dictionary<string, Type>(GenericTypeCache) { [key] = genericType }; } while (!ReferenceEquals( Interlocked.CompareExchange(ref GenericTypeCache, newCache, snapshot), snapshot)); return genericType; } private static readonly ConcurrentDictionary<Type, ObjectDictionaryDefinition> toObjectMapCache = new ConcurrentDictionary<Type, ObjectDictionaryDefinition>(); internal class ObjectDictionaryDefinition { public Type Type; public readonly List<ObjectDictionaryFieldDefinition> Fields = new List<ObjectDictionaryFieldDefinition>(); public readonly Dictionary<string, ObjectDictionaryFieldDefinition> FieldsMap = new Dictionary<string, ObjectDictionaryFieldDefinition>(); public void Add(string name, ObjectDictionaryFieldDefinition fieldDef) { Fields.Add(fieldDef); FieldsMap[name] = fieldDef; } } internal class ObjectDictionaryFieldDefinition { public string Name; public Type Type; public GetMemberDelegate GetValueFn; public SetMemberDelegate SetValueFn; public Type ConvertType; public GetMemberDelegate ConvertValueFn; public void SetValue(object instance, object value) { if (SetValueFn == null) return; if (Type != typeof(object)) { if (value is IEnumerable<KeyValuePair<string, object>> dictionary) { value = dictionary.FromObjectDictionary(Type); } if (!Type.IsInstanceOfType(value)) { lock (this) { //Only caches object converter used on first use if (ConvertType == null) { ConvertType = value.GetType(); ConvertValueFn = TypeConverter.CreateTypeConverter(ConvertType, Type); } } if (ConvertType.IsInstanceOfType(value)) { value = ConvertValueFn(value); } else { var tempConvertFn = TypeConverter.CreateTypeConverter(value.GetType(), Type); value = tempConvertFn(value); } } } SetValueFn(instance, value); } } public static Dictionary<string, object> ToObjectDictionary(this object obj) { if (obj == null) return null; if (obj is Dictionary<string, object> alreadyDict) return alreadyDict; if (obj is IDictionary<string, object> interfaceDict) return new Dictionary<string, object>(interfaceDict); var to = new Dictionary<string, object>(); if (obj is Dictionary<string, string> stringDict) { foreach (var entry in stringDict) { to[entry.Key] = entry.Value; } return to; } if (obj is IDictionary d) { foreach (var key in d.Keys) { to[key.ToString()] = d[key]; } return to; } if (obj is NameValueCollection nvc) { for (var i = 0; i < nvc.Count; i++) { to[nvc.GetKey(i)] = nvc.Get(i); } return to; } if (obj is IEnumerable<KeyValuePair<string, object>> objKvps) { foreach (var kvp in objKvps) { to[kvp.Key] = kvp.Value; } return to; } if (obj is IEnumerable<KeyValuePair<string, string>> strKvps) { foreach (var kvp in strKvps) { to[kvp.Key] = kvp.Value; } return to; } var type = obj.GetType(); if (type.GetKeyValuePairsTypes(out var keyType, out var valueType, out var kvpType) && obj is IEnumerable e) { var keyGetter = TypeProperties.Get(kvpType).GetPublicGetter("Key"); var valueGetter = TypeProperties.Get(kvpType).GetPublicGetter("Value"); foreach (var entry in e) { var key = keyGetter(entry); var value = valueGetter(entry); to[key.ConvertTo<string>()] = value; } return to; } if (obj is KeyValuePair<string, object> objKvp) return new Dictionary<string, object> { { nameof(objKvp.Key), objKvp.Key }, { nameof(objKvp.Value), objKvp.Value } }; if (obj is KeyValuePair<string, string> strKvp) return new Dictionary<string, object> { { nameof(strKvp.Key), strKvp.Key }, { nameof(strKvp.Value), strKvp.Value } }; if (type.GetKeyValuePairTypes(out _, out var _)) { return new Dictionary<string, object> { { "Key", TypeProperties.Get(type).GetPublicGetter("Key")(obj).ConvertTo<string>() }, { "Value", TypeProperties.Get(type).GetPublicGetter("Value")(obj) }, }; } if (!toObjectMapCache.TryGetValue(type, out var def)) toObjectMapCache[type] = def = CreateObjectDictionaryDefinition(type); foreach (var fieldDef in def.Fields) { to[fieldDef.Name] = fieldDef.GetValueFn(obj); } return to; } public static Type GetKeyValuePairsTypeDef(this Type dictType) { //matches IDictionary<,>, IReadOnlyDictionary<,>, List<KeyValuePair<string, object>> var genericDef = dictType.GetTypeWithGenericTypeDefinitionOf(typeof(IEnumerable<>)); if (genericDef == null) return null; var genericEnumType = genericDef.GetGenericArguments()[0]; return GetKeyValuePairTypeDef(genericEnumType); } public static Type GetKeyValuePairTypeDef(this Type genericEnumType) => genericEnumType.GetTypeWithGenericTypeDefinitionOf(typeof(KeyValuePair<,>)); public static bool GetKeyValuePairsTypes(this Type dictType, out Type keyType, out Type valueType) => dictType.GetKeyValuePairsTypes(out keyType, out valueType, out _); public static bool GetKeyValuePairsTypes(this Type dictType, out Type keyType, out Type valueType, out Type kvpType) { //matches IDictionary<,>, IReadOnlyDictionary<,>, List<KeyValuePair<string, object>> var genericDef = dictType.GetTypeWithGenericTypeDefinitionOf(typeof(IEnumerable<>)); if (genericDef != null) { kvpType = genericDef.GetGenericArguments()[0]; if (GetKeyValuePairTypes(kvpType, out keyType, out valueType)) return true; } kvpType = keyType = valueType = null; return false; } public static bool GetKeyValuePairTypes(this Type kvpType, out Type keyType, out Type valueType) { var genericKvps = kvpType.GetTypeWithGenericTypeDefinitionOf(typeof(KeyValuePair<,>)); if (genericKvps != null) { var genericArgs = kvpType.GetGenericArguments(); keyType = genericArgs[0]; valueType = genericArgs[1]; return true; } keyType = valueType = null; return false; } public static object FromObjectDictionary(this IEnumerable<KeyValuePair<string, object>> values, Type type) { if (values == null) return null; var alreadyDict = typeof(IEnumerable<KeyValuePair<string, object>>).IsAssignableFrom(type); if (alreadyDict) return values; var to = type.CreateInstance(); if (to is IDictionary d) { if (type.GetKeyValuePairsTypes(out var toKeyType, out var toValueType)) { foreach (var entry in values) { var toKey = entry.Key.ConvertTo(toKeyType); var toValue = entry.Value.ConvertTo(toValueType); d[toKey] = toValue; } } else { foreach (var entry in values) { d[entry.Key] = entry.Value; } } } else { PopulateInstanceInternal(values, to, type); } return to; } public static void PopulateInstance(this IEnumerable<KeyValuePair<string, object>> values, object instance) { if (values == null || instance == null) return; PopulateInstanceInternal(values, instance, instance.GetType()); } private static void PopulateInstanceInternal(IEnumerable<KeyValuePair<string, object>> values, object to, Type type) { if (!toObjectMapCache.TryGetValue(type, out var def)) toObjectMapCache[type] = def = CreateObjectDictionaryDefinition(type); foreach (var entry in values) { if (!def.FieldsMap.TryGetValue(entry.Key, out var fieldDef) && !def.FieldsMap.TryGetValue(entry.Key.ToPascalCase(), out fieldDef) || entry.Value == null || entry.Value == DBNull.Value) continue; fieldDef.SetValue(to, entry.Value); } } public static T FromObjectDictionary<T>(this IEnumerable<KeyValuePair<string, object>> values) { return (T)values.FromObjectDictionary(typeof(T)); } private static ObjectDictionaryDefinition CreateObjectDictionaryDefinition(Type type) { var def = new ObjectDictionaryDefinition { Type = type, }; foreach (var pi in type.GetSerializableProperties()) { def.Add(pi.Name, new ObjectDictionaryFieldDefinition { Name = pi.Name, Type = pi.PropertyType, GetValueFn = pi.CreateGetter(), SetValueFn = pi.CreateSetter(), }); } if (JsConfig.IncludePublicFields) { foreach (var fi in type.GetSerializableFields()) { def.Add(fi.Name, new ObjectDictionaryFieldDefinition { Name = fi.Name, Type = fi.FieldType, GetValueFn = fi.CreateGetter(), SetValueFn = fi.CreateSetter(), }); } } return def; } public static Dictionary<string, object> ToSafePartialObjectDictionary<T>(this T instance) { var to = new Dictionary<string, object>(); var propValues = instance.ToObjectDictionary(); if (propValues != null) { foreach (var entry in propValues) { var valueType = entry.Value?.GetType(); try { if (valueType == null || !valueType.IsClass || valueType == typeof(string)) { to[entry.Key] = entry.Value; } else if (!TypeSerializer.HasCircularReferences(entry.Value)) { if (entry.Value is IEnumerable enumerable) { to[entry.Key] = entry.Value; } else { to[entry.Key] = entry.Value.ToSafePartialObjectDictionary(); } } else { to[entry.Key] = entry.Value.ToString(); } } catch (Exception ignore) { Tracer.Instance.WriteDebug($"Could not retrieve value from '{valueType?.GetType().Name}': ${ignore.Message}"); } } } return to; } public static Dictionary<string, object> MergeIntoObjectDictionary(this object obj, params object[] sources) { var to = obj.ToObjectDictionary(); foreach (var source in sources) foreach (var entry in source.ToObjectDictionary()) { to[entry.Key] = entry.Value; } return to; } public static Dictionary<string, string> ToStringDictionary(this IEnumerable<KeyValuePair<string, object>> from) => ToStringDictionary(from, null); public static Dictionary<string, string> ToStringDictionary(this IEnumerable<KeyValuePair<string, object>> from, IEqualityComparer<string> comparer) { var to = comparer != null ? new Dictionary<string, string>(comparer) : new Dictionary<string, string>(); if (from != null) { foreach (var entry in from) { to[entry.Key] = entry.Value is string s ? s : entry.Value.ConvertTo<string>(); } } return to; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; namespace Sqloogle.Libs.Rhino.Etl.Core.DataReaders { /// <summary> /// Represent a data reader that is based on IEnumerable implementation. /// This is important because we can now pass an in memory generated code to code /// that requires this, such as the SqlBulkCopy class. /// </summary> public abstract class EnumerableDataReader : IDataReader { /// <summary> /// The enumerator that we are iterating on. /// Required so subclasses can access the current object. /// </summary> protected readonly IEnumerator enumerator; private long rowCount = 0; private bool isClosed = false; /// <summary> /// Initializes a new instance of the <see cref="EnumerableDataReader"/> class. /// </summary> /// <param name="enumerator">The enumerator.</param> protected EnumerableDataReader(IEnumerator enumerator) { this.enumerator = enumerator; } /// <summary> /// Gets the descriptors for the properties that this instance /// is going to handle /// </summary> /// <value>The property descriptors.</value> protected abstract IList<Descriptor> PropertyDescriptors { get; } #region IDataReader Members /// <summary> /// Closes the <see cref="T:System.Data.IDataReader"/> Object. /// </summary> public void Close() { DoClose(); isClosed = true; } /// <summary> /// Perform the actual closing of the reader /// </summary> protected abstract void DoClose(); /// <summary> /// Returns a <see cref="T:System.Data.DataTable"/> that describes the column metadata of the <see cref="T:System.Data.IDataReader"/>. /// </summary> /// <remarks> /// This is a very trivial implementation, anything that tries to do something really fancy with it /// may need more information /// </remarks> /// <returns> /// A <see cref="T:System.Data.DataTable"/> that describes the column metadata. /// </returns> public DataTable GetSchemaTable() { DataTable table = new DataTable("schema"); table.Columns.Add("ColumnName", typeof(string)); table.Columns.Add("ColumnOrdinal", typeof(int)); table.Columns.Add("DataType", typeof(Type)); for (int i = 0; i < PropertyDescriptors.Count; i++) { table.Rows.Add( PropertyDescriptors[i].Name, i, PropertyDescriptors[i].Type ); } return table; } /// <summary> /// We do not support mutliply result set /// </summary> /// <returns> /// true if there are more rows; otherwise, false. /// </returns> public bool NextResult() { return false; } /// <summary> /// Advances the <see cref="T:System.Data.IDataReader"/> to the next record. /// </summary> /// <returns> /// true if there are more rows; otherwise, false. /// </returns> public bool Read() { bool next = enumerator.MoveNext(); if (next) rowCount += 1; return next; } /// <summary> /// Gets a value indicating the depth of nesting for the current row. /// We do not support nesting. /// </summary> /// <value></value> /// <returns>The level of nesting.</returns> public int Depth { get { return 0; } } /// <summary> /// Gets a value indicating whether the data reader is closed. /// </summary> /// <value></value> /// <returns>true if the data reader is closed; otherwise, false.</returns> public bool IsClosed { get { return isClosed; } } /// <summary> /// Gets the number of rows changed, inserted, or deleted by execution of the SQL statement. /// </summary> /// <value></value> /// <returns>The number of rows changed, inserted, or deleted; 0 if no rows were affected or the statement failed; and -1 for SELECT statements.</returns> public int RecordsAffected { get { return -1; } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Close(); } /// <summary> /// Gets the name for the field to find. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// The name of the field or the empty string (""), if there is no value to return. /// </returns> /// <exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>. </exception> public string GetName(int i) { return PropertyDescriptors[i].Name; } /// <summary> /// Gets the data type information for the specified field. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// The data type information for the specified field. /// </returns> /// <exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>. </exception> public string GetDataTypeName(int i) { return PropertyDescriptors[i].Type.Name; } /// <summary> /// Gets the <see cref="T:System.Type"/> information corresponding to the type of <see cref="T:System.Object"/> that would be returned from <see cref="M:System.Data.IDataRecord.GetValue(System.Int32)"/>. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// The <see cref="T:System.Type"/> information corresponding to the type of <see cref="T:System.Object"/> that would be returned from <see cref="M:System.Data.IDataRecord.GetValue(System.Int32)"/>. /// </returns> /// <exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>. </exception> public Type GetFieldType(int i) { return PropertyDescriptors[i].Type; } /// <summary> /// Return the value of the specified field. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// The <see cref="T:System.Object"/> which will contain the field value upon return. /// </returns> /// <exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>. </exception> public object GetValue(int i) { return PropertyDescriptors[i].GetValue(enumerator.Current) ?? DBNull.Value; } /// <summary> /// Gets all the attribute fields in the collection for the current record. /// </summary> /// <param name="values">An array of <see cref="T:System.Object"/> to copy the attribute fields into.</param> /// <returns> /// The number of instances of <see cref="T:System.Object"/> in the array. /// </returns> public int GetValues(object[] values) { for (int i = 0; i < PropertyDescriptors.Count; i++) { values[i] = PropertyDescriptors[i].GetValue(enumerator.Current); } return PropertyDescriptors.Count; } /// <summary> /// Return the index of the named field. /// </summary> /// <param name="name">The name of the field to find.</param> /// <returns>The index of the named field.</returns> public int GetOrdinal(string name) { for (int i = 0; i < PropertyDescriptors.Count; i++) { if (string.Equals(PropertyDescriptors[i].Name, name, StringComparison.InvariantCultureIgnoreCase)) return i; } throw new ArgumentException("There is not property with name: " + name); } /// <summary> /// Gets the value of the specified column as a Boolean. /// </summary> /// <param name="i">The zero-based column ordinal.</param> /// <returns>The value of the column.</returns> /// <exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>. </exception> public bool GetBoolean(int i) { return (bool)GetValue(i); } /// <summary> /// Gets the 8-bit unsigned integer value of the specified column. /// </summary> /// <param name="i">The zero-based column ordinal.</param> /// <returns> /// The 8-bit unsigned integer value of the specified column. /// </returns> /// <exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>. </exception> public byte GetByte(int i) { return (byte)GetValue(i); } /// <summary> /// We do not support this operation /// </summary> public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length) { throw new NotSupportedException(); } /// <summary> /// Gets the character value of the specified column. /// </summary> /// <param name="i">The zero-based column ordinal.</param> /// <returns> /// The character value of the specified column. /// </returns> /// <exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>. </exception> public char GetChar(int i) { return (char)GetValue(i); } /// <summary> /// We do not support this operation /// </summary> public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length) { throw new NotSupportedException(); } /// <summary> /// Returns the GUID value of the specified field. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns>The GUID value of the specified field.</returns> /// <exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>. </exception> public Guid GetGuid(int i) { return (Guid)GetValue(i); } /// <summary> /// Gets the 16-bit signed integer value of the specified field. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// The 16-bit signed integer value of the specified field. /// </returns> /// <exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>. </exception> public short GetInt16(int i) { return (short)GetValue(i); } /// <summary> /// Gets the 32-bit signed integer value of the specified field. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// The 32-bit signed integer value of the specified field. /// </returns> /// <exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>. </exception> public int GetInt32(int i) { return (int)GetValue(i); } /// <summary> /// Gets the 64-bit signed integer value of the specified field. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// The 64-bit signed integer value of the specified field. /// </returns> /// <exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>. </exception> public long GetInt64(int i) { return (long)GetValue(i); } /// <summary> /// Gets the single-precision floating point number of the specified field. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// The single-precision floating point number of the specified field. /// </returns> /// <exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>. </exception> public float GetFloat(int i) { return (float)GetValue(i); } /// <summary> /// Gets the double-precision floating point number of the specified field. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// The double-precision floating point number of the specified field. /// </returns> /// <exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>. </exception> public double GetDouble(int i) { return (double)GetValue(i); } /// <summary> /// Gets the string value of the specified field. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns>The string value of the specified field.</returns> /// <exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>. </exception> public string GetString(int i) { return (string)GetValue(i); } /// <summary> /// Gets the fixed-position numeric value of the specified field. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// The fixed-position numeric value of the specified field. /// </returns> /// <exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>. </exception> public decimal GetDecimal(int i) { return (decimal)GetValue(i); } /// <summary> /// Gets the date and time data value of the specified field. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// The date and time data value of the specified field. /// </returns> /// <exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>. </exception> public DateTime GetDateTime(int i) { return (DateTime)GetValue(i); } /// <summary> /// We do not support nesting /// </summary> public IDataReader GetData(int i) { throw new NotSupportedException(); } /// <summary> /// Return whether the specified field is set to null. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// true if the specified field is set to null; otherwise, false. /// </returns> /// <exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>. </exception> public bool IsDBNull(int i) { return GetValue(i) == null || GetValue(i) == DBNull.Value; } /// <summary> /// Gets the number of columns in the current row. /// </summary> /// <value></value> /// <returns>When not positioned in a valid recordset, 0; otherwise, the number of columns in the current record. The default is -1.</returns> public int FieldCount { get { return PropertyDescriptors.Count; } } /// <summary> /// Gets the <see cref="System.Object"/> with the specified i. /// </summary> /// <value></value> public object this[int i] { get { return GetValue(i); } } /// <summary> /// Gets the <see cref="System.Object"/> with the specified name. /// </summary> /// <value></value> public object this[string name] { get { return GetValue(GetOrdinal(name)); } } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorLogger; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes { using Editor.Shared.Utilities; using DiagnosticId = String; using LanguageKind = String; [Export(typeof(ICodeFixService)), Shared] internal partial class CodeFixService : ForegroundThreadAffinitizedObject, ICodeFixService { private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>> _workspaceFixersMap; private readonly ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>> _projectFixersMap; // Shared by project fixers and workspace fixers. private ImmutableDictionary<CodeFixProvider, ImmutableArray<DiagnosticId>> _fixerToFixableIdsMap = ImmutableDictionary<CodeFixProvider, ImmutableArray<DiagnosticId>>.Empty; private readonly ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>> _fixerPriorityMap; private readonly ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider> _analyzerReferenceToFixersMap; private readonly ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>.CreateValueCallback _createProjectCodeFixProvider; private readonly ImmutableDictionary<LanguageKind, Lazy<ISuppressionFixProvider>> _suppressionProvidersMap; private readonly IEnumerable<Lazy<IErrorLoggerService>> _errorLoggers; private ImmutableDictionary<object, FixAllProviderInfo> _fixAllProviderMap; [ImportingConstructor] public CodeFixService( IDiagnosticAnalyzerService service, [ImportMany]IEnumerable<Lazy<IErrorLoggerService>> loggers, [ImportMany]IEnumerable<Lazy<CodeFixProvider, CodeChangeProviderMetadata>> fixers, [ImportMany]IEnumerable<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>> suppressionProviders) : base(assertIsForeground: false) { _errorLoggers = loggers; _diagnosticService = service; var fixersPerLanguageMap = fixers.ToPerLanguageMapWithMultipleLanguages(); var suppressionProvidersPerLanguageMap = suppressionProviders.ToPerLanguageMapWithMultipleLanguages(); _workspaceFixersMap = GetFixerPerLanguageMap(fixersPerLanguageMap, null); _suppressionProvidersMap = GetSuppressionProvidersPerLanguageMap(suppressionProvidersPerLanguageMap); // REVIEW: currently, fixer's priority is statically defined by the fixer itself. might considering making it more dynamic or configurable. _fixerPriorityMap = GetFixerPriorityPerLanguageMap(fixersPerLanguageMap); // Per-project fixers _projectFixersMap = new ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, ImmutableDictionary<string, List<CodeFixProvider>>>(); _analyzerReferenceToFixersMap = new ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>(); _createProjectCodeFixProvider = new ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>.CreateValueCallback(r => new ProjectCodeFixProvider(r)); _fixAllProviderMap = ImmutableDictionary<object, FixAllProviderInfo>.Empty; } public async Task<FirstDiagnosticResult> GetFirstDiagnosticWithFixAsync(Document document, TextSpan range, bool considerSuppressionFixes, CancellationToken cancellationToken) { if (document == null || !document.IsOpen()) { return default(FirstDiagnosticResult); } using (var diagnostics = SharedPools.Default<List<DiagnosticData>>().GetPooledObject()) { var fullResult = await _diagnosticService.TryAppendDiagnosticsForSpanAsync(document, range, diagnostics.Object, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var diagnostic in diagnostics.Object) { cancellationToken.ThrowIfCancellationRequested(); if (!range.IntersectsWith(diagnostic.TextSpan)) { continue; } // REVIEW: 2 possible designs. // 1. find the first fix and then return right away. if the lightbulb is actually expanded, find all fixes for the line synchronously. or // 2. kick off a task that finds all fixes for the given range here but return once we find the first one. // at the same time, let the task to run to finish. if the lightbulb is expanded, we just simply use the task to get all fixes. // // first approach is simpler, so I will implement that first. if the first approach turns out to be not good enough, then // I will try the second approach which will be more complex but quicker var hasFix = await ContainsAnyFix(document, diagnostic, considerSuppressionFixes, cancellationToken).ConfigureAwait(false); if (hasFix) { return new FirstDiagnosticResult(!fullResult, hasFix, diagnostic); } } return new FirstDiagnosticResult(!fullResult, false, default(DiagnosticData)); } } public async Task<IEnumerable<CodeFixCollection>> GetFixesAsync(Document document, TextSpan range, bool includeSuppressionFixes, CancellationToken cancellationToken) { // REVIEW: this is the first and simplest design. basically, when ctrl+. is pressed, it asks diagnostic service to give back // current diagnostics for the given span, and it will use that to get fixes. internally diagnostic service will either return cached information // (if it is up-to-date) or synchronously do the work at the spot. // // this design's weakness is that each side don't have enough information to narrow down works to do. it will most likely always do more works than needed. // sometimes way more than it is needed. (compilation) Dictionary<TextSpan, List<DiagnosticData>> aggregatedDiagnostics = null; foreach (var diagnostic in await _diagnosticService.GetDiagnosticsForSpanAsync(document, range, cancellationToken: cancellationToken).ConfigureAwait(false)) { if (diagnostic.IsSuppressed) { continue; } cancellationToken.ThrowIfCancellationRequested(); aggregatedDiagnostics = aggregatedDiagnostics ?? new Dictionary<TextSpan, List<DiagnosticData>>(); aggregatedDiagnostics.GetOrAdd(diagnostic.TextSpan, _ => new List<DiagnosticData>()).Add(diagnostic); } var result = new List<CodeFixCollection>(); if (aggregatedDiagnostics == null) { return result; } foreach (var spanAndDiagnostic in aggregatedDiagnostics) { result = await AppendFixesAsync(document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, result, cancellationToken).ConfigureAwait(false); } if (result.Any()) { // sort the result to the order defined by the fixers var priorityMap = _fixerPriorityMap[document.Project.Language].Value; result.Sort((d1, d2) => priorityMap.ContainsKey((CodeFixProvider)d1.Provider) ? (priorityMap.ContainsKey((CodeFixProvider)d2.Provider) ? priorityMap[(CodeFixProvider)d1.Provider] - priorityMap[(CodeFixProvider)d2.Provider] : -1) : 1); } // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive if (document.Project.Solution.Workspace.Kind != WorkspaceKind.Interactive && includeSuppressionFixes) { foreach (var spanAndDiagnostic in aggregatedDiagnostics) { result = await AppendSuppressionsAsync(document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, result, cancellationToken).ConfigureAwait(false); } } return result; } private async Task<List<CodeFixCollection>> AppendFixesAsync( Document document, TextSpan span, IEnumerable<DiagnosticData> diagnostics, List<CodeFixCollection> result, CancellationToken cancellationToken) { Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>> fixerMap; bool hasAnySharedFixer = _workspaceFixersMap.TryGetValue(document.Project.Language, out fixerMap); var projectFixersMap = GetProjectFixers(document.Project); var hasAnyProjectFixer = projectFixersMap.Any(); if (!hasAnySharedFixer && !hasAnyProjectFixer) { return result; } ImmutableArray<CodeFixProvider> workspaceFixers; List<CodeFixProvider> projectFixers; var allFixers = new List<CodeFixProvider>(); // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive bool isInteractive = document.Project.Solution.Workspace.Kind == WorkspaceKind.Interactive; foreach (var diagnosticId in diagnostics.Select(d => d.Id).Distinct()) { cancellationToken.ThrowIfCancellationRequested(); if (hasAnySharedFixer && fixerMap.Value.TryGetValue(diagnosticId, out workspaceFixers)) { if (isInteractive) { allFixers.AddRange(workspaceFixers.Where(IsInteractiveCodeFixProvider)); } else { allFixers.AddRange(workspaceFixers); } } if (hasAnyProjectFixer && projectFixersMap.TryGetValue(diagnosticId, out projectFixers)) { Debug.Assert(!isInteractive); allFixers.AddRange(projectFixers); } } var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>(); foreach (var fixer in allFixers.Distinct()) { cancellationToken.ThrowIfCancellationRequested(); Func<Diagnostic, bool> hasFix = (d) => this.GetFixableDiagnosticIds(fixer, extensionManager).Contains(d.Id); Func<ImmutableArray<Diagnostic>, Task<IEnumerable<CodeFix>>> getFixes = async (dxs) => { var fixes = new List<CodeFix>(); var context = new CodeFixContext(document, span, dxs, // TODO: Can we share code between similar lambdas that we pass to this API in BatchFixAllProvider.cs, CodeFixService.cs and CodeRefactoringService.cs? (action, applicableDiagnostics) => { // Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from. lock (fixes) { fixes.Add(new CodeFix(document.Project, action, applicableDiagnostics)); } }, verifyArguments: false, cancellationToken: cancellationToken); var task = fixer.RegisterCodeFixesAsync(context) ?? SpecializedTasks.EmptyTask; await task.ConfigureAwait(false); return fixes; }; await AppendFixesOrSuppressionsAsync(document, span, diagnostics, result, fixer, hasFix, getFixes, cancellationToken).ConfigureAwait(false); } return result; } private async Task<List<CodeFixCollection>> AppendSuppressionsAsync( Document document, TextSpan span, IEnumerable<DiagnosticData> diagnostics, List<CodeFixCollection> result, CancellationToken cancellationToken) { Lazy<ISuppressionFixProvider> lazySuppressionProvider; if (!_suppressionProvidersMap.TryGetValue(document.Project.Language, out lazySuppressionProvider) || lazySuppressionProvider.Value == null) { return result; } Func<Diagnostic, bool> hasFix = (d) => lazySuppressionProvider.Value.CanBeSuppressedOrUnsuppressed(d); Func<ImmutableArray<Diagnostic>, Task<IEnumerable<CodeFix>>> getFixes = (dxs) => lazySuppressionProvider.Value.GetSuppressionsAsync(document, span, dxs, cancellationToken); await AppendFixesOrSuppressionsAsync(document, span, diagnostics, result, lazySuppressionProvider.Value, hasFix, getFixes, cancellationToken).ConfigureAwait(false); return result; } private async Task<List<CodeFixCollection>> AppendFixesOrSuppressionsAsync( Document document, TextSpan span, IEnumerable<DiagnosticData> diagnosticsWithSameSpan, List<CodeFixCollection> result, object fixer, Func<Diagnostic, bool> hasFix, Func<ImmutableArray<Diagnostic>, Task<IEnumerable<CodeFix>>> getFixes, CancellationToken cancellationToken) { var diagnostics = (await diagnosticsWithSameSpan.OrderByDescending(d => d.Severity).ToDiagnosticsAsync(document.Project, cancellationToken).ConfigureAwait(false)).Where(d => hasFix(d)).ToImmutableArray(); if (diagnostics.Length <= 0) { // this can happen for suppression case where all diagnostics can't be suppressed return result; } var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>(); var fixes = await extensionManager.PerformFunctionAsync(fixer, () => getFixes(diagnostics), defaultValue: SpecializedCollections.EmptyEnumerable<CodeFix>()).ConfigureAwait(false); if (fixes != null && fixes.Any()) { // If the fix provider supports fix all occurrences, then get the corresponding FixAllProviderInfo and fix all context. var fixAllProviderInfo = extensionManager.PerformFunction(fixer, () => ImmutableInterlocked.GetOrAdd(ref _fixAllProviderMap, fixer, FixAllProviderInfo.Create), defaultValue: null); FixAllCodeActionContext fixAllContext = null; if (fixAllProviderInfo != null) { var codeFixProvider = (fixer as CodeFixProvider) ?? new WrapperCodeFixProvider((ISuppressionFixProvider)fixer, diagnostics.Select(d => d.Id)); fixAllContext = FixAllCodeActionContext.Create( document, fixAllProviderInfo, codeFixProvider, diagnostics, this.GetDocumentDiagnosticsAsync, this.GetProjectDiagnosticsAsync, cancellationToken); } result = result ?? new List<CodeFixCollection>(); var codeFix = new CodeFixCollection(fixer, span, fixes, fixAllContext); result.Add(codeFix); } return result; } public CodeFixProvider GetSuppressionFixer(string language, IEnumerable<string> diagnosticIds) { Lazy<ISuppressionFixProvider> lazySuppressionProvider; if (!_suppressionProvidersMap.TryGetValue(language, out lazySuppressionProvider) || lazySuppressionProvider.Value == null) { return null; } return new WrapperCodeFixProvider(lazySuppressionProvider.Value, diagnosticIds); } private async Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken) { Contract.ThrowIfNull(document); var solution = document.Project.Solution; var diagnostics = await _diagnosticService.GetDiagnosticsForIdsAsync(solution, null, document.Id, diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false); Contract.ThrowIfFalse(diagnostics.All(d => d.DocumentId != null)); return await diagnostics.ToDiagnosticsAsync(document.Project, cancellationToken).ConfigureAwait(false); } private async Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project, bool includeAllDocumentDiagnostics, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken) { Contract.ThrowIfNull(project); if (includeAllDocumentDiagnostics) { // Get all diagnostics for the entire project, including document diagnostics. var diagnostics = await _diagnosticService.GetDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds: diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false); return await diagnostics.ToDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false); } else { // Get all no-location diagnostics for the project, doesn't include document diagnostics. var diagnostics = await _diagnosticService.GetProjectDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false); Contract.ThrowIfFalse(diagnostics.All(d => d.DocumentId == null)); return await diagnostics.ToDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false); } } private async Task<bool> ContainsAnyFix(Document document, DiagnosticData diagnostic, bool considerSuppressionFixes, CancellationToken cancellationToken) { ImmutableArray<CodeFixProvider> workspaceFixers = ImmutableArray<CodeFixProvider>.Empty; List<CodeFixProvider> projectFixers = null; Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>> fixerMap; bool hasAnySharedFixer = _workspaceFixersMap.TryGetValue(document.Project.Language, out fixerMap) && fixerMap.Value.TryGetValue(diagnostic.Id, out workspaceFixers); var hasAnyProjectFixer = GetProjectFixers(document.Project).TryGetValue(diagnostic.Id, out projectFixers); // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive if (hasAnySharedFixer && document.Project.Solution.Workspace.Kind == WorkspaceKind.Interactive) { workspaceFixers = workspaceFixers.WhereAsArray(IsInteractiveCodeFixProvider); hasAnySharedFixer = workspaceFixers.Any(); } Lazy<ISuppressionFixProvider> lazySuppressionProvider = null; var hasSuppressionFixer = considerSuppressionFixes && _suppressionProvidersMap.TryGetValue(document.Project.Language, out lazySuppressionProvider) && lazySuppressionProvider.Value != null; if (!hasAnySharedFixer && !hasAnyProjectFixer && !hasSuppressionFixer) { return false; } var allFixers = ImmutableArray<CodeFixProvider>.Empty; if (hasAnySharedFixer) { allFixers = workspaceFixers; } if (hasAnyProjectFixer) { allFixers = allFixers.AddRange(projectFixers); } var dx = await diagnostic.ToDiagnosticAsync(document.Project, cancellationToken).ConfigureAwait(false); if (hasSuppressionFixer && lazySuppressionProvider.Value.CanBeSuppressedOrUnsuppressed(dx)) { return true; } var fixes = new List<CodeFix>(); var context = new CodeFixContext(document, dx, // TODO: Can we share code between similar lambdas that we pass to this API in BatchFixAllProvider.cs, CodeFixService.cs and CodeRefactoringService.cs? (action, applicableDiagnostics) => { // Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from. lock (fixes) { fixes.Add(new CodeFix(document.Project, action, applicableDiagnostics)); } }, verifyArguments: false, cancellationToken: cancellationToken); var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>(); // we do have fixer. now let's see whether it actually can fix it foreach (var fixer in allFixers) { await extensionManager.PerformActionAsync(fixer, () => fixer.RegisterCodeFixesAsync(context) ?? SpecializedTasks.EmptyTask).ConfigureAwait(false); foreach (var fix in fixes) { if (!fix.Action.PerformFinalApplicabilityCheck) { return true; } // Have to see if this fix is still applicable. Jump to the foreground thread // to make that check. var applicable = await Task.Factory.StartNew(() => { this.AssertIsForeground(); return fix.Action.IsApplicable(document.Project.Solution.Workspace); }, cancellationToken, TaskCreationOptions.None, this.ForegroundTaskScheduler).ConfigureAwait(false); this.AssertIsBackground(); if (applicable) { return true; } } } return false; } private bool IsInteractiveCodeFixProvider(CodeFixProvider provider) { // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive if (provider is FullyQualify.AbstractFullyQualifyCodeFixProvider) { return true; } var providerType = provider?.GetType(); while (providerType != null) { if (providerType.IsConstructedGenericType && providerType.GetGenericTypeDefinition() == typeof(AddImport.AbstractAddImportCodeFixProvider<>)) { return true; } providerType = providerType.GetTypeInfo().BaseType; } return false; } private static readonly Func<DiagnosticId, List<CodeFixProvider>> s_createList = _ => new List<CodeFixProvider>(); private ImmutableArray<DiagnosticId> GetFixableDiagnosticIds(CodeFixProvider fixer, IExtensionManager extensionManager) { // If we are passed a null extension manager it means we do not have access to a document so there is nothing to // show the user. In this case we will log any exceptions that occur, but the user will not see them. if (extensionManager != null) { return extensionManager.PerformFunction( fixer, () => ImmutableInterlocked.GetOrAdd(ref _fixerToFixableIdsMap, fixer, f => GetAndTestFixableDiagnosticIds(f)), defaultValue: ImmutableArray<DiagnosticId>.Empty); } try { return ImmutableInterlocked.GetOrAdd(ref _fixerToFixableIdsMap, fixer, f => GetAndTestFixableDiagnosticIds(f)); } catch (OperationCanceledException) { throw; } catch (Exception e) { foreach (var logger in _errorLoggers) { logger.Value.LogException(fixer, e); } return ImmutableArray<DiagnosticId>.Empty; } } private static ImmutableArray<string> GetAndTestFixableDiagnosticIds(CodeFixProvider codeFixProvider) { var ids = codeFixProvider.FixableDiagnosticIds; if (ids.IsDefault) { throw new InvalidOperationException( string.Format( WorkspacesResources.FixableDiagnosticIdsIncorrectlyInitialized, codeFixProvider.GetType().Name + "." + nameof(CodeFixProvider.FixableDiagnosticIds))); } return ids; } private ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>> GetFixerPerLanguageMap( Dictionary<LanguageKind, List<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>> fixersPerLanguage, IExtensionManager extensionManager) { var fixerMap = ImmutableDictionary.Create<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>>(); foreach (var languageKindAndFixers in fixersPerLanguage) { var lazyMap = new Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>(() => { var mutableMap = new Dictionary<DiagnosticId, List<CodeFixProvider>>(); foreach (var fixer in languageKindAndFixers.Value) { foreach (var id in this.GetFixableDiagnosticIds(fixer.Value, extensionManager)) { if (string.IsNullOrWhiteSpace(id)) { continue; } var list = mutableMap.GetOrAdd(id, s_createList); list.Add(fixer.Value); } } var immutableMap = ImmutableDictionary.CreateBuilder<DiagnosticId, ImmutableArray<CodeFixProvider>>(); foreach (var diagnosticIdAndFixers in mutableMap) { immutableMap.Add(diagnosticIdAndFixers.Key, diagnosticIdAndFixers.Value.AsImmutableOrEmpty()); } return immutableMap.ToImmutable(); }, isThreadSafe: true); fixerMap = fixerMap.Add(languageKindAndFixers.Key, lazyMap); } return fixerMap; } private static ImmutableDictionary<LanguageKind, Lazy<ISuppressionFixProvider>> GetSuppressionProvidersPerLanguageMap( Dictionary<LanguageKind, List<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>>> suppressionProvidersPerLanguage) { var suppressionFixerMap = ImmutableDictionary.Create<LanguageKind, Lazy<ISuppressionFixProvider>>(); foreach (var languageKindAndFixers in suppressionProvidersPerLanguage) { var suppressionFixerLazyMap = new Lazy<ISuppressionFixProvider>(() => languageKindAndFixers.Value.SingleOrDefault().Value); suppressionFixerMap = suppressionFixerMap.Add(languageKindAndFixers.Key, suppressionFixerLazyMap); } return suppressionFixerMap; } private static ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>> GetFixerPriorityPerLanguageMap( Dictionary<LanguageKind, List<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>> fixersPerLanguage) { var languageMap = ImmutableDictionary.CreateBuilder<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>>(); foreach (var languageAndFixers in fixersPerLanguage) { var lazyMap = new Lazy<ImmutableDictionary<CodeFixProvider, int>>(() => { var priorityMap = ImmutableDictionary.CreateBuilder<CodeFixProvider, int>(); var fixers = ExtensionOrderer.Order(languageAndFixers.Value); for (var i = 0; i < fixers.Count; i++) { priorityMap.Add(fixers[i].Value, i); } return priorityMap.ToImmutable(); }, isThreadSafe: true); languageMap.Add(languageAndFixers.Key, lazyMap); } return languageMap.ToImmutable(); } private ImmutableDictionary<DiagnosticId, List<CodeFixProvider>> GetProjectFixers(Project project) { // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive return project.Solution.Workspace.Kind == WorkspaceKind.Interactive ? ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Empty : _projectFixersMap.GetValue(project.AnalyzerReferences, pId => ComputeProjectFixers(project)); } private ImmutableDictionary<DiagnosticId, List<CodeFixProvider>> ComputeProjectFixers(Project project) { var extensionManager = project.Solution.Workspace.Services.GetService<IExtensionManager>(); ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Builder builder = null; foreach (var reference in project.AnalyzerReferences) { var projectCodeFixerProvider = _analyzerReferenceToFixersMap.GetValue(reference, _createProjectCodeFixProvider); foreach (var fixer in projectCodeFixerProvider.GetFixers(project.Language)) { var fixableIds = this.GetFixableDiagnosticIds(fixer, extensionManager); foreach (var id in fixableIds) { if (string.IsNullOrWhiteSpace(id)) { continue; } builder = builder ?? ImmutableDictionary.CreateBuilder<DiagnosticId, List<CodeFixProvider>>(); var list = builder.GetOrAdd(id, s_createList); list.Add(fixer); } } } if (builder == null) { return ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Empty; } return builder.ToImmutable(); } } }
//------------------------------------------------------------------------------ // <copyright file="ListItemsPage.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.Design.MobileControls { using System; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; using System.Windows.Forms.Design; // using System.Web.UI.Design.Util; using System.Web.UI.MobileControls; using System.Web.UI.Design.MobileControls.Util; using Button = System.Windows.Forms.Button; using Label = System.Windows.Forms.Label; using TextBox = System.Windows.Forms.TextBox; using CheckBox = System.Windows.Forms.CheckBox; using TreeView = System.Windows.Forms.TreeView; /// <summary> /// The Items page for the List control. /// </summary> /// <internalonly/> [ System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode) ] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] internal sealed class ListItemsPage : ListComponentEditorPage { private IListDesigner _listDesigner; private CheckBox _itemsAsLinksCheckBox; private TextBox _txtValue; private CheckBox _ckbSelected; private bool _isBaseControlList; public ListItemsPage() { TreeViewTitle = SR.GetString(SR.ListItemsPage_ItemCaption); AddButtonTitle = SR.GetString(SR.ListItemsPage_NewItemCaption); DefaultName = SR.GetString(SR.ListItemsPage_DefaultItemText); } protected override String HelpKeyword { get { if (_isBaseControlList) { return "net.Mobile.ListProperties.Items"; } else { return "net.Mobile.SelectionListProperties.Items"; } } } protected override bool FilterIllegalName() { return false; } protected override String GetNewName() { return SR.GetString(SR.ListItemsPage_DefaultItemText); } protected override void InitForm() { Debug.Assert(GetBaseControl() != null); _isBaseControlList = (GetBaseControl() is List); this._listDesigner = (IListDesigner)GetBaseDesigner(); Y = (_isBaseControlList ? 52 : 24); base.InitForm(); this.Text = SR.GetString(SR.ListItemsPage_Title); this.CommitOnDeactivate = true; this.Icon = new Icon( typeof(System.Web.UI.Design.MobileControls.MobileControlDesigner), "Items.ico" ); this.Size = new Size(382, 220); if (_isBaseControlList) { _itemsAsLinksCheckBox = new CheckBox(); _itemsAsLinksCheckBox.SetBounds(4, 4, 370, 16); _itemsAsLinksCheckBox.Text = SR.GetString(SR.ListItemsPage_ItemsAsLinksCaption); _itemsAsLinksCheckBox.FlatStyle = FlatStyle.System; _itemsAsLinksCheckBox.CheckedChanged += new EventHandler(this.OnSetPageDirty); _itemsAsLinksCheckBox.TabIndex = 0; } GroupLabel grplblItemList = new GroupLabel(); grplblItemList.SetBounds(4, _isBaseControlList ? 32 : 4, 372, LabelHeight); grplblItemList.Text = SR.GetString(SR.ListItemsPage_ItemListGroupLabel); grplblItemList.TabIndex = 1; grplblItemList.TabStop = false; TreeList.TabIndex = 2; Label lblValue = new Label(); lblValue.SetBounds(X, Y, 134, LabelHeight); lblValue.Text = SR.GetString(SR.ListItemsPage_ItemValueCaption); lblValue.TabStop = false; lblValue.TabIndex = Index; Y += LabelHeight; _txtValue = new TextBox(); _txtValue.SetBounds(X, Y, 134, CmbHeight); _txtValue.TextChanged += new EventHandler(this.OnPropertyChanged); _txtValue.TabIndex = Index + 1; this.Controls.AddRange(new Control[] { grplblItemList, lblValue, _txtValue }); if (_isBaseControlList) { this.Controls.Add(_itemsAsLinksCheckBox); } else { Y += CellSpace; _ckbSelected = new CheckBox(); _ckbSelected.SetBounds(X, Y, 134, LabelHeight); _ckbSelected.FlatStyle = System.Windows.Forms.FlatStyle.System; _ckbSelected.Text = SR.GetString(SR.ListItemsPage_ItemSelectedCaption); _ckbSelected.CheckedChanged += new EventHandler(this.OnPropertyChanged); _ckbSelected.TabIndex = Index + 2; this.Controls.Add(_ckbSelected); } } protected override void InitPage() { base.InitPage(); if (_isBaseControlList) { List list = (List)GetBaseControl(); _itemsAsLinksCheckBox.Checked = list.ItemsAsLinks; } else { _ckbSelected.Checked = false; } _txtValue.Text = String.Empty; } protected override void LoadItems() { using (new LoadingModeResource(this)) { foreach (MobileListItem item in _listDesigner.Items) { ItemTreeNode newNode = new ItemTreeNode(item); TreeList.TvList.Nodes.Add(newNode); } } } protected override void LoadItemProperties() { using (new LoadingModeResource(this)) { if (CurrentNode != null) { ItemTreeNode currentItemNode = (ItemTreeNode)CurrentNode; _txtValue.Text = currentItemNode.Value; if (!_isBaseControlList) { _ckbSelected.Checked = currentItemNode.Selected; } } else { _txtValue.Text = String.Empty; if (!_isBaseControlList) { _ckbSelected.Checked = false; } } } } protected override void OnAfterLabelEdit(Object source, NodeLabelEditEventArgs e) { base.OnAfterLabelEdit(source, e); if (!((ItemTreeNode)CurrentNode).ValueSet) { _txtValue.Text = ((ItemTreeNode)CurrentNode).Value = CurrentNode.Name; } } protected override void OnClickAddButton(Object source, EventArgs e) { if (IsLoading()) { return; } ItemTreeNode newNode = new ItemTreeNode(GetNewName()); TreeList.TvList.Nodes.Add(newNode); TreeList.TvList.SelectedNode = newNode; CurrentNode = newNode; newNode.Dirty = true; newNode.BeginEdit(); LoadItemProperties(); SetDirty(); } private void OnSetPageDirty(Object source, EventArgs e) { if (IsLoading()) { return; } SetDirty(); } protected override void OnPropertyChanged(Object source, EventArgs e) { // This means there are no fields yet. Do nothing if (CurrentNode == null || IsLoading()) { return; } if (source is TextBox) { ((ItemTreeNode)CurrentNode).Value = _txtValue.Text; } else { Debug.Assert(!_isBaseControlList); ((ItemTreeNode)CurrentNode).Selected = _ckbSelected.Checked; } SetDirty(); CurrentNode.Dirty = true; } protected override void SaveComponent() { // Delegate to base implementation first! // This will properly close ListTreeNode editing mode. base.SaveComponent(); _listDesigner.Items.Clear(); foreach (ItemTreeNode itemNode in TreeList.TvList.Nodes) { if (itemNode.Dirty) { itemNode.RuntimeItem.Text = itemNode.Text; itemNode.RuntimeItem.Value = itemNode.Value; if (!_isBaseControlList) { itemNode.RuntimeItem.Selected = itemNode.Selected; } } _listDesigner.Items.Add(itemNode.RuntimeItem); } if (_isBaseControlList) { List list = (List)GetBaseControl(); list.ItemsAsLinks = _itemsAsLinksCheckBox.Checked; TypeDescriptor.Refresh(list); } else { SelectionList selectionList = (SelectionList)GetBaseControl(); TypeDescriptor.Refresh(selectionList); } } protected override void UpdateControlsEnabling() { if (TreeList.TvList.SelectedNode == null) { TreeList.TvList.Enabled = _txtValue.Enabled = false; _txtValue.Text = String.Empty; } else { TreeList.TvList.Enabled = _txtValue.Enabled = true; } if (!_isBaseControlList) { SelectionList selectionListControl = (SelectionList) GetBaseControl(); if (TreeList.TvList.SelectedNode == null) { _ckbSelected.Enabled = false; _ckbSelected.Checked = false; } else { _ckbSelected.Enabled = true; } } } /// <summary> /// Internal object used to store all items properties /// </summary> [ System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode) ] private class ItemTreeNode : ListTreeNode { private MobileListItem _runtimeItem; private String _value; private bool _selected; private bool _valueSet = false; /// <summary> /// </summary> internal ItemTreeNode(String itemText) : base(itemText) { this._runtimeItem = new MobileListItem(); this._value = null; this._selected = false; } /// <summary> /// </summary> internal ItemTreeNode(MobileListItem runtimeItem) : base(runtimeItem.Text) { Debug.Assert(runtimeItem != null, "runtimeItem is null"); _valueSet = true; this._runtimeItem = runtimeItem; this._value = _runtimeItem.Value; this._selected = _runtimeItem.Selected; } internal MobileListItem RuntimeItem { get { return _runtimeItem; } } internal String Value { get { return _value; } set { _value = value; _valueSet = true; } } internal bool Selected { get { return _selected; } set { _selected = value; } } internal bool ValueSet { get { return _valueSet; } } } } }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; using System.Collections.ObjectModel; using System.Text; using System.Data.Linq; using System.Data.Linq.Mapping; using System.Data.Linq.Provider; using System.Linq; using System.Diagnostics.CodeAnalysis; namespace System.Data.Linq.SqlClient { internal class Translator { IDataServices services; SqlFactory sql; TypeSystemProvider typeProvider; internal Translator(IDataServices services, SqlFactory sqlFactory, TypeSystemProvider typeProvider) { this.services = services; this.sql = sqlFactory; this.typeProvider = typeProvider; } internal SqlSelect BuildDefaultQuery(MetaType rowType, bool allowDeferred, SqlLink link, Expression source) { System.Diagnostics.Debug.Assert(rowType != null && rowType.Table != null); if (rowType.HasInheritance && rowType.InheritanceRoot != rowType) { // RowType is expected to be an inheritance root. throw Error.ArgumentWrongValue("rowType"); } SqlTable table = sql.Table(rowType.Table, rowType, source); SqlAlias tableAlias = new SqlAlias(table); SqlAliasRef tableAliasRef = new SqlAliasRef(tableAlias); SqlExpression projection = this.BuildProjection(tableAliasRef, table.RowType, allowDeferred, link, source); return new SqlSelect(projection, tableAlias, source); } internal SqlExpression BuildProjection(SqlExpression item, MetaType rowType, bool allowDeferred, SqlLink link, Expression source) { if (!rowType.HasInheritance) { return this.BuildProjectionInternal(item, rowType, (rowType.Table != null) ? rowType.PersistentDataMembers : rowType.DataMembers, allowDeferred, link, source); } else { // Build a type case that represents a switch between the various type. List<MetaType> mappedTypes = new List<MetaType>(rowType.InheritanceTypes); List<SqlTypeCaseWhen> whens = new List<SqlTypeCaseWhen>(); SqlTypeCaseWhen @else = null; MetaType root = rowType.InheritanceRoot; MetaDataMember discriminator = root.Discriminator; Type dt = discriminator.Type; SqlMember dm = sql.Member(item, discriminator.Member); foreach (MetaType type in mappedTypes) { if (type.HasInheritanceCode) { SqlNew defaultProjection = this.BuildProjectionInternal(item, type, type.PersistentDataMembers, allowDeferred, link, source); if (type.IsInheritanceDefault) { @else = new SqlTypeCaseWhen(null, defaultProjection); } // Add an explicit case even for the default. // Redundant results will be optimized out later. object code = InheritanceRules.InheritanceCodeForClientCompare(type.InheritanceCode, dm.SqlType); SqlExpression match = sql.Value(dt, sql.Default(discriminator), code, true, source); whens.Add(new SqlTypeCaseWhen(match, defaultProjection)); } } if (@else == null) { throw Error.EmptyCaseNotSupported(); } whens.Add(@else); // Add the else at the end. return sql.TypeCase(root.Type, root, dm, whens.ToArray(), source); } } /// <summary> /// Check whether this member will be preloaded. /// </summary> private bool IsPreloaded(MemberInfo member) { if (this.services.Context.LoadOptions == null) { return false; } return this.services.Context.LoadOptions.IsPreloaded(member); } private SqlNew BuildProjectionInternal(SqlExpression item, MetaType rowType, IEnumerable<MetaDataMember> members, bool allowDeferred, SqlLink link, Expression source) { List<SqlMemberAssign> bindings = new List<SqlMemberAssign>(); foreach (MetaDataMember mm in members) { if (allowDeferred && (mm.IsAssociation || mm.IsDeferred)) { // check if this member is the reverse association to the supplied link if (link != null && mm != link.Member && mm.IsAssociation && mm.MappedName == link.Member.MappedName && !mm.Association.IsMany && !IsPreloaded(link.Member.Member)) { // place a new link here with an expansion that is previous link's root expression. // this will allow joins caused by reverse association references to 'melt' away. :-) SqlLink mlink = this.BuildLink(item, mm, source); mlink.Expansion = link.Expression; bindings.Add(new SqlMemberAssign(mm.Member, mlink)); } else { bindings.Add(new SqlMemberAssign(mm.Member, this.BuildLink(item, mm, source))); } } else if (!mm.IsAssociation) { bindings.Add(new SqlMemberAssign(mm.Member, sql.Member(item, mm))); } } ConstructorInfo cons = rowType.Type.GetConstructor(BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic, null, System.Type.EmptyTypes, null); if (cons == null) { throw Error.MappedTypeMustHaveDefaultConstructor(rowType.Type); } return sql.New(rowType, cons, null, null, bindings, source); } private SqlLink BuildLink(SqlExpression item, MetaDataMember member, Expression source) { if (member.IsAssociation) { SqlExpression[] exprs = new SqlExpression[member.Association.ThisKey.Count]; for (int i = 0, n = exprs.Length; i < n; i++) { MetaDataMember mm = member.Association.ThisKey[i]; exprs[i] = sql.Member(item, mm.Member); } MetaType otherType = member.Association.OtherType; return new SqlLink(new object(), otherType, member.Type, typeProvider.From(member.Type), item, member, exprs, null, source); } else { // if not association link is always based on primary key MetaType thisType = member.DeclaringType; System.Diagnostics.Debug.Assert(thisType.IsEntity); List<SqlExpression> exprs = new List<SqlExpression>(); foreach (MetaDataMember mm in thisType.IdentityMembers) { exprs.Add(sql.Member(item, mm.Member)); } SqlExpression expansion = sql.Member(item, member.Member); return new SqlLink(new object(), thisType, member.Type, typeProvider.From(member.Type), item, member, exprs, expansion, source); } } internal SqlNode TranslateLink(SqlLink link, bool asExpression) { return this.TranslateLink(link, link.KeyExpressions, asExpression); } /// <summary> /// Create an Expression representing the given association and key value expressions. /// </summary> internal static Expression TranslateAssociation(DataContext context, MetaAssociation association, Expression otherSource, Expression[] keyValues, Expression thisInstance) { if (association == null) throw Error.ArgumentNull("association"); if (keyValues == null) throw Error.ArgumentNull("keyValues"); if (context.LoadOptions!=null) { LambdaExpression subquery = context.LoadOptions.GetAssociationSubquery(association.ThisMember.Member); if (subquery!=null) { RelationComposer rc = new RelationComposer(subquery.Parameters[0], association, otherSource, thisInstance); return rc.Visit(subquery.Body); } } return WhereClauseFromSourceAndKeys(otherSource, association.OtherKey.ToArray(), keyValues); } internal static Expression WhereClauseFromSourceAndKeys(Expression source, MetaDataMember[] keyMembers, Expression [] keyValues) { Type elementType = TypeSystem.GetElementType(source.Type); ParameterExpression p = Expression.Parameter(elementType, "p"); Expression whereExpression=null; for (int i = 0; i < keyMembers.Length; i++) { MetaDataMember metaMember = keyMembers[i]; Expression parameterAsDeclaring = elementType == metaMember.Member.DeclaringType ? (Expression)p : (Expression)Expression.Convert(p, metaMember.Member.DeclaringType); Expression memberExpression = (metaMember.Member is FieldInfo) ? Expression.Field(parameterAsDeclaring, (FieldInfo)metaMember.Member) : Expression.Property(parameterAsDeclaring, (PropertyInfo)metaMember.Member); Expression keyValue = keyValues[i]; if (keyValue.Type != memberExpression.Type) keyValue = Expression.Convert(keyValue, memberExpression.Type); Expression memberEqualityExpression = Expression.Equal(memberExpression, keyValue); whereExpression = (whereExpression != null) ? Expression.And(whereExpression, memberEqualityExpression) : memberEqualityExpression; } Expression sequenceExpression = Expression.Call(typeof(Enumerable), "Where", new Type[] {p.Type}, source, Expression.Lambda(whereExpression, p)); return sequenceExpression; } /// <summary> /// Composes a subquery into a linked association. /// </summary> private class RelationComposer : ExpressionVisitor { ParameterExpression parameter; MetaAssociation association; Expression otherSouce; Expression parameterReplacement; internal RelationComposer(ParameterExpression parameter, MetaAssociation association, Expression otherSouce, Expression parameterReplacement) { if (parameter==null) throw Error.ArgumentNull("parameter"); if (association == null) throw Error.ArgumentNull("association"); if (otherSouce == null) throw Error.ArgumentNull("otherSouce"); if (parameterReplacement==null) throw Error.ArgumentNull("parameterReplacement"); this.parameter = parameter; this.association = association; this.otherSouce = otherSouce; this.parameterReplacement = parameterReplacement; } internal override Expression VisitParameter(ParameterExpression p) { if (p == parameter) { return this.parameterReplacement; } return base.VisitParameter(p); } private static Expression[] GetKeyValues(Expression expr, ReadOnlyCollection<MetaDataMember> keys) { List<Expression> values = new List<Expression>(); foreach(MetaDataMember key in keys){ values.Add(Expression.PropertyOrField(expr, key.Name)); } return values.ToArray(); } internal override Expression VisitMemberAccess(MemberExpression m) { if (MetaPosition.AreSameMember(m.Member, this.association.ThisMember.Member)) { Expression[] keyValues = GetKeyValues(this.Visit(m.Expression), this.association.ThisKey); return WhereClauseFromSourceAndKeys(this.otherSouce, this.association.OtherKey.ToArray(), keyValues); } Expression exp = this.Visit(m.Expression); if (exp != m.Expression) { if (exp.Type != m.Expression.Type && m.Member.Name == "Count" && TypeSystem.IsSequenceType(exp.Type)) { return Expression.Call(typeof(Enumerable), "Count", new Type[] {TypeSystem.GetElementType(exp.Type)}, exp); } return Expression.MakeMemberAccess(exp, m.Member); } return m; } } internal SqlNode TranslateLink(SqlLink link, List<SqlExpression> keyExpressions, bool asExpression) { MetaDataMember mm = link.Member; if (mm.IsAssociation) { // Create the row source. MetaType otherType = mm.Association.OtherType; Type tableType = otherType.InheritanceRoot.Type; ITable table = this.services.Context.GetTable(tableType); Expression source = new LinkedTableExpression(link, table, typeof(IQueryable<>).MakeGenericType(otherType.Type)); // Build key expression nodes. Expression[] keyExprs = new Expression[keyExpressions.Count]; for (int i = 0; i < keyExpressions.Count; ++i) { MetaDataMember metaMember = mm.Association.OtherKey[i]; Type memberType = TypeSystem.GetMemberType(metaMember.Member); keyExprs[i] = InternalExpression.Known(keyExpressions[i], memberType); } Expression lex = link.Expression != null ? (Expression)InternalExpression.Known(link.Expression) : (Expression)Expression.Constant(null, link.Member.Member.DeclaringType); Expression expr = TranslateAssociation(this.services.Context, mm.Association, source, keyExprs, lex); // Convert QueryConverter qc = new QueryConverter(this.services, this.typeProvider, this, this.sql); SqlSelect sel = (SqlSelect)qc.ConvertInner(expr, link.SourceExpression); // Turn it into an expression is necessary SqlNode result = sel; if (asExpression) { if (mm.Association.IsMany) { result = new SqlSubSelect(SqlNodeType.Multiset, link.ClrType, link.SqlType, sel); } else { result = new SqlSubSelect(SqlNodeType.Element, link.ClrType, link.SqlType, sel); } } return result; } else { System.Diagnostics.Debug.Assert(link.Expansion != null); System.Diagnostics.Debug.Assert(link.KeyExpressions == keyExpressions); // deferred expression already defined... return link.Expansion; } } [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification="These issues are related to our use of if-then and case statements for node types, which adds to the complexity count however when reviewed they are easy to navigate and understand.")] internal SqlExpression TranslateEquals(SqlBinary expr) { System.Diagnostics.Debug.Assert( expr.NodeType == SqlNodeType.EQ || expr.NodeType == SqlNodeType.NE || expr.NodeType == SqlNodeType.EQ2V || expr.NodeType == SqlNodeType.NE2V); SqlExpression eLeft = expr.Left; SqlExpression eRight = expr.Right; if (eRight.NodeType == SqlNodeType.Element) { SqlSubSelect sub = (SqlSubSelect)eRight; SqlAlias alias = new SqlAlias(sub.Select); SqlAliasRef aref = new SqlAliasRef(alias); SqlSelect select = new SqlSelect(aref, alias, expr.SourceExpression); select.Where = sql.Binary(expr.NodeType, sql.DoNotVisitExpression(eLeft), aref); return sql.SubSelect(SqlNodeType.Exists, select); } else if (eLeft.NodeType == SqlNodeType.Element) { SqlSubSelect sub = (SqlSubSelect)eLeft; SqlAlias alias = new SqlAlias(sub.Select); SqlAliasRef aref = new SqlAliasRef(alias); SqlSelect select = new SqlSelect(aref, alias, expr.SourceExpression); select.Where = sql.Binary(expr.NodeType, sql.DoNotVisitExpression(eRight), aref); return sql.SubSelect(SqlNodeType.Exists, select); } MetaType mtLeft = TypeSource.GetSourceMetaType(eLeft, this.services.Model); MetaType mtRight = TypeSource.GetSourceMetaType(eRight, this.services.Model); if (eLeft.NodeType == SqlNodeType.TypeCase) { eLeft = BestIdentityNode((SqlTypeCase)eLeft); } if (eRight.NodeType == SqlNodeType.TypeCase) { eRight = BestIdentityNode((SqlTypeCase)eRight); } if (mtLeft.IsEntity && mtRight.IsEntity && mtLeft.Table != mtRight.Table) { throw Error.CannotCompareItemsAssociatedWithDifferentTable(); } // do simple or no translation for non-structural types if (!mtLeft.IsEntity && !mtRight.IsEntity && (eLeft.NodeType != SqlNodeType.New || eLeft.SqlType.CanBeColumn) && (eRight.NodeType != SqlNodeType.New || eRight.SqlType.CanBeColumn)) { if (expr.NodeType == SqlNodeType.EQ2V || expr.NodeType == SqlNodeType.NE2V) { return this.TranslateEqualsOp(expr.NodeType, sql.DoNotVisitExpression(expr.Left), sql.DoNotVisitExpression(expr.Right), false); } return expr; } // If the two types are not comparable, we return the predicate "1=0". if ((mtLeft != mtRight) && (mtLeft.InheritanceRoot != mtRight.InheritanceRoot)) { return sql.Binary(SqlNodeType.EQ, sql.ValueFromObject(0,expr.SourceExpression), sql.ValueFromObject(1,expr.SourceExpression)); } List<SqlExpression> exprs1; List<SqlExpression> exprs2; SqlLink link1 = eLeft as SqlLink; if (link1 != null && link1.Member.IsAssociation && link1.Member.Association.IsForeignKey) { exprs1 = link1.KeyExpressions; } else { exprs1 = this.GetIdentityExpressions(mtLeft, sql.DoNotVisitExpression(eLeft)); } SqlLink link2 = eRight as SqlLink; if (link2 != null && link2.Member.IsAssociation && link2.Member.Association.IsForeignKey) { exprs2 = link2.KeyExpressions; } else { exprs2 = this.GetIdentityExpressions(mtRight, sql.DoNotVisitExpression(eRight)); } System.Diagnostics.Debug.Assert(exprs1.Count > 0); System.Diagnostics.Debug.Assert(exprs2.Count > 0); System.Diagnostics.Debug.Assert(exprs1.Count == exprs2.Count); SqlExpression exp = null; SqlNodeType eqKind = (expr.NodeType == SqlNodeType.EQ2V || expr.NodeType == SqlNodeType.NE2V) ? SqlNodeType.EQ2V : SqlNodeType.EQ; for (int i = 0, n = exprs1.Count; i < n; i++) { SqlExpression eq = this.TranslateEqualsOp(eqKind, exprs1[i], exprs2[i], !mtLeft.IsEntity); if (exp == null) { exp = eq; } else { exp = sql.Binary(SqlNodeType.And, exp, eq); } } if (expr.NodeType == SqlNodeType.NE || expr.NodeType == SqlNodeType.NE2V) { exp = sql.Unary(SqlNodeType.Not, exp, exp.SourceExpression); } return exp; } private SqlExpression TranslateEqualsOp(SqlNodeType op, SqlExpression left, SqlExpression right, bool allowExpand) { switch (op) { case SqlNodeType.EQ: case SqlNodeType.NE: return sql.Binary(op, left, right); case SqlNodeType.EQ2V: if (SqlExpressionNullability.CanBeNull(left) != false && SqlExpressionNullability.CanBeNull(right) != false) { SqlNodeType eqOp = allowExpand ? SqlNodeType.EQ2V : SqlNodeType.EQ; return sql.Binary(SqlNodeType.Or, sql.Binary(SqlNodeType.And, sql.Unary(SqlNodeType.IsNull, (SqlExpression)SqlDuplicator.Copy(left)), sql.Unary(SqlNodeType.IsNull, (SqlExpression)SqlDuplicator.Copy(right)) ), sql.Binary(SqlNodeType.And, sql.Binary(SqlNodeType.And, sql.Unary(SqlNodeType.IsNotNull, (SqlExpression)SqlDuplicator.Copy(left)), sql.Unary(SqlNodeType.IsNotNull, (SqlExpression)SqlDuplicator.Copy(right)) ), sql.Binary(eqOp, left, right) ) ); } else { SqlNodeType eqOp = allowExpand ? SqlNodeType.EQ2V : SqlNodeType.EQ; return sql.Binary(eqOp, left, right); } case SqlNodeType.NE2V: if (SqlExpressionNullability.CanBeNull(left) != false && SqlExpressionNullability.CanBeNull(right) != false) { SqlNodeType eqOp = allowExpand ? SqlNodeType.EQ2V : SqlNodeType.EQ; return sql.Unary(SqlNodeType.Not, sql.Binary(SqlNodeType.Or, sql.Binary(SqlNodeType.And, sql.Unary(SqlNodeType.IsNull, (SqlExpression)SqlDuplicator.Copy(left)), sql.Unary(SqlNodeType.IsNull, (SqlExpression)SqlDuplicator.Copy(right)) ), sql.Binary(SqlNodeType.And, sql.Binary(SqlNodeType.And, sql.Unary(SqlNodeType.IsNotNull, (SqlExpression)SqlDuplicator.Copy(left)), sql.Unary(SqlNodeType.IsNotNull, (SqlExpression)SqlDuplicator.Copy(right)) ), sql.Binary(eqOp, left, right) ) ) ); } else { SqlNodeType neOp = allowExpand ? SqlNodeType.NE2V : SqlNodeType.NE; return sql.Binary(neOp, left, right); } default: throw Error.UnexpectedNode(op); } } internal SqlExpression TranslateLinkEquals(SqlBinary bo) { SqlLink link1 = bo.Left as SqlLink; SqlLink link2 = bo.Right as SqlLink; if ((link1 != null && link1.Member.IsAssociation && link1.Member.Association.IsForeignKey) || (link2 != null && link2.Member.IsAssociation && link2.Member.Association.IsForeignKey)) { return this.TranslateEquals(bo); } return bo; } internal SqlExpression TranslateLinkIsNull(SqlUnary expr) { System.Diagnostics.Debug.Assert(expr.NodeType == SqlNodeType.IsNull || expr.NodeType == SqlNodeType.IsNotNull); SqlLink link = expr.Operand as SqlLink; if (!(link != null && link.Member.IsAssociation && link.Member.Association.IsForeignKey)) { return expr; } List<SqlExpression> exprs = link.KeyExpressions; System.Diagnostics.Debug.Assert(exprs.Count > 0); SqlExpression exp = null; SqlNodeType combo = (expr.NodeType == SqlNodeType.IsNull) ? SqlNodeType.Or : SqlNodeType.And; for (int i = 0, n = exprs.Count; i < n; i++) { SqlExpression compare = sql.Unary(expr.NodeType, sql.DoNotVisitExpression(exprs[i]), expr.SourceExpression); if (exp == null) { exp = compare; } else { exp = sql.Binary(combo, exp, compare); } } return exp; } /// <summary> /// Find the alternative in type case that will best identify the object. /// If there is a SqlNew it is expected to have all the identity fields. /// If there is no SqlNew then we must be dealing with all literal NULL alternatives. In this case, /// just return the first one. /// </summary> private static SqlExpression BestIdentityNode(SqlTypeCase tc) { foreach (SqlTypeCaseWhen when in tc.Whens) { if (when.TypeBinding.NodeType == SqlNodeType.New) { return when.TypeBinding; } } return tc.Whens[0].TypeBinding; // There were no SqlNews, take the first alternative } private static bool IsPublic(MemberInfo mi) { FieldInfo fi = mi as FieldInfo; if (fi != null) { return fi.IsPublic; } PropertyInfo pi = mi as PropertyInfo; if (pi != null) { if (pi.CanRead) { var gm = pi.GetGetMethod(); if (gm != null) { return gm.IsPublic; } } } return false; } [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification="Unknown reason.")] private IEnumerable<MetaDataMember> GetIdentityMembers(MetaType type) { if (type.IsEntity) { return type.IdentityMembers; } return type.DataMembers.Where(m => IsPublic(m.Member)); } private List<SqlExpression> GetIdentityExpressions(MetaType type, SqlExpression expr) { List<MetaDataMember> members = GetIdentityMembers(type).ToList(); System.Diagnostics.Debug.Assert(members.Count > 0); List<SqlExpression> exprs = new List<SqlExpression>(members.Count); foreach (MetaDataMember mm in members) { exprs.Add(sql.Member((SqlExpression)SqlDuplicator.Copy(expr), mm)); } return exprs; } } }
// Copyright (C) 2014 dot42 // // Original filename: Javax.Security.Auth.cs // // 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. #pragma warning disable 1717 namespace Javax.Security.Auth { /// <summary> /// <para>Legacy security code; do not use. </para> /// </summary> /// <java-name> /// javax/security/auth/SubjectDomainCombiner /// </java-name> [Dot42.DexImport("javax/security/auth/SubjectDomainCombiner", AccessFlags = 33)] public partial class SubjectDomainCombiner : global::Java.Security.IDomainCombiner /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Ljavax/security/auth/Subject;)V", AccessFlags = 1)] public SubjectDomainCombiner(global::Javax.Security.Auth.Subject subject) /* MethodBuilder.Create */ { } /// <java-name> /// getSubject /// </java-name> [Dot42.DexImport("getSubject", "()Ljavax/security/auth/Subject;", AccessFlags = 1)] public virtual global::Javax.Security.Auth.Subject GetSubject() /* MethodBuilder.Create */ { return default(global::Javax.Security.Auth.Subject); } /// <summary> /// <para>Returns a combination of the two provided <c> ProtectionDomain </c> arrays. Implementers can simply merge the two arrays into one, remove duplicates and perform other optimizations.</para><para></para> /// </summary> /// <returns> /// <para>a single <c> ProtectionDomain </c> array computed from the two provided arrays. </para> /// </returns> /// <java-name> /// combine /// </java-name> [Dot42.DexImport("combine", "([Ljava/security/ProtectionDomain;[Ljava/security/ProtectionDomain;)[Ljava/securi" + "ty/ProtectionDomain;", AccessFlags = 1)] public virtual global::Java.Security.ProtectionDomain[] Combine(global::Java.Security.ProtectionDomain[] current, global::Java.Security.ProtectionDomain[] assigned) /* MethodBuilder.Create */ { return default(global::Java.Security.ProtectionDomain[]); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal SubjectDomainCombiner() /* TypeBuilder.AddDefaultConstructor */ { } /// <java-name> /// getSubject /// </java-name> public global::Javax.Security.Auth.Subject Subject { [Dot42.DexImport("getSubject", "()Ljavax/security/auth/Subject;", AccessFlags = 1)] get{ return GetSubject(); } } } /// <summary> /// <para>The central class of the <c> javax.security.auth </c> package representing an authenticated user or entity (both referred to as "subject"). IT defines also the static methods that allow code to be run, and do modifications according to the subject's permissions. </para><para>A subject has the following features: <ul><li><para>A set of <c> Principal </c> objects specifying the identities bound to a <c> Subject </c> that distinguish it. </para></li><li><para>Credentials (public and private) such as certificates, keys, or authentication proofs such as tickets </para></li></ul></para> /// </summary> /// <java-name> /// javax/security/auth/Subject /// </java-name> [Dot42.DexImport("javax/security/auth/Subject", AccessFlags = 49)] public sealed partial class Subject : global::Java.Io.ISerializable /* scope: __dot42__ */ { /// <summary> /// <para>The default constructor initializing the sets of public and private credentials and principals with the empty set. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public Subject() /* MethodBuilder.Create */ { } /// <summary> /// <para>The constructor for the subject, setting its public and private credentials and principals according to the arguments.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(ZLjava/util/Set;Ljava/util/Set;Ljava/util/Set;)V", AccessFlags = 1, Signature = "(ZLjava/util/Set<+Ljava/security/Principal;>;Ljava/util/Set<*>;Ljava/util/Set<*>;" + ")V")] public Subject(bool readOnly, global::Java.Util.ISet<global::Java.Security.IPrincipal> subjPrincipals, global::Java.Util.ISet<object> pubCredentials, global::Java.Util.ISet<object> privCredentials) /* MethodBuilder.Create */ { } /// <java-name> /// doAs /// </java-name> [Dot42.DexImport("doAs", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedAction;)Ljava/lang/Object;" + "", AccessFlags = 9, Signature = "<T:Ljava/lang/Object;>(Ljavax/security/auth/Subject;Ljava/security/PrivilegedActi" + "on<TT;>;)TT;")] public static T DoAs<T>(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedAction<T> privilegedAction) /* MethodBuilder.Create */ { return default(T); } /// <java-name> /// doAsPrivileged /// </java-name> [Dot42.DexImport("doAsPrivileged", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedAction;Ljava/security/Acce" + "ssControlContext;)Ljava/lang/Object;", AccessFlags = 9, Signature = "<T:Ljava/lang/Object;>(Ljavax/security/auth/Subject;Ljava/security/PrivilegedActi" + "on<TT;>;Ljava/security/AccessControlContext;)TT;")] public static T DoAsPrivileged<T>(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedAction<T> privilegedAction, global::Java.Security.AccessControlContext accessControlContext) /* MethodBuilder.Create */ { return default(T); } /// <java-name> /// doAs /// </java-name> [Dot42.DexImport("doAs", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedExceptionAction;)Ljava/lan" + "g/Object;", AccessFlags = 9, Signature = "<T:Ljava/lang/Object;>(Ljavax/security/auth/Subject;Ljava/security/PrivilegedExce" + "ptionAction<TT;>;)TT;")] public static T DoAs<T>(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedExceptionAction<T> privilegedExceptionAction) /* MethodBuilder.Create */ { return default(T); } /// <java-name> /// doAsPrivileged /// </java-name> [Dot42.DexImport("doAsPrivileged", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedExceptionAction;Ljava/secu" + "rity/AccessControlContext;)Ljava/lang/Object;", AccessFlags = 9, Signature = "<T:Ljava/lang/Object;>(Ljavax/security/auth/Subject;Ljava/security/PrivilegedExce" + "ptionAction<TT;>;Ljava/security/AccessControlContext;)TT;")] public static T DoAsPrivileged<T>(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedExceptionAction<T> privilegedExceptionAction, global::Java.Security.AccessControlContext accessControlContext) /* MethodBuilder.Create */ { return default(T); } /// <summary> /// <para>Checks two Subjects for equality. More specifically if the principals, public and private credentials are equal, equality for two <c> Subjects </c> is implied.</para><para></para> /// </summary> /// <returns> /// <para><c> true </c> if the specified <c> Subject </c> is equal to this one. </para> /// </returns> /// <java-name> /// equals /// </java-name> [Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)] public override bool Equals(object obj) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Returns this <c> Subject </c> 's Principal.</para><para></para> /// </summary> /// <returns> /// <para>this <c> Subject </c> 's Principal. </para> /// </returns> /// <java-name> /// getPrincipals /// </java-name> [Dot42.DexImport("getPrincipals", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/security/Principal;>;")] public global::Java.Util.ISet<global::Java.Security.IPrincipal> GetPrincipals() /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<global::Java.Security.IPrincipal>); } /// <summary> /// <para>Returns this <c> Subject </c> 's Principal which is a subclass of the <c> Class </c> provided.</para><para></para> /// </summary> /// <returns> /// <para>this <c> Subject </c> 's Principal. Modifications to the returned set of <c> Principal </c> s do not affect this <c> Subject </c> 's set. </para> /// </returns> /// <java-name> /// getPrincipals /// </java-name> [Dot42.DexImport("getPrincipals", "(Ljava/lang/Class;)Ljava/util/Set;", AccessFlags = 1, Signature = "<T::Ljava/security/Principal;>(Ljava/lang/Class<TT;>;)Ljava/util/Set<TT;>;")] public global::Java.Util.ISet<T> GetPrincipals<T>(global::System.Type c) /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<T>); } /// <summary> /// <para>Returns the private credentials associated with this <c> Subject </c> .</para><para></para> /// </summary> /// <returns> /// <para>the private credentials associated with this <c> Subject </c> . </para> /// </returns> /// <java-name> /// getPrivateCredentials /// </java-name> [Dot42.DexImport("getPrivateCredentials", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/lang/Object;>;")] public global::Java.Util.ISet<object> GetPrivateCredentials() /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<object>); } /// <summary> /// <para>Returns this <c> Subject </c> 's private credentials which are a subclass of the <c> Class </c> provided.</para><para></para> /// </summary> /// <returns> /// <para>this <c> Subject </c> 's private credentials. Modifications to the returned set of credentials do not affect this <c> Subject </c> 's credentials. </para> /// </returns> /// <java-name> /// getPrivateCredentials /// </java-name> [Dot42.DexImport("getPrivateCredentials", "(Ljava/lang/Class;)Ljava/util/Set;", AccessFlags = 1, Signature = "<T:Ljava/lang/Object;>(Ljava/lang/Class<TT;>;)Ljava/util/Set<TT;>;")] public global::Java.Util.ISet<T> GetPrivateCredentials<T>(global::System.Type c) /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<T>); } /// <summary> /// <para>Returns the public credentials associated with this <c> Subject </c> .</para><para></para> /// </summary> /// <returns> /// <para>the public credentials associated with this <c> Subject </c> . </para> /// </returns> /// <java-name> /// getPublicCredentials /// </java-name> [Dot42.DexImport("getPublicCredentials", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/lang/Object;>;")] public global::Java.Util.ISet<object> GetPublicCredentials() /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<object>); } /// <summary> /// <para>Returns this <c> Subject </c> 's public credentials which are a subclass of the <c> Class </c> provided.</para><para></para> /// </summary> /// <returns> /// <para>this <c> Subject </c> 's public credentials. Modifications to the returned set of credentials do not affect this <c> Subject </c> 's credentials. </para> /// </returns> /// <java-name> /// getPublicCredentials /// </java-name> [Dot42.DexImport("getPublicCredentials", "(Ljava/lang/Class;)Ljava/util/Set;", AccessFlags = 1, Signature = "<T:Ljava/lang/Object;>(Ljava/lang/Class<TT;>;)Ljava/util/Set<TT;>;")] public global::Java.Util.ISet<T> GetPublicCredentials<T>(global::System.Type c) /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<T>); } /// <summary> /// <para>Returns a hash code of this <c> Subject </c> .</para><para></para> /// </summary> /// <returns> /// <para>a hash code of this <c> Subject </c> . </para> /// </returns> /// <java-name> /// hashCode /// </java-name> [Dot42.DexImport("hashCode", "()I", AccessFlags = 1)] public override int GetHashCode() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Prevents from modifications being done to the credentials and Principal sets. After setting it to read-only this <c> Subject </c> can not be made writable again. The destroy method on the credentials still works though. </para> /// </summary> /// <java-name> /// setReadOnly /// </java-name> [Dot42.DexImport("setReadOnly", "()V", AccessFlags = 1)] public void SetReadOnly() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns whether this <c> Subject </c> is read-only or not.</para><para></para> /// </summary> /// <returns> /// <para>whether this <c> Subject </c> is read-only or not. </para> /// </returns> /// <java-name> /// isReadOnly /// </java-name> [Dot42.DexImport("isReadOnly", "()Z", AccessFlags = 1)] public bool IsReadOnly() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Returns a <c> String </c> representation of this <c> Subject </c> .</para><para></para> /// </summary> /// <returns> /// <para>a <c> String </c> representation of this <c> Subject </c> . </para> /// </returns> /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the <c> Subject </c> that was last associated with the <c> context </c> provided as argument.</para><para></para> /// </summary> /// <returns> /// <para>the <c> Subject </c> that was last associated with the <c> context </c> provided as argument. </para> /// </returns> /// <java-name> /// getSubject /// </java-name> [Dot42.DexImport("getSubject", "(Ljava/security/AccessControlContext;)Ljavax/security/auth/Subject;", AccessFlags = 9)] public static global::Javax.Security.Auth.Subject GetSubject(global::Java.Security.AccessControlContext context) /* MethodBuilder.Create */ { return default(global::Javax.Security.Auth.Subject); } /// <summary> /// <para>Returns this <c> Subject </c> 's Principal.</para><para></para> /// </summary> /// <returns> /// <para>this <c> Subject </c> 's Principal. </para> /// </returns> /// <java-name> /// getPrincipals /// </java-name> public global::Java.Util.ISet<global::Java.Security.IPrincipal> Principals { [Dot42.DexImport("getPrincipals", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/security/Principal;>;")] get{ return GetPrincipals(); } } /// <summary> /// <para>Returns the private credentials associated with this <c> Subject </c> .</para><para></para> /// </summary> /// <returns> /// <para>the private credentials associated with this <c> Subject </c> . </para> /// </returns> /// <java-name> /// getPrivateCredentials /// </java-name> public global::Java.Util.ISet<object> PrivateCredentials { [Dot42.DexImport("getPrivateCredentials", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/lang/Object;>;")] get{ return GetPrivateCredentials(); } } /// <summary> /// <para>Returns the public credentials associated with this <c> Subject </c> .</para><para></para> /// </summary> /// <returns> /// <para>the public credentials associated with this <c> Subject </c> . </para> /// </returns> /// <java-name> /// getPublicCredentials /// </java-name> public global::Java.Util.ISet<object> PublicCredentials { [Dot42.DexImport("getPublicCredentials", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/lang/Object;>;")] get{ return GetPublicCredentials(); } } } /// <summary> /// <para>Legacy security code; do not use. </para> /// </summary> /// <java-name> /// javax/security/auth/PrivateCredentialPermission /// </java-name> [Dot42.DexImport("javax/security/auth/PrivateCredentialPermission", AccessFlags = 49)] public sealed partial class PrivateCredentialPermission : global::Java.Security.Permission /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)] public PrivateCredentialPermission(string name, string action) /* MethodBuilder.Create */ { } /// <java-name> /// getPrincipals /// </java-name> [Dot42.DexImport("getPrincipals", "()[[Ljava/lang/String;", AccessFlags = 1)] public string[][] GetPrincipals() /* MethodBuilder.Create */ { return default(string[][]); } /// <java-name> /// getActions /// </java-name> [Dot42.DexImport("getActions", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetActions() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getCredentialClass /// </java-name> [Dot42.DexImport("getCredentialClass", "()Ljava/lang/String;", AccessFlags = 1)] public string GetCredentialClass() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// hashCode /// </java-name> [Dot42.DexImport("hashCode", "()I", AccessFlags = 1)] public override int GetHashCode() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// equals /// </java-name> [Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)] public override bool Equals(object @object) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// implies /// </java-name> [Dot42.DexImport("implies", "(Ljava/security/Permission;)Z", AccessFlags = 1)] public override bool Implies(global::Java.Security.Permission permission) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// newPermissionCollection /// </java-name> [Dot42.DexImport("newPermissionCollection", "()Ljava/security/PermissionCollection;", AccessFlags = 1)] public override global::Java.Security.PermissionCollection NewPermissionCollection() /* MethodBuilder.Create */ { return default(global::Java.Security.PermissionCollection); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal PrivateCredentialPermission() /* TypeBuilder.AddDefaultConstructor */ { } /// <java-name> /// getPrincipals /// </java-name> public string[][] Principals { [Dot42.DexImport("getPrincipals", "()[[Ljava/lang/String;", AccessFlags = 1)] get{ return GetPrincipals(); } } /// <java-name> /// getActions /// </java-name> public string Actions { [Dot42.DexImport("getActions", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetActions(); } } /// <java-name> /// getCredentialClass /// </java-name> public string CredentialClass { [Dot42.DexImport("getCredentialClass", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetCredentialClass(); } } } /// <summary> /// <para>Signals that the Destroyable#destroy() method failed. </para> /// </summary> /// <java-name> /// javax/security/auth/DestroyFailedException /// </java-name> [Dot42.DexImport("javax/security/auth/DestroyFailedException", AccessFlags = 33)] public partial class DestroyFailedException : global::System.Exception /* scope: __dot42__ */ { /// <summary> /// <para>Creates an exception of type <c> DestroyFailedException </c> . </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public DestroyFailedException() /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates an exception of type <c> DestroyFailedException </c> .</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public DestroyFailedException(string message) /* MethodBuilder.Create */ { } } /// <summary> /// <para>Allows for special treatment of sensitive information, when it comes to destroying or clearing of the data. </para> /// </summary> /// <java-name> /// javax/security/auth/Destroyable /// </java-name> [Dot42.DexImport("javax/security/auth/Destroyable", AccessFlags = 1537)] public partial interface IDestroyable /* scope: __dot42__ */ { /// <summary> /// <para>Erases the sensitive information. Once an object is destroyed any calls to its methods will throw an <c> IllegalStateException </c> . If it does not succeed a DestroyFailedException is thrown.</para><para></para> /// </summary> /// <java-name> /// destroy /// </java-name> [Dot42.DexImport("destroy", "()V", AccessFlags = 1025)] void Destroy() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns <c> true </c> once an object has been safely destroyed.</para><para></para> /// </summary> /// <returns> /// <para>whether the object has been safely destroyed. </para> /// </returns> /// <java-name> /// isDestroyed /// </java-name> [Dot42.DexImport("isDestroyed", "()Z", AccessFlags = 1025)] bool IsDestroyed() /* MethodBuilder.Create */ ; } /// <summary> /// <para>Legacy security code; do not use. </para> /// </summary> /// <java-name> /// javax/security/auth/AuthPermission /// </java-name> [Dot42.DexImport("javax/security/auth/AuthPermission", AccessFlags = 49)] public sealed partial class AuthPermission : global::Java.Security.BasicPermission /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public AuthPermission(string name) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)] public AuthPermission(string name, string actions) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal AuthPermission() /* TypeBuilder.AddDefaultConstructor */ { } } }
// 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.Drawing; using System.Windows.Forms; using mshtml; using OpenLiveWriter.CoreServices; using OpenLiveWriter.HtmlEditor; using OpenLiveWriter.Interop.Com; using OpenLiveWriter.Interop.Windows; using OpenLiveWriter.Mshtml; using OpenLiveWriter.PostEditor.PostHtmlEditing.Behaviors; namespace OpenLiveWriter.PostEditor.PostHtmlEditing.Behaviors { public class ResizableElementBehavior : ElementControlBehavior { private BehaviorControl _dragBufferControl; private ResizerControl _resizerControl; BehaviorDragAndDropSource _dragDropController; public ResizableElementBehavior(IHtmlEditorComponentContext editorContext) : base(editorContext) { _dragBufferControl = new BehaviorControl(); _dragBufferControl.Visible = false; _resizerControl = new ResizerControl(); _resizerControl.SizerModeChanged += new SizerModeEventHandler(resizerControl_SizerModeChanged); _resizerControl.Resized += new EventHandler(resizerControl_Resized); _resizerControl.Visible = false; Controls.Add(_dragBufferControl); Controls.Add(_resizerControl); _dragDropController = new SmartContentDragAndDropSource(editorContext); } protected override void OnElementAttached() { base.OnElementAttached(); (HTMLElement as IHTMLElement3).contentEditable = "false"; SynchronizeResizerWithElement(); } protected override void Dispose(bool disposeManagedResources) { if (!_disposed) { if (disposeManagedResources) { _resizerControl.SizerModeChanged += new SizerModeEventHandler(resizerControl_SizerModeChanged); _resizerControl.Resized -= new EventHandler(resizerControl_Resized); _dragDropController.Dispose(); } _disposed = true; } base.Dispose(disposeManagedResources); } private bool _disposed; protected override void OnSelectedChanged() { base.OnSelectedChanged(); if (Selected) { _resizerControl.Visible = true; SynchronizeResizerWithElement(); } else _resizerControl.Visible = false; PerformLayout(); Invalidate(); } protected virtual void Select() { SmartContentSelection.SelectIfSmartContentElement(EditorContext, HTMLElement); // The element is now selected, move it to the top of the list of events to get messages EditorContext.PreHandleEvent -= HandlePreHandleEvent; EditorContext.PreHandleEvent += HandlePreHandleEvent; } protected virtual void Deselect() { MarkupRange range = EditorContext.MarkupServices.CreateMarkupRange(HTMLElement); range.Start.MoveAdjacentToElement(HTMLElement, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin); range.Collapse(true); range.ToTextRange().select(); } protected override bool QueryElementSelected() { SmartContentSelection selection = EditorContext.Selection as SmartContentSelection; if (selection != null) { return selection.HTMLElement.sourceIndex == HTMLElement.sourceIndex; } else { return false; } } protected override void OnLayout() { base.OnLayout(); Rectangle elementRect = ElementRectangle; _resizerControl.VirtualLocation = new Point(elementRect.X - ResizerControl.SIZERS_PADDING, elementRect.Y - ResizerControl.SIZERS_PADDING); } public override void Draw(RECT rcBounds, RECT rcUpdate, int lDrawFlags, IntPtr hdc, IntPtr pvDrawObject) { base.Draw(rcBounds, rcUpdate, lDrawFlags, hdc, pvDrawObject); // JJA: Made this change because I noticed that unqualified calling of UpdateCursor // during painting would mess with other components trying to manipulate the cursor // for sizing (e.g. resizable smart content, tables). This basically caused the cursor // to "flash" back to the default cursor constantly during sizing. To repro, just // take out the if statement below (call UpdateCursor always) and note that if you have // two SmartContent objects on the page then the cursor flashes when sizing. // I would have removed this call entirely b/c it seems string that UpdateCursor // needs to be call from a paint event but I didn't want to disrupt whatever original // purpose this had. If we believe this call is not necessary we should definiely // remove it so it doesn't cause any more mischief! if (_resizerControl != null && _resizerControl.ActiveSizerHandle != SizerHandle.None) { UpdateCursor(Selected); } } protected override int HandlePreHandleEvent(int inEvtDispId, IHTMLEventObj pIEventObj) { if (ShouldProcessEvents(inEvtDispId, pIEventObj)) { if (inEvtDispId == DISPID_HTMLELEMENTEVENTS2.ONMOUSEDOWN) { leftMouseDown = (Control.MouseButtons & MouseButtons.Left) == MouseButtons.Left; if (!Selected && HTMLElementHelper.IsChildOrSameElement(HTMLElement, pIEventObj.srcElement)) { return HandlePreHandleEventLeftMouseButtonDown(inEvtDispId, pIEventObj); } rightMouseDown = (Control.MouseButtons & MouseButtons.Right) == MouseButtons.Right; if (rightMouseDown) { //cancel the event so that the editor doesn't try to do a right drag drop //we'll handle showing the context menu on our own. return HRESULT.S_OK; } } int controlResult = base.HandlePreHandleEvent(inEvtDispId, pIEventObj); UpdateCursor(Selected, inEvtDispId, pIEventObj); if (_resizerControl.Mode == SizerMode.Resizing) { //if the control is resizing, kill all events so that the editor doesn't //try to do a drag and drop. return HRESULT.S_OK; } else { if (_dragDropController.PreHandleEvent(inEvtDispId, pIEventObj) == HRESULT.S_OK) { return HRESULT.S_OK; } //eat the mouse events so that the editor doesn't try to //do anything funny (like opening a browser URL). //Note: Allow non-left clicks through for right-click context menus switch (inEvtDispId) { case DISPID_HTMLELEMENTEVENTS2.ONMOUSEUP: if (rightMouseDown & (Control.MouseButtons & MouseButtons.Right) != MouseButtons.Right) { rightMouseDown = false; Point p = EditorContext.PointToScreen(new Point(pIEventObj.clientX, pIEventObj.clientY)); EditorContext.ShowContextMenu(p); return HRESULT.S_OK; } return leftMouseDown ? HRESULT.S_OK : HRESULT.S_FALSE; } } return controlResult; } return HRESULT.S_FALSE; } protected bool leftMouseDown; protected bool rightMouseDown; protected int HandlePreHandleEventLeftMouseButtonDown(int inEvtDispId, IHTMLEventObj pIEventObj) { // Look to see if we were previously selected on the object bool isSelected = QueryElementSelected(); // The user has clicked in the object somewhere, so select it Select(); // Look to see if we are in a resize knob Point p = TranslateClientPointToBounds(new Point(pIEventObj.clientX, pIEventObj.clientY)); p = _resizerControl.PointToVirtualClient(p); bool closeToHandle = _resizerControl.GetHandleForPoint(p) != SizerHandle.None; //notify the drag drop controller about the mouse down so that drag can be initiated //on the first click that selects this element. (Fixes bug that required 2 clicks to //initial drag/drop). if (!isSelected && !closeToHandle) { _dragDropController.PreHandleEvent(inEvtDispId, pIEventObj); //cancel the event so that the editor doesn't try to do anything funny (like placing a caret at the click) return HRESULT.S_OK; } // The user clicked a knob, let the resize handles know. This prevents bugs where // it takes 2 clicks to catch a knob to resize _resizerControl.RaiseMouseDown(new MouseEventArgs(MouseButtons.Left, 1, p.X, p.Y, 0)); return HRESULT.S_OK; } public override bool CaptureAllEvents { get { //capture all events while resizing so that mouse movements outside the element's //bounds can still affect the element's size. return _resizerControl.Mode == SizerMode.Resizing; } } public override void OnResize(SIZE size) { base.OnResize(size); if (Attached && _resizerControl.Mode != SizerMode.Resizing) SynchronizeResizerWithElement(); } protected bool PreserveAspectRatio { get { return !_resizerControl.AllowAspectRatioDistortion; } set { _resizerControl.AllowAspectRatioDistortion = !value; } } protected bool Resizable { get { return _resizerControl.Resizable; } set { _resizerControl.Resizable = value; } } private void resizerControl_SizerModeChanged(SizerHandle handle, SizerMode mode) { SuspendLayout(); if (mode == SizerMode.Normal) { //trim the padding of the behavior for drawing the sizers OnResizeEnd(_resizerControl.SizerSize); _dragBufferControl.Visible = false; SynchronizeResizerWithElement(); } else { //notify subclasses that a resize action has been initiated bool preserveAspectRatio = handle == SizerHandle.TopLeft || handle == SizerHandle.TopRight || handle == SizerHandle.BottomLeft || handle == SizerHandle.BottomRight; OnResizeStart(ElementRectangle.Size, preserveAspectRatio); //expand the padding of the behavior region to the whole body so that the resizer //can have the freedom to paint anywhere in the document. This is important //since the resizer handles may be placed well outside of the element bounds depending //on which sizer handle was grabbed and how the element is anchored. Rectangle rect = CalculateElementRectangleRelativeToBody(HTMLElement); IHTMLElement body = (HTMLElement.document as IHTMLDocument2).body; _dragBufferControl.VirtualSize = new Size(body.offsetWidth, body.offsetHeight); _dragBufferControl.VirtualLocation = new Point(-rect.X, -rect.Y); _dragBufferControl.Visible = true; } ResumeLayout(); PerformLayout(); Invalidate(); } protected virtual void OnResizeStart(Size currentSize, bool preserveAspectRatio) { } protected void UpdateResizerAspectRatioOffset(Size size) { _resizerControl.AspectRatioOffset = size; } protected virtual void OnResizing(Size currentSize) { } protected virtual void OnResizeEnd(Size newSize) { } private void resizerControl_Resized(object sender, EventArgs e) { if (_resizerControl.Mode == SizerMode.Resizing) { OnResizing(_resizerControl.SizerSize); } } protected virtual void UpdateCursor(bool selected, int inEvtDispId, IHTMLEventObj pIEventObj) { UpdateCursor(selected); } protected void UpdateCursor(bool selected) { if (!selected) { EditorContext.OverrideCursor = true; Cursor.Current = Cursors.Arrow; return; } switch (_resizerControl.ActiveSizerHandle) { case SizerHandle.TopLeft: EditorContext.OverrideCursor = true; Cursor.Current = Cursors.SizeNWSE; break; case SizerHandle.TopRight: EditorContext.OverrideCursor = true; Cursor.Current = Cursors.SizeNESW; break; case SizerHandle.BottomLeft: EditorContext.OverrideCursor = true; Cursor.Current = Cursors.SizeNESW; break; case SizerHandle.BottomRight: EditorContext.OverrideCursor = true; Cursor.Current = Cursors.SizeNWSE; break; case SizerHandle.Top: EditorContext.OverrideCursor = true; Cursor.Current = Cursors.SizeNS; break; case SizerHandle.Right: EditorContext.OverrideCursor = true; Cursor.Current = Cursors.SizeWE; break; case SizerHandle.Bottom: EditorContext.OverrideCursor = true; Cursor.Current = Cursors.SizeNS; break; case SizerHandle.Left: EditorContext.OverrideCursor = true; Cursor.Current = Cursors.SizeWE; break; default: EditorContext.OverrideCursor = true; Cursor.Current = Cursors.Arrow; break; } } private void SynchronizeResizerWithElement() { if (Attached && _resizerControl.Mode != SizerMode.Resizing) { Rectangle rect = ElementRectangle; _resizerControl.VirtualLocation = new Point( rect.X - ResizerControl.SIZERS_PADDING, rect.Y - ResizerControl.SIZERS_PADDING); _resizerControl.VirtualSize = new Size(rect.Width + ResizerControl.SIZERS_PADDING * 2, rect.Height + ResizerControl.SIZERS_PADDING * 2); } } private Point CalculateElementLocationRelativeToBody(IHTMLElement element) { int offsetTop = 0; int offsetLeft = 0; while (element != null) { offsetTop += element.offsetTop; offsetLeft += element.offsetLeft; element = element.offsetParent; } return new Point(offsetLeft, offsetTop); } private Rectangle CalculateElementRectangleRelativeToBody(IHTMLElement element) { return new Rectangle( CalculateElementLocationRelativeToBody(element), new Size(element.offsetWidth, element.offsetHeight) ); } } }
// 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.Runtime.CompilerServices; using Xunit; namespace System.Threading.Tasks.Sources.Tests { public class ManualResetValueTaskSourceTests { [Fact] public async Task ReuseInstanceWithResets_Success() { var mrvts = new ManualResetValueTaskSource<int>(); for (short i = 42; i < 48; i++) { var ignored = Task.Delay(1).ContinueWith(_ => mrvts.SetResult(i)); Assert.Equal(i, await new ValueTask<int>(mrvts, mrvts.Version)); Assert.Equal(i, await new ValueTask<int>(mrvts, mrvts.Version)); // can use multiple times until it's reset mrvts.Reset(); } } [Fact] public void AccessWrongVersion_Fails() { var mrvts = new ManualResetValueTaskSource<int>(); mrvts.Reset(); Assert.Throws<InvalidOperationException>(() => mrvts.GetResult(0)); Assert.Throws<InvalidOperationException>(() => mrvts.GetStatus(0)); Assert.Throws<InvalidOperationException>(() => mrvts.OnCompleted(_ => { }, new object(), 0, ValueTaskSourceOnCompletedFlags.None)); Assert.Throws<InvalidOperationException>(() => mrvts.GetResult(2)); Assert.Throws<InvalidOperationException>(() => mrvts.GetStatus(2)); Assert.Throws<InvalidOperationException>(() => mrvts.OnCompleted(_ => { }, new object(), 2, ValueTaskSourceOnCompletedFlags.None)); } [Fact] public void SetTwice_Fails() { var mrvts = new ManualResetValueTaskSource<int>(); mrvts.SetResult(42); Assert.Throws<InvalidOperationException>(() => mrvts.SetResult(42)); Assert.Throws<InvalidOperationException>(() => mrvts.SetException(new Exception())); mrvts.Reset(); mrvts.SetException(new Exception()); Assert.Throws<InvalidOperationException>(() => mrvts.SetResult(42)); Assert.Throws<InvalidOperationException>(() => mrvts.SetException(new Exception())); } [Fact] public void GetResult_BeforeCompleted_Fails() { var mrvts = new ManualResetValueTaskSource<int>(); Assert.Throws<InvalidOperationException>(() => mrvts.GetResult(0)); } [Fact] public void SetResult_BeforeOnCompleted_ResultAvailableSynchronously() { var mrvts = new ManualResetValueTaskSource<int>(); mrvts.Reset(); mrvts.Reset(); Assert.Equal(2, mrvts.Version); mrvts.SetResult(42); Assert.Equal(ValueTaskSourceStatus.Succeeded, mrvts.GetStatus(2)); Assert.Equal(42, mrvts.GetResult(2)); var mres = new ManualResetEventSlim(); mrvts.OnCompleted(s => ((ManualResetEventSlim)s).Set(), mres, 2, ValueTaskSourceOnCompletedFlags.None); mres.Wait(); Assert.Equal(2, mrvts.Version); } [Fact] public async Task SetResult_AfterOnCompleted_ResultAvailableAsynchronously() { var mrvts = new ManualResetValueTaskSource<int>(); mrvts.Reset(); mrvts.Reset(); Assert.Equal(2, mrvts.Version); Assert.Equal(ValueTaskSourceStatus.Pending, mrvts.GetStatus(2)); Assert.Throws<InvalidOperationException>(() => mrvts.GetResult(2)); var onCompletedRan = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); mrvts.OnCompleted(s => ((TaskCompletionSource<bool>)s).SetResult(true), onCompletedRan, 2, ValueTaskSourceOnCompletedFlags.None); Assert.False(onCompletedRan.Task.IsCompleted); await Task.Delay(1); Assert.False(onCompletedRan.Task.IsCompleted); mrvts.SetResult(42); Assert.Equal(ValueTaskSourceStatus.Succeeded, mrvts.GetStatus(2)); Assert.Equal(42, mrvts.GetResult(2)); await onCompletedRan.Task; Assert.Equal(2, mrvts.Version); } [Fact] public void SetException_BeforeOnCompleted_ResultAvailableSynchronously() { var mrvts = new ManualResetValueTaskSource<int>(); mrvts.Reset(); mrvts.Reset(); Assert.Equal(2, mrvts.Version); var e = new FormatException(); mrvts.SetException(e); Assert.Equal(ValueTaskSourceStatus.Faulted, mrvts.GetStatus(2)); Assert.Same(e, Assert.Throws<FormatException>(() => mrvts.GetResult(2))); var mres = new ManualResetEventSlim(); mrvts.OnCompleted(s => ((ManualResetEventSlim)s).Set(), mres, 2, ValueTaskSourceOnCompletedFlags.None); mres.Wait(); Assert.Equal(2, mrvts.Version); } [Fact] public async Task SetException_AfterOnCompleted_ResultAvailableAsynchronously() { var mrvts = new ManualResetValueTaskSource<int>(); mrvts.Reset(); mrvts.Reset(); Assert.Equal(2, mrvts.Version); Assert.Equal(ValueTaskSourceStatus.Pending, mrvts.GetStatus(2)); Assert.Throws<InvalidOperationException>(() => mrvts.GetResult(2)); var onCompletedRan = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); mrvts.OnCompleted(s => ((TaskCompletionSource<bool>)s).SetResult(true), onCompletedRan, 2, ValueTaskSourceOnCompletedFlags.None); Assert.False(onCompletedRan.Task.IsCompleted); await Task.Delay(1); Assert.False(onCompletedRan.Task.IsCompleted); var e = new FormatException(); mrvts.SetException(e); Assert.Equal(ValueTaskSourceStatus.Faulted, mrvts.GetStatus(2)); Assert.Same(e, Assert.Throws<FormatException>(() => mrvts.GetResult(2))); await onCompletedRan.Task; Assert.Equal(2, mrvts.Version); } [Fact] public void SetException_OperationCanceledException_StatusIsCanceled() { var mrvts = new ManualResetValueTaskSource<int>(); var e = new OperationCanceledException(); mrvts.SetException(e); Assert.Equal(ValueTaskSourceStatus.Canceled, mrvts.GetStatus(0)); Assert.Same(e, Assert.Throws<OperationCanceledException>(() => mrvts.GetResult(0))); } [Theory] [InlineData(false)] [InlineData(true)] public void FlowContext_SetBeforeOnCompleted_FlowsIfExpected(bool flowContext) { var mres = new ManualResetEventSlim(); var mrvts = new ManualResetValueTaskSource<int>(); mrvts.RunContinuationsAsynchronously = true; mrvts.SetResult(1); var al = new AsyncLocal<int>(); al.Value = 42; mrvts.OnCompleted( _ => { Assert.Equal(flowContext ? 42 : 0, al.Value); mres.Set(); }, null, 0, flowContext ? ValueTaskSourceOnCompletedFlags.FlowExecutionContext : ValueTaskSourceOnCompletedFlags.None); mres.Wait(); } [Theory] [InlineData(false)] [InlineData(true)] public void FlowContext_SetAfterOnCompleted_FlowsIfExpected(bool flowContext) { var mres = new ManualResetEventSlim(); var mrvts = new ManualResetValueTaskSource<int>(); mrvts.RunContinuationsAsynchronously = true; var al = new AsyncLocal<int>(); al.Value = 42; mrvts.OnCompleted( _ => { Assert.Equal(flowContext ? 42 : 0, al.Value); mres.Set(); }, null, 0, flowContext ? ValueTaskSourceOnCompletedFlags.FlowExecutionContext : ValueTaskSourceOnCompletedFlags.None); mrvts.SetResult(1); mres.Wait(); } [Fact] public void OnCompleted_NullDelegate_Throws() { var mrvts = new ManualResetValueTaskSource<int>(); AssertExtensions.Throws<ArgumentNullException>("continuation", () => mrvts.OnCompleted(null, new object(), 0, ValueTaskSourceOnCompletedFlags.None)); } [Fact] public void OnCompleted_UsedTwiceBeforeCompletion_Throws() { var mrvts = new ManualResetValueTaskSource<int>(); mrvts.OnCompleted(_ => { }, null, 0, ValueTaskSourceOnCompletedFlags.None); Assert.Throws<InvalidOperationException>(() => mrvts.OnCompleted(_ => { }, null, 0, ValueTaskSourceOnCompletedFlags.None)); } [Fact] public void OnCompleted_UnknownFlagsIgnored() { var mrvts = new ManualResetValueTaskSource<int>(); mrvts.OnCompleted(_ => { }, new object(), 0, (ValueTaskSourceOnCompletedFlags)int.MaxValue); } [Theory] [InlineData(false)] [InlineData(true)] public void OnCompleted_ContinuationAlwaysInvokedAsynchronously(bool runContinuationsAsynchronously) { var mres = new ManualResetEventSlim(); var mrvts = new ManualResetValueTaskSource<int>() { RunContinuationsAsynchronously = runContinuationsAsynchronously }; for (short i = 0; i < 10; i++) { int threadId = Environment.CurrentManagedThreadId; mrvts.SetResult(42); mrvts.OnCompleted( _ => { Assert.NotEqual(threadId, Environment.CurrentManagedThreadId); mres.Set(); }, null, i, ValueTaskSourceOnCompletedFlags.None); mrvts.Reset(); mres.Wait(); mres.Reset(); } } [Theory] [InlineData(false)] [InlineData(true)] public void SetResult_RunContinuationsAsynchronously_ContinuationInvokedAccordingly(bool runContinuationsAsynchronously) { var mres = new ManualResetEventSlim(); var mrvts = new ManualResetValueTaskSource<int>() { RunContinuationsAsynchronously = runContinuationsAsynchronously }; for (short i = 0; i < 10; i++) { int threadId = Environment.CurrentManagedThreadId; mrvts.OnCompleted( _ => { Assert.Equal(!runContinuationsAsynchronously, threadId == Environment.CurrentManagedThreadId); mres.Set(); }, null, i, ValueTaskSourceOnCompletedFlags.None); mrvts.SetResult(42); mres.Wait(); mrvts.Reset(); mres.Reset(); } } [Theory] [InlineData(false, false, false)] [InlineData(false, false, true)] [InlineData(false, true, false)] [InlineData(false, true, true)] [InlineData(true, false, false)] [InlineData(true, false, true)] [InlineData(true, true, false)] [InlineData(true, true, true)] public async Task SynchronizationContext_CaptureIfRequested( bool runContinuationsAsynchronously, bool captureSyncCtx, bool setBeforeOnCompleted) { await Task.Run(async () => // escape xunit sync ctx { var mrvts = new ManualResetValueTaskSource<int>() { RunContinuationsAsynchronously = runContinuationsAsynchronously }; if (setBeforeOnCompleted) { mrvts.SetResult(42); } var tcs = new TaskCompletionSource<bool>(); var sc = new TrackingSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(sc); Assert.Equal(0, sc.Posts); mrvts.OnCompleted( _ => tcs.SetResult(true), null, 0, captureSyncCtx ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); SynchronizationContext.SetSynchronizationContext(null); if (!setBeforeOnCompleted) { mrvts.SetResult(42); } await tcs.Task; Assert.Equal(captureSyncCtx ? 1 : 0, sc.Posts); }); } [Theory] [InlineData(false, false, false)] [InlineData(false, false, true)] [InlineData(false, true, false)] [InlineData(false, true, true)] [InlineData(true, false, false)] [InlineData(true, false, true)] [InlineData(true, true, false)] [InlineData(true, true, true)] public async Task TaskScheduler_CaptureIfRequested( bool runContinuationsAsynchronously, bool captureTaskScheduler, bool setBeforeOnCompleted) { await Task.Run(async () => // escape xunit sync ctx { var mrvts = new ManualResetValueTaskSource<int>() { RunContinuationsAsynchronously = runContinuationsAsynchronously }; if (setBeforeOnCompleted) { mrvts.SetResult(42); } var tcs = new TaskCompletionSource<bool>(); var ts = new TrackingTaskScheduler(); Assert.Equal(0, ts.QueueTasks); await Task.Factory.StartNew(() => { mrvts.OnCompleted( _ => tcs.SetResult(true), null, 0, captureTaskScheduler ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); }, CancellationToken.None, TaskCreationOptions.None, ts); if (!setBeforeOnCompleted) { mrvts.SetResult(42); } await tcs.Task; Assert.Equal(captureTaskScheduler ? 2 : 1, ts.QueueTasks); }); } private sealed class TrackingSynchronizationContext : SynchronizationContext { public int Posts; public override void Post(SendOrPostCallback d, object state) { Interlocked.Increment(ref Posts); base.Post(d, state); } } private sealed class TrackingTaskScheduler : TaskScheduler { public int QueueTasks; protected override void QueueTask(Task task) { QueueTasks++; ThreadPool.QueueUserWorkItem(_ => TryExecuteTask(task)); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) => false; protected override IEnumerable<Task> GetScheduledTasks() => null; } [Fact] public async Task AsyncEnumerable_Success() { // Equivalent to: // int total = 0; // foreach async(int i in CountAsync(20)) // { // total += i; // } // Assert.Equal(190, i); IAsyncEnumerator<int> enumerator = CountAsync(20).GetAsyncEnumerator(); try { int total = 0; while (await enumerator.MoveNextAsync()) { total += enumerator.Current; } Assert.Equal(190, total); } finally { await enumerator.DisposeAsync(); } } // Approximate compiler-generated code for: // internal static AsyncEnumerable<int> CountAsync(int items) // { // for (int i = 0; i < items; i++) // { // await Task.Delay(i).ConfigureAwait(false); // yield return i; // } // } internal static IAsyncEnumerable<int> CountAsync(int items) => new CountAsyncEnumerable(items); private sealed class CountAsyncEnumerable : IAsyncEnumerable<int>, // used as the enumerable itself IAsyncEnumerator<int>, // used as the enumerator returned from first call to enumerable's GetAsyncEnumerator IValueTaskSource<bool>, // used as the backing store behind the ValueTask<bool> returned from each MoveNextAsync IAsyncStateMachine // uses existing builder's support for ExecutionContext, optimized awaits, etc. { // This implementation will generally incur only two allocations of overhead // for the entire enumeration: // - The CountAsyncEnumerable object itself. // - A throw-away task object inside of _builder. // The task built by the builder isn't necessary, but using the _builder allows // this implementation to a) avoid needing to be concerned with ExecutionContext // flowing, and b) enables the implementation to take advantage of optimizations // such as avoiding Action allocation when all awaited types are known to corelib. private const int StateStart = -1; private const int StateDisposed = -2; private const int StateCtor = -3; /// <summary>Current state of the state machine.</summary> private int _state = StateCtor; /// <summary>All of the logic for managing the IValueTaskSource implementation</summary> private ManualResetValueTaskSourceCore<bool> _vts; // mutable struct; do not make this readonly /// <summary>Builder used for efficiently waiting and appropriately managing ExecutionContext.</summary> private AsyncIteratorMethodBuilder _builder = AsyncIteratorMethodBuilder.Create(); // mutable struct; do not make this readonly private readonly int _param_items; private int _local_items; private int _local_i; private TaskAwaiter _awaiter0; private CancellationToken _cancellationToken; public CountAsyncEnumerable(int items) { _local_items = _param_items = items; } public IAsyncEnumerator<int> GetAsyncEnumerator(CancellationToken cancellationToken = default) { CountAsyncEnumerable cae = Interlocked.CompareExchange(ref _state, StateStart, StateCtor) == StateCtor ? this : new CountAsyncEnumerable(_param_items) { _state = StateStart }; cae._cancellationToken = cancellationToken; return cae; } public ValueTask<bool> MoveNextAsync() { _vts.Reset(); CountAsyncEnumerable inst = this; _builder.MoveNext(ref inst); // invokes MoveNext, protected by ExecutionContext guards switch (_vts.GetStatus(_vts.Version)) { case ValueTaskSourceStatus.Succeeded: return new ValueTask<bool>(_vts.GetResult(_vts.Version)); default: return new ValueTask<bool>(this, _vts.Version); } } public ValueTask DisposeAsync() { _vts.Reset(); _state = StateDisposed; return default; } public int Current { get; private set; } public void MoveNext() { try { switch (_state) { case StateStart: _local_i = 0; goto case 0; case 0: if (_local_i < _local_items) { _awaiter0 = Task.Delay(_local_i, _cancellationToken).GetAwaiter(); if (!_awaiter0.IsCompleted) { _state = 1; CountAsyncEnumerable inst = this; _builder.AwaitUnsafeOnCompleted(ref _awaiter0, ref inst); return; } goto case 1; } _state = int.MaxValue; _builder.Complete(); _vts.SetResult(false); return; case 1: _awaiter0.GetResult(); _awaiter0 = default; Current = _local_i; _state = 2; _vts.SetResult(true); return; case 2: _local_i++; _state = 0; goto case 0; default: throw new InvalidOperationException(); } } catch (Exception e) { _state = int.MaxValue; _builder.Complete(); _vts.SetException(e); // see https://github.com/dotnet/roslyn/issues/26567; we may want to move this out of the catch return; } } void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { } bool IValueTaskSource<bool>.GetResult(short token) => _vts.GetResult(token); ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token) => _vts.GetStatus(token); void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) => _vts.OnCompleted(continuation, state, token, flags); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq.Expressions; using System.Web.Mvc; using MvcContrib.FluentHtml.Behaviors; using MvcContrib.FluentHtml.Elements; using MvcContrib.FluentHtml.Expressions; using MvcContrib.UnitTests.FluentHtml.Fakes; using MvcContrib.UnitTests.FluentHtml.Helpers; using NUnit.Framework; using HtmlAttribute=MvcContrib.FluentHtml.Html.HtmlAttribute; namespace MvcContrib.UnitTests.FluentHtml { [TestFixture] public class ValidationMemberBehaviorTests { ModelStateDictionary stateDictionary; private Expression<Func<FakeModel, object>> expression; private ValidationBehavior target; [SetUp] public void SetUp() { stateDictionary = new ModelStateDictionary(); expression = null; target = new ValidationBehavior(() => stateDictionary); } [Test] public void element_for_member_with_no_error_renders_with_no_class() { expression = x => x.Price; var textbox = new TextBox(expression.GetNameFor(), null, new List<IBehaviorMarker> { target }); var element = textbox.ToString().ShouldHaveHtmlNode("Price"); element.ShouldNotHaveAttribute(HtmlAttribute.Class); } [Test] public void element_for_member_with_error_renders_with_default_error_class() { stateDictionary.AddModelError("Price", "Something bad happened"); expression = x => x.Price; var textbox = new TextBox(expression.GetNameFor(), null, new List<IBehaviorMarker> { target }); var element = textbox.ToString().ShouldHaveHtmlNode("Price"); element.ShouldHaveAttribute(HtmlAttribute.Class).WithValue("input-validation-error"); } [Test] public void element_for_member_with_error_renders_with_specified_error_class_and_specified_other_class() { stateDictionary.AddModelError("Price", "Something bad happened"); target = new ValidationBehavior(() => stateDictionary, "my-error-class"); expression = x => x.Price; var textbox = new TextBox(expression.GetNameFor(), null, new List<IBehaviorMarker> { target }) .Class("another-class"); var element = textbox.ToString().ShouldHaveHtmlNode("Price"); element.ShouldHaveAttribute(HtmlAttribute.Class).Value .ShouldContain("another-class") .ShouldContain("my-error-class"); } [Test] public void element_with_error_renders_with_attempted_value() { stateDictionary.AddModelError("Price", "Something bad happened"); stateDictionary["Price"].Value = new ValueProviderResult("bad value", "bad value", CultureInfo.CurrentCulture); expression = x => x.Price; var textbox = new TextBox(expression.GetNameFor(), expression.GetMemberExpression(), new List<IBehaviorMarker> { target }); var element = textbox.ToString().ShouldHaveHtmlNode("Price"); element.ShouldHaveAttribute(HtmlAttribute.Value).WithValue("bad value"); } [Test] public void element_without_error_renders_with_attempted_value() { stateDictionary.Add("Price", new ModelState() { Value = new ValueProviderResult("foo", "foo", CultureInfo.CurrentCulture) }); expression = x => x.Price; var textbox = new TextBox(expression.GetNameFor(), expression.GetMemberExpression(), new List<IBehaviorMarker> { target }); var element = textbox.ToString().ShouldHaveHtmlNode("Price"); element.ShouldHaveAttribute(HtmlAttribute.Value).WithValue("foo"); } [Test] public void does_not_add_css_class_when_retrieving_value_from_modelstate_with_no_error() { stateDictionary.Add("Price", new ModelState() { Value = new ValueProviderResult("foo", "foo", CultureInfo.CurrentCulture) }); expression = x => x.Price; var textbox = new TextBox(expression.GetNameFor(), null, new List<IBehaviorMarker> { target }); var element = textbox.ToString().ShouldHaveHtmlNode("Price"); element.ShouldHaveAttribute(HtmlAttribute.Value).WithValue("foo"); element.ShouldNotHaveAttribute(HtmlAttribute.Class); } [Test] public void handles_checkboxes_correctly() { stateDictionary.AddModelError("Done", "Foo"); stateDictionary["Done"].Value = new ValueProviderResult(new[] { "true", "false" }, "true", CultureInfo.CurrentCulture); expression = x => x.Done; var checkbox = new CheckBox(expression.GetNameFor(), expression.GetMemberExpression(), new List<IBehaviorMarker> { target }); var element = checkbox.ToString().ShouldHaveHtmlNode("Done"); element.ShouldHaveAttribute("checked").WithValue("checked"); element.ShouldHaveAttribute("value").WithValue("true"); } [Test] public void when_handling_checkbox_does_not_fall_back_to_default_behavior() { stateDictionary.AddModelError("Done", "Foo"); stateDictionary["Done"].Value = new ValueProviderResult(new[] { "false", "false" }, "false", CultureInfo.CurrentCulture); expression = x => x.Done; var checkbox = new CheckBox(expression.GetNameFor(), expression.GetMemberExpression(), new List<IBehaviorMarker> { target }); var element = checkbox.ToString().ShouldHaveHtmlNode("Done"); element.ShouldHaveAttribute("value").WithValue("true"); } [Test] public void does_not_restore_value_for_password_field() { stateDictionary.Add("Password", new ModelState() { Value = new ValueProviderResult("foo", "foo", CultureInfo.CurrentCulture) }); expression = x => x.Password; var passwordField = new Password(expression.GetNameFor(), expression.GetMemberExpression(), new List<IBehaviorMarker> { target }); var element = passwordField.ToString().ShouldHaveHtmlNode("Password"); element.ShouldHaveAttribute(HtmlAttribute.Value).WithValue(""); } [Test] public void restore_checked_from_radio_set() { stateDictionary.Add("Selection", new ModelState { Value = new ValueProviderResult((int)FakeEnum.Two, "2", CultureInfo.CurrentCulture) }); expression = x => x.Selection; var html = new RadioSet(expression.GetNameFor(), expression.GetMemberExpression(), new List<IBehaviorMarker> { target }).Options<FakeEnum>().ToString(); var element = html.ShouldHaveHtmlNode("Selection"); var options = element.ShouldHaveChildNodesCount(8); RadioSetTests.VerifyOption("Selection", (int)FakeEnum.Zero, FakeEnum.Zero, options[0], options[1],false); RadioSetTests.VerifyOption("Selection", (int)FakeEnum.One, FakeEnum.One, options[2], options[3],false); RadioSetTests.VerifyOption("Selection", (int)FakeEnum.Two, FakeEnum.Two, options[4], options[5],true); RadioSetTests.VerifyOption("Selection", (int)FakeEnum.Three, FakeEnum.Three, options[6], options[7],false); } [Test] public void Should_apply_model_state_value_to_textbox_value() { stateDictionary.SetModelValue("foo", new ValueProviderResult("bar", "bar", CultureInfo.InvariantCulture)); var textbox = new TextBox("foo"); target.Execute(textbox); textbox.ToString() .ShouldHaveHtmlNode("foo") .ShouldHaveAttribute(HtmlAttribute.Value) .Value .ShouldEqual("bar"); } [Test] public void Should_apply_model_state_value_to_textarea_value() { stateDictionary.SetModelValue("foo", new ValueProviderResult("bar", "bar", CultureInfo.InvariantCulture)); var textArea = new TextArea("foo"); target.Execute(textArea); textArea.ToString() .ShouldHaveHtmlNode("foo") .ShouldHaveInnerTextEqual("bar"); } [Test] public void Should_apply_model_state_value_to_select_element_selected_value() { stateDictionary.SetModelValue("foo", new ValueProviderResult(1, "1", CultureInfo.InvariantCulture)); var select = new Select("foo").Options(new[] { 1, 2 }); target.Execute(select); var selectedValues = ConvertToGeneric<string>(select.SelectedValues); select.SelectedValues.ShouldNotBeNull(); selectedValues.ShouldCount(1); Assert.Contains("1", selectedValues); } [Test] public void Should_apply_model_state_values_to_multiselect_element_selected_values() { stateDictionary.SetModelValue("foo", new ValueProviderResult(new[] { 1, 3 }, "1,3", CultureInfo.InvariantCulture)); var select = new MultiSelect("foo").Options(new[] { 1, 2, 3 }); target.Execute(select); var selectedValues = ConvertToGeneric<string>(select.SelectedValues); select.SelectedValues.ShouldNotBeNull(); selectedValues.ShouldCount(2); Assert.Contains("1", selectedValues); Assert.Contains("3", selectedValues); } [Test] public void Should_apply_model_state_values_to_multiselect_element_selected_values_when_only_one_item_is_in_model_state() { stateDictionary.SetModelValue("foo", new ValueProviderResult(1, "1", CultureInfo.InvariantCulture)); var select = new MultiSelect("foo").Options(new[] { 1, 2, 3 }); target.Execute(select); var selectedValues = ConvertToGeneric<string>(select.SelectedValues); select.SelectedValues.ShouldNotBeNull(); selectedValues.ShouldCount(1); Assert.Contains("1", selectedValues); } private static List<T> ConvertToGeneric<T>(IEnumerable e) { var result = new List<T>(); var enumerator = e.GetEnumerator(); while (enumerator.MoveNext()) { result.Add((T)enumerator.Current); } return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using Xunit; namespace System.Security.Cryptography.EcDsa.Tests { public partial class ECDsaTests { public static IEnumerable<object[]> AllImplementations() { return new[] { new ECDsa[] { ECDsaFactory.Create() }, new ECDsa[] { new ECDsaStub() }, }; } [Theory, MemberData(nameof(AllImplementations))] public void SignDataByteArray_NullData_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>("data", () => ecdsa.SignData((byte[])null, default(HashAlgorithmName))); } [Theory, MemberData(nameof(AllImplementations))] public void SignDataByteArray_DefaultHashAlgorithm_ThrowsArgumentException(ECDsa ecdsa) { Assert.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.SignData(new byte[0], default(HashAlgorithmName))); } [Theory, MemberData(nameof(AllImplementations))] public void SignDataByteArraySpan_NullData_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>("data", () => ecdsa.SignData(null, -1, -1, default(HashAlgorithmName))); } [Theory, MemberData(nameof(AllImplementations))] public void SignDataByteArraySpan_NegativeOffset_ThrowsArgumentOutOfRangeException(ECDsa ecdsa) { Assert.Throws<ArgumentOutOfRangeException>("offset", () => ecdsa.SignData(new byte[0], -1, -1, default(HashAlgorithmName))); } [Theory, MemberData(nameof(AllImplementations))] public void SignDataByteArraySpan_OffsetGreaterThanCount_ThrowsArgumentOutOfRangeException(ECDsa ecdsa) { Assert.Throws<ArgumentOutOfRangeException>("offset", () => ecdsa.SignData(new byte[0], 2, 1, default(HashAlgorithmName))); } [Theory, MemberData(nameof(AllImplementations))] public void SignDataByteArraySpan_NegativeCount_ThrowsArgumentOutOfRangeException(ECDsa ecdsa) { Assert.Throws<ArgumentOutOfRangeException>("count", () => ecdsa.SignData(new byte[0], 0, -1, default(HashAlgorithmName))); } [Theory, MemberData(nameof(AllImplementations))] public void SignDataByteArraySpan_CountGreaterThanLengthMinusOffset_ThrowsArgumentOutOfRangeException(ECDsa ecdsa) { Assert.Throws<ArgumentOutOfRangeException>("count", () => ecdsa.SignData(new byte[0], 0, 1, default(HashAlgorithmName))); } [Theory, MemberData(nameof(AllImplementations))] public void SignDataByteArraySpan_DefaultHashAlgorithm_ThrowsArgumentException(ECDsa ecdsa) { Assert.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.SignData(new byte[0], 0, 0, default(HashAlgorithmName))); } [Theory, MemberData(nameof(AllImplementations))] public void SignDataByteArraySpan_EmptyHashAlgorithm_ThrowsArgumentException(ECDsa ecdsa) { Assert.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.SignData(new byte[10], 0, 10, new HashAlgorithmName(""))); } [Theory, MemberData(nameof(AllImplementations))] public void SignDataStream_NullData_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>("data", () => ecdsa.SignData((Stream)null, default(HashAlgorithmName))); } [Theory, MemberData(nameof(AllImplementations))] public void SignDataStream_DefaultHashAlgorithm_ThrowsArgumentException(ECDsa ecdsa) { Assert.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.SignData(new MemoryStream(), default(HashAlgorithmName))); } [Theory, MemberData(nameof(AllImplementations))] public void VerifyDataByteArray_NullData_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>("data", () => ecdsa.VerifyData((byte[])null, null, default(HashAlgorithmName))); } [Theory, MemberData(nameof(AllImplementations))] public void VerifyDataByteArray_NullSignature_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>("signature", () => ecdsa.VerifyData(new byte[0], null, default(HashAlgorithmName))); } [Theory, MemberData(nameof(AllImplementations))] public void VerifyDataByteArray_DefaultHashAlgorithm_ThrowsArgumentException(ECDsa ecdsa) { Assert.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.VerifyData(new byte[0], new byte[0], default(HashAlgorithmName))); } [Theory, MemberData(nameof(AllImplementations))] public void VerifyDataByteArraySpan_NullData_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>("data", () => ecdsa.VerifyData((byte[])null, -1, -1, null, default(HashAlgorithmName))); } [Theory, MemberData(nameof(AllImplementations))] public void VerifyDataByteArraySpan_NegativeOffset_ThrowsArgumentOutOfRangeException(ECDsa ecdsa) { Assert.Throws<ArgumentOutOfRangeException>("offset", () => ecdsa.VerifyData(new byte[0], -1, -1, null, default(HashAlgorithmName))); } [Theory, MemberData(nameof(AllImplementations))] public void VerifyDataByteArraySpan_OffsetGreaterThanCount_ThrowsArgumentOutOfRangeException(ECDsa ecdsa) { Assert.Throws<ArgumentOutOfRangeException>("offset", () => ecdsa.VerifyData(new byte[0], 2, 1, null, default(HashAlgorithmName))); } [Theory, MemberData(nameof(AllImplementations))] public void VerifyDataByteArraySpan_NegativeCount_ThrowsArgumentOutOfRangeException(ECDsa ecdsa) { Assert.Throws<ArgumentOutOfRangeException>("count", () => ecdsa.VerifyData(new byte[0], 0, -1, null, default(HashAlgorithmName))); } [Theory, MemberData(nameof(AllImplementations))] public void VerifyDataByteArraySpan_CountGreaterThanLengthMinusOffset_ThrowsArgumentOutOfRangeException(ECDsa ecdsa) { Assert.Throws<ArgumentOutOfRangeException>("count", () => ecdsa.VerifyData(new byte[0], 0, 1, null, default(HashAlgorithmName))); } [Theory, MemberData(nameof(AllImplementations))] public void VerifyDataByteArraySpan_NullSignature_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>("signature", () => ecdsa.VerifyData(new byte[0], 0, 0, null, default(HashAlgorithmName))); } [Theory, MemberData(nameof(AllImplementations))] public void VerifyDataByteArraySpan_EmptyHashAlgorithm_ThrowsArgumentException(ECDsa ecdsa) { Assert.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.VerifyData(new byte[10], 0, 10, new byte[0], new HashAlgorithmName(""))); } [Theory, MemberData(nameof(AllImplementations))] public void VerifyDataStream_NullData_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>("data", () => ecdsa.VerifyData((Stream)null, null, default(HashAlgorithmName))); } [Theory, MemberData(nameof(AllImplementations))] public void VerifyDataStream_NullSignature_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>("signature", () => ecdsa.VerifyData(new MemoryStream(), null, default(HashAlgorithmName))); } [Theory, MemberData(nameof(AllImplementations))] public void VerifyDataStream_DefaultHashAlgorithm_ThrowsArgumentException(ECDsa ecdsa) { Assert.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.VerifyData(new MemoryStream(), new byte[0], default(HashAlgorithmName))); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static IEnumerable<object[]> RealImplementations() { return new[] { new ECDsa[] { ECDsaFactory.Create() }, }; } [Theory, MemberData(nameof(RealImplementations))] public void SignHash_NullHash_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>( "hash", () => ecdsa.SignHash(null)); } [Theory, MemberData(nameof(RealImplementations))] public void VerifyHash_NullHash_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>( "hash", () => ecdsa.VerifyHash(null, null)); } [Theory, MemberData(nameof(RealImplementations))] public void VerifyHash_NullSignature_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>( "signature", () => ecdsa.VerifyHash(new byte[0], null)); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// [Theory, MemberData(nameof(RealImplementations))] public void SignDataByteArray_UnsupportedHashAlgorithm_ThrowsCryptographicException(ECDsa ecdsa) { Assert.Throws<CryptographicException>( () => ecdsa.SignData(new byte[0], new HashAlgorithmName("NOT_A_REAL_HASH_ALGORITHM"))); } [Theory, MemberData(nameof(RealImplementations))] public void SignDataByteArraySpan_UnsupportedHashAlgorithm_ThrowsCryptographicException(ECDsa ecdsa) { Assert.Throws<CryptographicException>( () => ecdsa.SignData(new byte[0], 0, 0, new HashAlgorithmName("NOT_A_REAL_HASH_ALGORITHM"))); } [Theory, MemberData(nameof(RealImplementations))] public void SignDataStream_UnsupportedHashAlgorithm_ThrowsCryptographicException(ECDsa ecdsa) { Assert.Throws<CryptographicException>( () => ecdsa.SignData(new MemoryStream(), new HashAlgorithmName("NOT_A_REAL_HASH_ALGORITHM"))); } [Theory, MemberData(nameof(RealImplementations))] public void VerifyDataByteArray_UnsupportedHashAlgorithm_ThrowsCryptographicException(ECDsa ecdsa) { Assert.Throws<CryptographicException>( () => ecdsa.VerifyData(new byte[0], new byte[0], new HashAlgorithmName("NOT_A_REAL_HASH_ALGORITHM"))); } [Theory, MemberData(nameof(RealImplementations))] public void VerifyDataByteArraySpan_UnsupportedHashAlgorithm_ThrowsCryptographicException(ECDsa ecdsa) { Assert.Throws<CryptographicException>( () => ecdsa.VerifyData(new byte[0], 0, 0, new byte[0], new HashAlgorithmName("NOT_A_REAL_HASH_ALGORITHM"))); } [Theory, MemberData(nameof(RealImplementations))] public void VerifyDataStream_UnsupportedHashAlgorithm_ThrowsCryptographicException(ECDsa ecdsa) { Assert.Throws<CryptographicException>( () => ecdsa.VerifyData(new MemoryStream(), new byte[0], new HashAlgorithmName("NOT_A_REAL_HASH_ALGORITHM"))); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// [Theory, MemberData(nameof(RealImplementations))] public void SignData_MaxOffset_ZeroLength_NoThrow(ECDsa ecdsa) { // Explicitly larger than Array.Empty byte[] data = new byte[10]; byte[] signature = ecdsa.SignData(data, data.Length, 0, HashAlgorithmName.SHA256); Assert.True(ecdsa.VerifyData(Array.Empty<byte>(), signature, HashAlgorithmName.SHA256)); } [Theory, MemberData(nameof(RealImplementations))] public void VerifyData_MaxOffset_ZeroLength_NoThrow(ECDsa ecdsa) { // Explicitly larger than Array.Empty byte[] data = new byte[10]; byte[] signature = ecdsa.SignData(Array.Empty<byte>(), HashAlgorithmName.SHA256); Assert.True(ecdsa.VerifyData(data, data.Length, 0, signature, HashAlgorithmName.SHA256)); } [Theory, MemberData(nameof(RealImplementations))] public void Roundtrip_WithOffset(ECDsa ecdsa) { byte[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; byte[] halfData = { 5, 6, 7, 8, 9 }; byte[] dataSignature = ecdsa.SignData(data, 5, data.Length - 5, HashAlgorithmName.SHA256); byte[] halfDataSignature = ecdsa.SignData(halfData, HashAlgorithmName.SHA256); // Cross-feed the VerifyData calls to prove that both offsets work Assert.True(ecdsa.VerifyData(data, 5, data.Length - 5, halfDataSignature, HashAlgorithmName.SHA256)); Assert.True(ecdsa.VerifyData(halfData, dataSignature, HashAlgorithmName.SHA256)); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// [Theory] [InlineData(256)] [InlineData(384)] [InlineData(521)] public void CreateKey(int keySize) { using (ECDsa ecdsa = ECDsaFactory.Create()) { // Step 1, don't throw here. ecdsa.KeySize = keySize; // Step 2, ensure the key was generated without throwing. ecdsa.SignData(Array.Empty<byte>(), HashAlgorithmName.SHA256); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static IEnumerable<object[]> InteroperableSignatureConfigurations() { foreach (HashAlgorithmName hashAlgorithm in new[] { HashAlgorithmName.MD5, HashAlgorithmName.SHA1, HashAlgorithmName.SHA256, HashAlgorithmName.SHA384, HashAlgorithmName.SHA512 }) { yield return new object[] { ECDsaFactory.Create(), hashAlgorithm }; } } [Theory, MemberData(nameof(InteroperableSignatureConfigurations))] public void SignVerify_InteroperableSameKeys_RoundTripsUnlessTampered(ECDsa ecdsa, HashAlgorithmName hashAlgorithm) { byte[] data = Encoding.UTF8.GetBytes("something to repeat and sign"); // large enough to make hashing work though multiple iterations and not a multiple of 4KB it uses. byte[] dataArray = new byte[33333]; MemoryStream dataStream = new MemoryStream(dataArray, true); while (dataStream.Position < dataArray.Length - data.Length) { dataStream.Write(data, 0, data.Length); } dataStream.Position = 0; byte[] dataArray2 = new byte[dataArray.Length + 2]; dataArray.CopyTo(dataArray2, 1); ArraySegment<byte> dataSpan = new ArraySegment<byte>(dataArray2, 1, dataArray.Length); HashAlgorithm halg; if (hashAlgorithm == HashAlgorithmName.MD5) halg = MD5.Create(); else if (hashAlgorithm == HashAlgorithmName.SHA1) halg = SHA1.Create(); else if (hashAlgorithm == HashAlgorithmName.SHA256) halg = SHA256.Create(); else if (hashAlgorithm == HashAlgorithmName.SHA384) halg = SHA384.Create(); else if (hashAlgorithm == HashAlgorithmName.SHA512) halg = SHA512.Create(); else throw new Exception("Hash algorithm not supported."); List<byte[]> signatures = new List<byte[]>(6); // Compute a signature using each of the SignData overloads. Then, verify it using each // of the VerifyData overloads, and VerifyHash overloads. // // Then, verify that VerifyHash fails if the data is tampered with. signatures.Add(ecdsa.SignData(dataArray, hashAlgorithm)); signatures.Add(ecdsa.SignData(dataSpan.Array, dataSpan.Offset, dataSpan.Count, hashAlgorithm)); signatures.Add(ecdsa.SignData(dataStream, hashAlgorithm)); dataStream.Position = 0; signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataArray))); signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataSpan.Array, dataSpan.Offset, dataSpan.Count))); signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataStream))); dataStream.Position = 0; foreach (byte[] signature in signatures) { Assert.True(ecdsa.VerifyData(dataArray, signature, hashAlgorithm), "Verify 1"); Assert.True(ecdsa.VerifyData(dataSpan.Array, dataSpan.Offset, dataSpan.Count, signature, hashAlgorithm), "Verify 2"); Assert.True(ecdsa.VerifyData(dataStream, signature, hashAlgorithm), "Verify 3"); Assert.True(dataStream.Position == dataArray.Length, "Check stream read 3A"); dataStream.Position = 0; Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataArray), signature), "Verify 4"); Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataSpan.Array, dataSpan.Offset, dataSpan.Count), signature), "Verify 5"); Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataStream), signature), "Verify 6"); Assert.True(dataStream.Position == dataArray.Length, "Check stream read 6A"); dataStream.Position = 0; } int distinctSignatures = signatures.Distinct(new ByteArrayComparer()).Count(); Assert.True(distinctSignatures == signatures.Count, "Signing should be randomized"); foreach (byte[] signature in signatures) { signature[signature.Length - 1] ^= 0xFF; // flip some bits Assert.False(ecdsa.VerifyData(dataArray, signature, hashAlgorithm), "Verify Tampered 1"); Assert.False(ecdsa.VerifyData(dataSpan.Array, dataSpan.Offset, dataSpan.Count, signature, hashAlgorithm), "Verify Tampered 2"); Assert.False(ecdsa.VerifyData(dataStream, signature, hashAlgorithm), "Verify Tampered 3"); Assert.True(dataStream.Position == dataArray.Length, "Check stream read 3B"); dataStream.Position = 0; Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataArray), signature), "Verify Tampered 4"); Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataSpan.Array, dataSpan.Offset, dataSpan.Count), signature), "Verify Tampered 5"); Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataStream), signature), "Verify Tampered 6"); Assert.True(dataStream.Position == dataArray.Length, "Check stream read 6B"); dataStream.Position = 0; } } private class ByteArrayComparer : IEqualityComparer<byte[]> { public bool Equals(byte[] x, byte[] y) { return x.SequenceEqual(y); } public int GetHashCode(byte[] obj) { int h = 5381; foreach (byte b in obj) { h = ((h << 5) + h) ^ b.GetHashCode(); } return h; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using JCG = J2N.Collections.Generic; namespace YAF.Lucene.Net.Util.Fst { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using DataInput = YAF.Lucene.Net.Store.DataInput; using DataOutput = YAF.Lucene.Net.Store.DataOutput; // TODO: merge with PagedBytes, except PagedBytes doesn't // let you read while writing which FST needs internal class BytesStore : DataOutput { private readonly JCG.List<byte[]> blocks = new JCG.List<byte[]>(); private readonly int blockSize; private readonly int blockBits; private readonly int blockMask; private byte[] current; private int nextWrite; public BytesStore(int blockBits) { this.blockBits = blockBits; blockSize = 1 << blockBits; blockMask = blockSize - 1; nextWrite = blockSize; } /// <summary> /// Pulls bytes from the provided <see cref="Store.IndexInput"/>. </summary> public BytesStore(DataInput @in, long numBytes, int maxBlockSize) { int blockSize = 2; int blockBits = 1; while (blockSize < numBytes && blockSize < maxBlockSize) { blockSize *= 2; blockBits++; } this.blockBits = blockBits; this.blockSize = blockSize; this.blockMask = blockSize - 1; long left = numBytes; while (left > 0) { int chunk = (int)Math.Min(blockSize, left); byte[] block = new byte[chunk]; @in.ReadBytes(block, 0, block.Length); blocks.Add(block); left -= chunk; } // So .getPosition still works nextWrite = blocks[blocks.Count - 1].Length; } /// <summary> /// Absolute write byte; you must ensure dest is &lt; max /// position written so far. /// </summary> public virtual void WriteByte(int dest, byte b) { int blockIndex = dest >> blockBits; byte[] block = blocks[blockIndex]; block[dest & blockMask] = b; } public override void WriteByte(byte b) { if (nextWrite == blockSize) { current = new byte[blockSize]; blocks.Add(current); nextWrite = 0; } current[nextWrite++] = b; } public override void WriteBytes(byte[] b, int offset, int len) { while (len > 0) { int chunk = blockSize - nextWrite; if (len <= chunk) { System.Buffer.BlockCopy(b, offset, current, nextWrite, len); nextWrite += len; break; } else { if (chunk > 0) { Array.Copy(b, offset, current, nextWrite, chunk); offset += chunk; len -= chunk; } current = new byte[blockSize]; blocks.Add(current); nextWrite = 0; } } } internal virtual int BlockBits { get { return blockBits; } } /// <summary> /// Absolute writeBytes without changing the current /// position. Note: this cannot "grow" the bytes, so you /// must only call it on already written parts. /// </summary> internal virtual void WriteBytes(long dest, byte[] b, int offset, int len) { //System.out.println(" BS.writeBytes dest=" + dest + " offset=" + offset + " len=" + len); Debug.Assert(dest + len <= Position, "dest=" + dest + " pos=" + Position + " len=" + len); // Note: weird: must go "backwards" because copyBytes // calls us with overlapping src/dest. If we // go forwards then we overwrite bytes before we can // copy them: /* int blockIndex = dest >> blockBits; int upto = dest & blockMask; byte[] block = blocks.get(blockIndex); while (len > 0) { int chunk = blockSize - upto; System.out.println(" cycle chunk=" + chunk + " len=" + len); if (len <= chunk) { System.arraycopy(b, offset, block, upto, len); break; } else { System.arraycopy(b, offset, block, upto, chunk); offset += chunk; len -= chunk; blockIndex++; block = blocks.get(blockIndex); upto = 0; } } */ long end = dest + len; int blockIndex = (int)(end >> blockBits); int downTo = (int)(end & blockMask); if (downTo == 0) { blockIndex--; downTo = blockSize; } byte[] block = blocks[blockIndex]; while (len > 0) { //System.out.println(" cycle downTo=" + downTo + " len=" + len); if (len <= downTo) { //System.out.println(" final: offset=" + offset + " len=" + len + " dest=" + (downTo-len)); Array.Copy(b, offset, block, downTo - len, len); break; } else { len -= downTo; //System.out.println(" partial: offset=" + (offset + len) + " len=" + downTo + " dest=0"); Array.Copy(b, offset + len, block, 0, downTo); blockIndex--; block = blocks[blockIndex]; downTo = blockSize; } } } /// <summary> /// Absolute copy bytes self to self, without changing the /// position. Note: this cannot "grow" the bytes, so must /// only call it on already written parts. /// </summary> public virtual void CopyBytes(long src, long dest, int len) { //System.out.println("BS.copyBytes src=" + src + " dest=" + dest + " len=" + len); Debug.Assert(src < dest); // Note: weird: must go "backwards" because copyBytes // calls us with overlapping src/dest. If we // go forwards then we overwrite bytes before we can // copy them: /* int blockIndex = src >> blockBits; int upto = src & blockMask; byte[] block = blocks.get(blockIndex); while (len > 0) { int chunk = blockSize - upto; System.out.println(" cycle: chunk=" + chunk + " len=" + len); if (len <= chunk) { writeBytes(dest, block, upto, len); break; } else { writeBytes(dest, block, upto, chunk); blockIndex++; block = blocks.get(blockIndex); upto = 0; len -= chunk; dest += chunk; } } */ long end = src + len; int blockIndex = (int)(end >> blockBits); int downTo = (int)(end & blockMask); if (downTo == 0) { blockIndex--; downTo = blockSize; } byte[] block = blocks[blockIndex]; while (len > 0) { //System.out.println(" cycle downTo=" + downTo); if (len <= downTo) { //System.out.println(" finish"); WriteBytes(dest, block, downTo - len, len); break; } else { //System.out.println(" partial"); len -= downTo; WriteBytes(dest + len, block, 0, downTo); blockIndex--; block = blocks[blockIndex]; downTo = blockSize; } } } /// <summary> /// Writes an <see cref="int"/> at the absolute position without /// changing the current pointer. /// <para/> /// NOTE: This was writeInt() in Lucene /// </summary> public virtual void WriteInt32(long pos, int value) { int blockIndex = (int)(pos >> blockBits); int upto = (int)(pos & blockMask); byte[] block = blocks[blockIndex]; int shift = 24; for (int i = 0; i < 4; i++) { block[upto++] = (byte)(value >> shift); shift -= 8; if (upto == blockSize) { upto = 0; blockIndex++; block = blocks[blockIndex]; } } } /// <summary> /// Reverse from <paramref name="srcPos"/>, inclusive, to <paramref name="destPos"/>, inclusive. </summary> public virtual void Reverse(long srcPos, long destPos) { Debug.Assert(srcPos < destPos); Debug.Assert(destPos < Position); //System.out.println("reverse src=" + srcPos + " dest=" + destPos); int srcBlockIndex = (int)(srcPos >> blockBits); int src = (int)(srcPos & blockMask); byte[] srcBlock = blocks[srcBlockIndex]; int destBlockIndex = (int)(destPos >> blockBits); int dest = (int)(destPos & blockMask); byte[] destBlock = blocks[destBlockIndex]; //System.out.println(" srcBlock=" + srcBlockIndex + " destBlock=" + destBlockIndex); int limit = (int)(destPos - srcPos + 1) / 2; for (int i = 0; i < limit; i++) { //System.out.println(" cycle src=" + src + " dest=" + dest); byte b = srcBlock[src]; srcBlock[src] = destBlock[dest]; destBlock[dest] = b; src++; if (src == blockSize) { srcBlockIndex++; srcBlock = blocks[srcBlockIndex]; //System.out.println(" set destBlock=" + destBlock + " srcBlock=" + srcBlock); src = 0; } dest--; if (dest == -1) { destBlockIndex--; destBlock = blocks[destBlockIndex]; //System.out.println(" set destBlock=" + destBlock + " srcBlock=" + srcBlock); dest = blockSize - 1; } } } public virtual void SkipBytes(int len) { while (len > 0) { int chunk = blockSize - nextWrite; if (len <= chunk) { nextWrite += len; break; } else { len -= chunk; current = new byte[blockSize]; blocks.Add(current); nextWrite = 0; } } } public virtual long Position { get { return ((long)blocks.Count - 1) * blockSize + nextWrite; } } /// <summary> /// Pos must be less than the max position written so far! /// i.e., you cannot "grow" the file with this! /// </summary> public virtual void Truncate(long newLen) { Debug.Assert(newLen <= Position); Debug.Assert(newLen >= 0); int blockIndex = (int)(newLen >> blockBits); nextWrite = (int)(newLen & blockMask); if (nextWrite == 0) { blockIndex--; nextWrite = blockSize; } blocks.RemoveRange(blockIndex + 1, blocks.Count - (blockIndex + 1)); if (newLen == 0) { current = null; } else { current = blocks[blockIndex]; } Debug.Assert(newLen == Position); } public virtual void Finish() { if (current != null) { byte[] lastBuffer = new byte[nextWrite]; Array.Copy(current, 0, lastBuffer, 0, nextWrite); blocks[blocks.Count - 1] = lastBuffer; current = null; } } /// <summary> /// Writes all of our bytes to the target <see cref="DataOutput"/>. </summary> public virtual void WriteTo(DataOutput @out) { foreach (byte[] block in blocks) { @out.WriteBytes(block, 0, block.Length); } } public virtual FST.BytesReader GetForwardReader() { if (blocks.Count == 1) { return new ForwardBytesReader(blocks[0]); } return new ForwardBytesReaderAnonymousInner(this); } private class ForwardBytesReaderAnonymousInner : FST.BytesReader { private readonly BytesStore outerInstance; public ForwardBytesReaderAnonymousInner(BytesStore outerInstance) { this.outerInstance = outerInstance; nextRead = outerInstance.blockSize; } private byte[] current; private int nextBuffer; private int nextRead; public override byte ReadByte() { if (nextRead == outerInstance.blockSize) { current = outerInstance.blocks[nextBuffer++]; nextRead = 0; } return current[nextRead++]; } public override void SkipBytes(int count) { Position = Position + count; } public override void ReadBytes(byte[] b, int offset, int len) { while (len > 0) { int chunkLeft = outerInstance.blockSize - nextRead; if (len <= chunkLeft) { Array.Copy(current, nextRead, b, offset, len); nextRead += len; break; } else { if (chunkLeft > 0) { Array.Copy(current, nextRead, b, offset, chunkLeft); offset += chunkLeft; len -= chunkLeft; } current = outerInstance.blocks[nextBuffer++]; nextRead = 0; } } } public override long Position { get { return ((long)nextBuffer - 1) * outerInstance.blockSize + nextRead; } set { int bufferIndex = (int)(value >> outerInstance.blockBits); nextBuffer = bufferIndex + 1; current = outerInstance.blocks[bufferIndex]; nextRead = (int)(value & outerInstance.blockMask); Debug.Assert(this.Position == value, "pos=" + value + " Position=" + this.Position); } } public override bool IsReversed { get { return false; } } } public virtual FST.BytesReader GetReverseReader() { return GetReverseReader(true); } internal virtual FST.BytesReader GetReverseReader(bool allowSingle) { if (allowSingle && blocks.Count == 1) { return new ReverseBytesReader(blocks[0]); } return new ReverseBytesReaderAnonymousInner(this); } private class ReverseBytesReaderAnonymousInner : FST.BytesReader { private readonly BytesStore outerInstance; public ReverseBytesReaderAnonymousInner(BytesStore outerInstance) { this.outerInstance = outerInstance; current = outerInstance.blocks.Count == 0 ? null : outerInstance.blocks[0]; nextBuffer = -1; nextRead = 0; } private byte[] current; private int nextBuffer; private int nextRead; public override byte ReadByte() { if (nextRead == -1) { current = outerInstance.blocks[nextBuffer--]; nextRead = outerInstance.blockSize - 1; } return current[nextRead--]; } public override void SkipBytes(int count) { Position = Position - count; } public override void ReadBytes(byte[] b, int offset, int len) { for (int i = 0; i < len; i++) { b[offset + i] = ReadByte(); } } public override long Position { get { return ((long)nextBuffer + 1) * outerInstance.blockSize + nextRead; } set { // NOTE: a little weird because if you // setPosition(0), the next byte you read is // bytes[0] ... but I would expect bytes[-1] (ie, // EOF)...? int bufferIndex = (int)(value >> outerInstance.blockBits); nextBuffer = bufferIndex - 1; current = outerInstance.blocks[bufferIndex]; nextRead = (int)(value & outerInstance.blockMask); Debug.Assert(this.Position == value, "value=" + value + " this.Position=" + this.Position); } } public override bool IsReversed { get { return true; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using System.Text; namespace Microsoft.DotNet.Build.Tasks { public class GenerateResourcesCode : BuildTask { private TargetLanguage _targetLanguage = TargetLanguage.CSharp; private StreamWriter _targetStream; private string _resourcesName; private string _srClassName; private string _srNamespace; [Required] public string ResxFilePath { get; set; } [Required] public string OutputSourceFilePath { get; set; } [Required] public string AssemblyName { get; set; } /// <summary> /// Defines the namespace in which the generated SR class is defined. If not specified defaults to System. /// </summary> public string SRNamespace { get; set; } /// <summary> /// Defines the class in which the ResourceType property is generated. If not specified defaults to SR. /// </summary> public string SRClassName { get; set; } /// <summary> /// Defines the namespace in which the generated resources class is defined. If not specified defaults to SRNamespace. /// </summary> public string ResourcesNamespace { get; set; } /// <summary> /// Defines the class in which the resource properties/constants are generated. If not specified defaults to SRClassName. /// </summary> public string ResourcesClassName { get; set; } /// <summary> /// Emit constant key strings instead of properties that retrieve values. /// </summary> public bool AsConstants { get; set; } /// <summary> /// Emit enum of Resource IDs instead of a class with properties that retrieve values. /// </summary> public bool AsEnum { get; set; } public override bool Execute() { if (AsConstants && AsEnum) { Log.LogError($"{nameof(AsConstants)} and {nameof(AsEnum)} cannot both be set to true."); } try { _resourcesName = "FxResources." + AssemblyName; _srNamespace = String.IsNullOrEmpty(SRNamespace) ? "System" : SRNamespace; _srClassName = String.IsNullOrEmpty(SRClassName) ? "SR" : SRClassName; using (_targetStream = File.CreateText(OutputSourceFilePath)) { if (String.Equals(Path.GetExtension(OutputSourceFilePath), ".vb", StringComparison.OrdinalIgnoreCase)) { _targetLanguage = TargetLanguage.VB; } WriteSR(); WriteResources(); } } catch (Exception e) { Log.LogError("Failed to generate the resource code with error:\n" + e.Message); return false; // fail the task } return true; } private void WriteSR() { string commentPrefix = _targetLanguage == TargetLanguage.CSharp ? "// " : "' "; _targetStream.WriteLine(commentPrefix + "Do not edit this file manually it is auto-generated during the build based on the .resx file for this project."); if (_targetLanguage == TargetLanguage.CSharp) { _targetStream.WriteLine($"namespace {_srNamespace}"); _targetStream.WriteLine("{"); _targetStream.WriteLine(""); _targetStream.WriteLine($" internal static partial class {_srClassName}"); _targetStream.WriteLine(" {"); _targetStream.WriteLine($" internal static System.Type ResourceType {{ get; }} = typeof({_resourcesName}.SR); "); _targetStream.WriteLine(" }"); _targetStream.WriteLine("}"); _targetStream.WriteLine(""); _targetStream.WriteLine($"namespace {_resourcesName}"); _targetStream.WriteLine("{"); _targetStream.WriteLine(" // The type of this class is used to create the ResourceManager instance as the type name matches the name of the embedded resources file"); _targetStream.WriteLine(" internal static class SR"); _targetStream.WriteLine(" {"); _targetStream.WriteLine(" }"); _targetStream.WriteLine("}"); _targetStream.WriteLine(""); } else { _targetStream.WriteLine($"Namespace {_srNamespace}"); _targetStream.WriteLine(""); _targetStream.WriteLine($" Friend Partial Class {_srClassName}"); _targetStream.WriteLine($" Friend Shared ReadOnly Property ResourceType As System.Type = GetType({_resourcesName}.SR)"); _targetStream.WriteLine(" End Class"); _targetStream.WriteLine("End Namespace"); _targetStream.WriteLine(""); _targetStream.WriteLine($"Namespace {_resourcesName}"); _targetStream.WriteLine(" ' The type of this class is used to create the ResourceManager instance as the type name matches the name of the embedded resources file"); _targetStream.WriteLine(" Friend Class SR"); _targetStream.WriteLine(" "); _targetStream.WriteLine(" End Class"); _targetStream.WriteLine("End Namespace"); _targetStream.WriteLine(""); } } private void WriteResources() { var resources = GetResources(ResxFilePath); var accessorNamespace = String.IsNullOrEmpty(ResourcesNamespace) ? _srNamespace : ResourcesNamespace; var accessorClassName = String.IsNullOrEmpty(ResourcesClassName) ? _srClassName : ResourcesClassName; if (_targetLanguage == TargetLanguage.CSharp) { _targetStream.WriteLine($"namespace {accessorNamespace}"); _targetStream.WriteLine("{"); _targetStream.WriteLine(""); var accessor = AsEnum ? "enum" : "static partial class"; _targetStream.WriteLine($" internal {accessor} {accessorClassName}"); _targetStream.WriteLine(" {"); _targetStream.WriteLine(""); } else { _targetStream.WriteLine($"Namespace {accessorNamespace}"); _targetStream.WriteLine(""); var accessor = AsEnum ? "Enum" : "Partial Class"; _targetStream.WriteLine($" Friend {accessor} {accessorClassName}"); _targetStream.WriteLine(""); } if (AsConstants) { foreach (var resourcePair in resources) { WriteResourceConstant((string)resourcePair.Key); } } else if (AsEnum) { foreach(var resourcePair in resources) { _targetStream.Write($" {resourcePair.Key}"); if (_targetLanguage == TargetLanguage.CSharp) { _targetStream.WriteLine(","); } else { _targetStream.WriteLine(); } } } else { _targetStream.WriteLine(_targetLanguage == TargetLanguage.CSharp ? "#if !DEBUGRESOURCES" : "#If Not DEBUGRESOURCES Then"); foreach (var resourcePair in resources) { WriteResourceProperty(resourcePair.Key, _targetLanguage == TargetLanguage.CSharp ? "null" : "Nothing"); } _targetStream.WriteLine(_targetLanguage == TargetLanguage.CSharp ? "#else" : "#Else"); foreach (var resourcePair in resources) { WriteResourceProperty(resourcePair.Key, CreateStringLiteral(resourcePair.Value)); } _targetStream.WriteLine(_targetLanguage == TargetLanguage.CSharp ? "#endif" : "#End If"); } if (_targetLanguage == TargetLanguage.CSharp) { _targetStream.WriteLine(" }"); _targetStream.WriteLine("}"); } else { var accessor = AsEnum ? "Enum" : "Class"; _targetStream.WriteLine($" End {accessor}"); _targetStream.WriteLine("End Namespace"); } } private string CreateStringLiteral(string original) { StringBuilder stringLiteral = new StringBuilder(original.Length + 3); if (_targetLanguage == TargetLanguage.CSharp) { stringLiteral.Append('@'); } stringLiteral.Append('\"'); for (var i = 0; i < original.Length; i++) { // duplicate '"' for VB and C# if (original[i] == '\"') { stringLiteral.Append("\""); } stringLiteral.Append(original[i]); } stringLiteral.Append('\"'); return stringLiteral.ToString(); } private void WriteResourceProperty(string resourceId, string resourceValueLiteral) { if (_targetLanguage == TargetLanguage.CSharp) { _targetStream.WriteLine($" internal static string {resourceId} {{"); _targetStream.WriteLine($" get {{ return {_srNamespace}.{_srClassName}.GetResourceString(\"{resourceId}\", {resourceValueLiteral}); }}"); _targetStream.WriteLine($" }}"); } else { _targetStream.WriteLine($" Friend Shared ReadOnly Property {resourceId} As String"); _targetStream.WriteLine($" Get"); _targetStream.WriteLine($" Return {_srNamespace}.{_srClassName}.GetResourceString(\"{resourceId}\", {resourceValueLiteral})"); _targetStream.WriteLine($" End Get"); _targetStream.WriteLine($" End Property"); } } private void WriteResourceConstant(string resourceId) { if (_targetLanguage == TargetLanguage.CSharp) { _targetStream.WriteLine($" internal const string {resourceId} = \"{resourceId}\";"); } else { _targetStream.WriteLine($" Friend Const {resourceId} As String = \"{resourceId}\""); } } private enum TargetLanguage { CSharp, VB } internal List<KeyValuePair<string, string>> GetResources(string fileName) { // preserve the ordering of the resources List<KeyValuePair<string, string>> resources = new List<KeyValuePair<string, string>>(); HashSet<string> resourceIds = new HashSet<string>(); XDocument doc = XDocument.Load(fileName, LoadOptions.PreserveWhitespace); foreach (XElement dataElem in doc.Element("root").Elements("data")) { string name = dataElem.Attribute("name").Value; string value = dataElem.Element("value").Value; if (resourceIds.Contains(name)) { Log.LogError($"Duplicate resource id \"{name}\""); } else { resourceIds.Add(name); resources.Add(new KeyValuePair<string, string>(name, value)); } } return resources; } } }
using System; using System.Collections.Generic; using System.Linq; using GameFramework.Audio; using GameFramework.Drawing; using GameFramework.Hexes; using GameFramework.Sprites; using GameFramework.Tiles; namespace GameFramework { public abstract class GameResourceManager : IComposite, INavigatorMetadataProvider { #region Fields private readonly Dictionary<string, Texture> textureDictionary; private readonly Dictionary<string, HexSheet> hexSheetDictionary; private readonly Dictionary<string, TileSheet> tileSheetDictionary; private readonly Dictionary<string, SpriteSheet> spriteSheetDictionary; private readonly Dictionary<string, DrawingFont> drawingFontDictionary; private readonly Dictionary<string, Sound> soundDictionary; private readonly Dictionary<string, Music> musicDictionary; #endregion #region Constructor protected GameResourceManager() { this.textureDictionary = new Dictionary<string, Texture>(); this.hexSheetDictionary = new Dictionary<string, HexSheet>(); this.tileSheetDictionary = new Dictionary<string, TileSheet>(); this.spriteSheetDictionary = new Dictionary<string, SpriteSheet>(); this.drawingFontDictionary = new Dictionary<string, DrawingFont>(); this.soundDictionary = new Dictionary<string, Sound>(); this.musicDictionary = new Dictionary<string, Music>(); this.AddHexSheet(NullHexDefinition.CreateInstance().Sheet); this.AddTileSheet(NullTileDefinition.CreateInstance().Sheet); } #endregion public IEnumerable<object> Children { get { return this.drawingFontDictionary.Values.Cast<object>() .Concat(this.textureDictionary.Values) .Concat(this.tileSheetDictionary.Values) .Concat(this.hexSheetDictionary.Values) .Concat(this.spriteSheetDictionary.Values); } } public NavigatorMetadata GetMetadata() { // TODO: Need new node kind and label return new NavigatorMetadata("Resource Manager", NodeKind.Utility); } #region Texture public void AddTexture(Texture texture) { this.textureDictionary.Add(texture.Name, texture); } public void AddTexture(string assetName) { this.textureDictionary.Add(assetName, null); } public void AddTexture(string assetName, Texture texture) { this.textureDictionary.Add(assetName, texture); texture.Name = assetName; } public Texture GetTexture(string assetName) { Texture texture; if (!this.textureDictionary.TryGetValue(assetName, out texture)) { texture = this.CreateTexture(assetName); this.textureDictionary[assetName] = texture; } return texture; } protected virtual Texture CreateTexture(string assetName) { throw new NotSupportedException(); } #endregion #region HexSheet public void AddHexSheet(HexSheet sheet) { this.hexSheetDictionary.Add(sheet.Name, sheet); } public HexSheet GetHexSheet(string name) { return this.hexSheetDictionary[name]; } #endregion #region TileSheet public void AddTileSheet(TileSheet sheet) { this.tileSheetDictionary.Add(sheet.Name, sheet); } public TileSheet GetTileSheet(string name) { TileSheet result; return this.tileSheetDictionary.TryGetValue(name, out result) ? result : null; } #endregion #region SpriteSheet public void AddSpriteSheet(SpriteSheet sheet) { this.spriteSheetDictionary.Add(sheet.Name, sheet); } public SpriteSheet GetSpriteSheet(string name) { return this.spriteSheetDictionary[name]; } #endregion #region SpriteFont public virtual DrawingFont GetDrawingFont(string assetName) { DrawingFont drawingFont; if (!this.drawingFontDictionary.TryGetValue(assetName, out drawingFont)) { drawingFont = this.CreateDrawingFont(assetName); this.drawingFontDictionary[assetName] = drawingFont; } return drawingFont; } protected virtual DrawingFont CreateDrawingFont(string assetName) { return new DrawingFont { Name = assetName, //Font = this.contentManager.Load<SpriteFont>(assetName) }; } #endregion #region Sound public Sound GetSoundEffect(string assetName) { Sound sound; if (!this.soundDictionary.TryGetValue(assetName, out sound)) { sound = this.CreateSoundEffect(assetName); this.soundDictionary[assetName] = sound; } return sound; } protected virtual Sound CreateSoundEffect(string assetName) { throw new NotSupportedException(); } #endregion #region Music public Music GetMusic(string assetName) { Music music; if (!this.musicDictionary.TryGetValue(assetName, out music)) { music = this.CreateMusic(assetName); this.musicDictionary[assetName] = music; } return music; } protected abstract Music CreateMusic(string assetName); #endregion } }
using System.IO.Compression; using Prototest.Library.Version1; namespace Protobuild.Tests { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; public abstract class ProtobuildTest { private readonly IAssert _assert; private string m_TestName; private string m_TestLocation; private string _protobuildName; protected ProtobuildTest(IAssert assert) { _assert = assert; } protected void SetupTest(string name, bool isPackTest = false, string parent = null, string child = null) { // This is used to ensure Protobuild.exe is referenced. _protobuildName = typeof(Protobuild.Bootstrap.Program).FullName; this.m_TestName = name; var location = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName; var dataLocation = Path.Combine(location, "..", "..", "..", "..", "TestData", this.m_TestName); var protobuildLocation = AppDomain.CurrentDomain.GetAssemblies().First(x => x.GetName().Name == "Protobuild").Location; this.m_TestLocation = dataLocation; this.DeployProtobuildToTestFolder(dataLocation, protobuildLocation, isPackTest, parent, child); } private void PurgeSolutionsAndProjects(string dataLocation) { var dir = new DirectoryInfo(dataLocation); foreach (var solution in dir.GetFiles("*.sln")) { solution.Delete(); } foreach (var project in dir.GetFiles("*.csproj")) { project.Delete(); } foreach (var sub in dir.GetDirectories()) { this.PurgeSolutionsAndProjects(sub.FullName); } } private void DeployProtobuildToTestFolder(string dataLocation, string protobuildLocation, bool isPackTest, string parent, string child) { if (parent == null) { File.Copy(protobuildLocation, Path.Combine(dataLocation, "Protobuild.exe"), true); } else { File.Copy(parent, Path.Combine(dataLocation, "Protobuild.exe"), true); } if (!isPackTest) { foreach (var dir in new DirectoryInfo(dataLocation).GetDirectories()) { if (dir.GetDirectories().Any(x => x.Name == "Build")) { this.DeployProtobuildToTestFolder(dir.FullName, protobuildLocation, false, child, child); } } } } protected Tuple<string, string> Generate(string platform = null, string args = null, bool expectFailure = false, bool capture = false, string hostPlatform = null) { return this.OtherMode("generate", (platform ?? "Windows") + " " + args, expectFailure, capture: capture, hostPlatform: hostPlatform); } protected Tuple<string, string> OtherMode(string mode, string args = null, bool expectFailure = false, bool purge = true, bool capture = false, string workingSubdirectory = null, string hostPlatform = null) { if (purge) { this.PurgeSolutionsAndProjects(this.m_TestLocation); } var stdout = string.Empty; var stderr = string.Empty; var simulate = string.Empty; if (hostPlatform != null) { simulate = "--simulate-host-platform " + hostPlatform + " "; } var pi = new ProcessStartInfo { FileName = Path.Combine(this.m_TestLocation, "Protobuild.exe"), Arguments = simulate + "--" + mode + " " + (args ?? string.Empty), WorkingDirectory = workingSubdirectory != null ? Path.Combine(this.m_TestLocation, workingSubdirectory) : this.m_TestLocation, CreateNoWindow = capture, UseShellExecute = false, RedirectStandardError = capture, RedirectStandardOutput = capture, }; var p = new Process { StartInfo = pi }; if (capture) { p.OutputDataReceived += (sender, eventArgs) => { if (!string.IsNullOrEmpty(eventArgs.Data)) { stdout += eventArgs.Data + "\n"; } }; p.ErrorDataReceived += (sender, eventArgs) => { if (!string.IsNullOrEmpty(eventArgs.Data)) { stderr += eventArgs.Data + "\n"; } }; } p.Start(); if (capture) { p.BeginOutputReadLine(); p.BeginErrorReadLine(); } p.WaitForExit(); if (p.ExitCode == 134) { // SIGSEGV due to Mono bugs, try again. return this.OtherMode(mode, args, expectFailure, purge, capture); } if (expectFailure) { _assert.True(1 == p.ExitCode, "Expected command '" + pi.FileName + " " + pi.Arguments + "' to fail, but got successful exit code."); } else { _assert.True(0 == p.ExitCode, "Expected command '" + pi.FileName + " " + pi.Arguments + "' to succeed, but got failure exit code."); } return new Tuple<string, string>(stdout, stderr); } protected string ReadFile(string path) { path = path.Replace('\\', Path.DirectorySeparatorChar); using (var reader = new StreamReader(Path.Combine(this.m_TestLocation, path))) { return reader.ReadToEnd(); } } protected string GetPath(string path) { path = path.Replace('\\', Path.DirectorySeparatorChar); return Path.Combine(this.m_TestLocation, path); } protected Dictionary<string, byte[]> LoadPackage(string path) { if (path.EndsWith(".tar.lzma")) { using (var lzma = new FileStream(Path.Combine(m_TestLocation, path), FileMode.Open, FileAccess.Read, FileShare.None)) { using (var decompress = new MemoryStream()) { LZMA.LzmaHelper.Decompress(lzma, decompress); decompress.Seek(0, SeekOrigin.Begin); var archive = new tar_cs.TarReader(decompress); var deduplicator = new Reduplicator(); return deduplicator.UnpackTarToMemory(archive); } } } else if (path.EndsWith(".tar.gz")) { using (var file = new FileStream(Path.Combine(m_TestLocation, path), FileMode.Open, FileAccess.Read, FileShare.None)) { using (var gzip = new GZipStream(file, CompressionMode.Decompress)) { var archive = new tar_cs.TarReader(gzip); var deduplicator = new Reduplicator(); return deduplicator.UnpackTarToMemory(archive); } } } else { throw new NotSupportedException(); } } protected string SetupSrcPackage() { var protobuildLocation = AppDomain.CurrentDomain.GetAssemblies().First(x => x.GetName().Name == "Protobuild").Location; var location = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName; var dataLocation = Path.Combine(location, "..", "..", "..", "..", "TestData", "SrcPackage"); var tempLocation = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); CopyDirectory(dataLocation, tempLocation); File.Copy(protobuildLocation, Path.Combine(tempLocation, "Protobuild.exe"), true); RunGitAndCapture(tempLocation, "init"); RunGitAndCapture(tempLocation, "config user.email [email protected]"); RunGitAndCapture(tempLocation, "config user.name Temp"); RunGitAndCapture(tempLocation, "add -f ."); RunGitAndCapture(tempLocation, "commit -a -m 'temp'"); return tempLocation; } protected string SetupSrcTemplate() { var location = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName; var dataLocation = Path.Combine(location, "..", "..", "..", "..", "TestData", "SrcTemplate"); var tempLocation = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); CopyDirectory(dataLocation, tempLocation); RunGitAndCapture(tempLocation, "init"); RunGitAndCapture(tempLocation, "config user.email [email protected]"); RunGitAndCapture(tempLocation, "config user.name Temp"); RunGitAndCapture(tempLocation, "add -f ."); RunGitAndCapture(tempLocation, "commit -a -m 'temp'"); return tempLocation; } protected string SetupSrcTemplateAlt() { var location = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName; var dataLocation = Path.Combine(location, "..", "..", "..", "..", "TestData", "SrcTemplateAlt"); var tempLocation = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); CopyDirectory(dataLocation, tempLocation); RunGitAndCapture(tempLocation, "init"); RunGitAndCapture(tempLocation, "config user.email [email protected]"); RunGitAndCapture(tempLocation, "config user.name Temp"); RunGitAndCapture(tempLocation, "add -f ."); RunGitAndCapture(tempLocation, "commit -a -m 'temp'"); return tempLocation; } private static void CopyDirectory(string source, string dest) { var dir = new DirectoryInfo(source); if (!Directory.Exists(dest)) { Directory.CreateDirectory(dest); } foreach (var file in dir.GetFiles()) { var temppath = Path.Combine(dest, file.Name); file.CopyTo(temppath, true); } foreach (var subdir in dir.GetDirectories()) { var temppath = Path.Combine(dest, subdir.Name); CopyDirectory(subdir.FullName, temppath); } } private static string RunGitAndCapture(string folder, string str) { var processStartInfo = new ProcessStartInfo { FileName = "git", Arguments = str, WorkingDirectory = folder, RedirectStandardOutput = true, CreateNoWindow = true, UseShellExecute = false, }; var process = Process.Start(processStartInfo); var result = process.StandardOutput.ReadToEnd(); process.WaitForExit(); if (process.ExitCode != 0) { throw new InvalidOperationException("Got an unexpected exit code of " + process.ExitCode + " from Git"); } return result; } } }
#region CVS Log /* * Version: * $Id: ID3Tag.cs,v 1.3 2004/11/16 08:41:25 cwoodbury Exp $ * * Revisions: * $Log: ID3Tag.cs,v $ * Revision 1.3 2004/11/16 08:41:25 cwoodbury * Renamed Comment property to Comments for consistency. * * Revision 1.2 2004/11/10 06:51:56 cwoodbury * Hid CVS log messages away in #region * * Revision 1.1 2004/11/03 01:18:07 cwoodbury * Added to ID3Sharp * */ #endregion /* * Author(s): * Chris Woodbury * * Project Location: * http://id3sharp.sourceforge.net * * License: * Licensed under the Open Software License version 2.0 */ using System; using System.IO; namespace ID3Sharp.Models { /// <summary> /// /// </summary> public abstract class ID3Tag { #region Properties /// <summary> /// Gets and sets the album title of the file this tag represents. /// </summary> public abstract string Album { get; set; } /// <summary> /// Gets and sets the album title of the file this tag represents. /// </summary> public abstract string Artist { get; set; } /// <summary> /// Gets and sets the key of the file this tag represents. /// </summary> public abstract string Key { get; set; } /// <summary> /// Gets and sets the comments of the file this tag represents. /// </summary> public abstract string Comments { get; set; } /// <summary> /// Gets and sets the string value of the genre of the file this tag represents. /// </summary> public abstract string Genre { get; set; } /// <summary> /// Gets and sets the integer value of the genre of the file this tag represents. /// </summary> public virtual int GenreAsInt { get { return ID3Genre.GetGenre( this.Genre ); } set { this.Genre = ID3Genre.GetGenre( value ); } } /// <summary> /// Gets and sets the title of the file this tag represents. /// </summary> public abstract string Title { get; set; } /// <summary> /// Gets and sets the release year of the file this tag represents. /// </summary> public abstract string Year { get; set; } /// <summary> /// Gets and sets the track number of the file this tag represents. /// </summary> public abstract int TrackNumber { get; set; } /// <summary> /// Gets a value indicating whether the Artist property is not empty or null. /// </summary> public bool HasArtist { get { return ! String.IsNullOrEmpty( Artist ); } } /// <summary> /// Gets a value indicating whether the Title property is not empty or null. /// </summary> public bool HasTitle { get { return ! String.IsNullOrEmpty( Title ); } } /// <summary> /// Gets a value indicating whether the Album property is not empty or null. /// </summary> public bool HasAlbum { get { return ! String.IsNullOrEmpty( Album ); } } /// <summary> /// Gets a value indicating whether the Comments property is not empty or null. /// </summary> public bool HasComments { get { return ! String.IsNullOrEmpty( Comments ); } } /// <summary> /// Gets a value indicating whether the Genre property is not empty or null. /// </summary> public bool HasGenre { get { return ! String.IsNullOrEmpty( Genre ); } } /// <summary> /// Gets a value indicating whether the Key property is not empty or null. /// </summary> public bool HasKey { get { return ! String.IsNullOrEmpty(Key); } } /// <summary> /// Gets a value indicating whether the Year property is not empty or null. /// </summary> public bool HasYear { get { return ! String.IsNullOrEmpty( Year ); } } /// <summary> /// Gets a value indicating whether the TrackNumber property is greater than 0. /// </summary> public bool HasTrackNumber { get { return (TrackNumber > 0); } } public abstract string UniqueFileIdentifier { get; set; } #endregion #region Constructors /// <summary> /// Creates a new ID3Tag. /// </summary> protected ID3Tag() { } /// <summary> /// Copy constructor. /// </summary> /// <param name="tag">The tag to copy.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors" )] protected ID3Tag( ID3Tag tag ) { if ( tag == null ) { throw new ArgumentNullException( "tag" ); } this.Album = tag.Album; this.Artist = tag.Artist; this.Comments = tag.Comments; this.GenreAsInt = tag.GenreAsInt; this.Title = tag.Title; this.TrackNumber = tag.TrackNumber; this.Year = tag.Year; } #endregion /// <summary> /// Returns a string representation of this tag object. /// </summary> /// <returns>A string representation of this tag object.</returns> public override string ToString() { string toString = String.Format( "{0} - {1}", Artist, Title ); if ( HasAlbum ) { toString += String.Format( " ({0})", Album ); } return toString; } /// <summary> /// Writes the tag to a stream using the format specified by a particular ID3 version. /// </summary> /// <param name="stream">The stream to write the tag to.</param> /// <param name="version">The version to use.</param> public abstract void WriteTag( Stream stream, ID3Versions version ); /// <summary> /// Writes the tag to a file using the format specified by a particular ID3 version. /// </summary> /// <param name="filename">The name of the file to write the tag to.</param> /// <param name="version">The version to use.</param> public virtual void WriteTag( string filename, ID3Versions version ) { using ( Stream stream = new FileStream( filename, FileMode.OpenOrCreate, FileAccess.ReadWrite ) ) { WriteTag( stream, version ); } } /// <summary> /// Converts a string to an array of bytes. /// </summary> /// <param name="str">The string to convert.</param> /// <returns>The array of bytes equivalent to the /// specified string.</returns> protected byte[] StringToBytes( string str ) { if ( str == null ) { throw new ArgumentNullException( "str" ); } byte[] bytes = new byte[ str.Length ]; for ( int itr = 0; itr < bytes.Length; itr++ ) { bytes[ itr ] = (byte) str[ itr ]; } return bytes; } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Modules; using IronPython.Runtime.Types; #if FEATURE_NUMERICS using System.Numerics; #else using Microsoft.Scripting.Math; using Complex = Microsoft.Scripting.Math.Complex64; #endif namespace IronPython.Runtime.Operations { public static partial class BigIntegerOps { [StaticExtensionMethod] public static object __new__(CodeContext context, PythonType cls, string s, int radix) { if (radix == 16 || radix == 8 || radix == 2) { s = Int32Ops.TrimRadix(s, radix); } if (cls == TypeCache.BigInteger) { return ParseBigIntegerSign(s, radix); } else { BigInteger res = ParseBigIntegerSign(s, radix); return cls.CreateInstance(context, res); } } [StaticExtensionMethod] public static object __new__(CodeContext/*!*/ context, PythonType cls, IList<byte> s) { object value; IPythonObject po = s as IPythonObject; if (po == null || !PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, po, "__long__", out value)) { value = ParseBigIntegerSign(s.MakeString(), 10); } if (cls == TypeCache.BigInteger) { return value; } else { // derived long creation... return cls.CreateInstance(context, value); } } private static BigInteger ParseBigIntegerSign(string s, int radix) { try { return LiteralParser.ParseBigIntegerSign(s, radix); } catch (ArgumentException e) { throw PythonOps.ValueError(e.Message); } } [StaticExtensionMethod] public static object __new__(CodeContext context, PythonType cls, object x) { Extensible<string> es; if (x is string) { return ReturnObject(context, cls, ParseBigIntegerSign((string)x, 10)); } else if ((es = x as Extensible<string>) != null) { object value; if (PythonTypeOps.TryInvokeUnaryOperator(context, x, "__long__", out value)) { return ReturnObject(context, cls, (BigInteger)value); } return ReturnObject(context, cls, ParseBigIntegerSign(es.Value, 10)); } if (x is double) return ReturnObject(context, cls, DoubleOps.__long__((double)x)); if (x is int) return ReturnObject(context, cls, (BigInteger)(int)x); if (x is BigInteger) return ReturnObject(context, cls, x); if (x is Complex) throw PythonOps.TypeError("can't convert complex to long; use long(abs(z))"); if (x is decimal) { return ReturnObject(context, cls, (BigInteger)(decimal)x); } object result; int intRes; BigInteger bigintRes; if (PythonTypeOps.TryInvokeUnaryOperator(context, x, "__long__", out result) && !Object.ReferenceEquals(result, NotImplementedType.Value) || x is OldInstance && PythonTypeOps.TryInvokeUnaryOperator(context, x, "__int__", out result) && !Object.ReferenceEquals(result, NotImplementedType.Value)) { if (result is int || result is BigInteger || result is Extensible<int> || result is Extensible<BigInteger>) { return ReturnObject(context, cls, result); } else { throw PythonOps.TypeError("__long__ returned non-long (type {0})", PythonTypeOps.GetOldName(result)); } } else if (PythonOps.TryGetBoundAttr(context, x, "__trunc__", out result)) { result = PythonOps.CallWithContext(context, result); if (Converter.TryConvertToInt32(result, out intRes)) { return ReturnObject(context, cls, (BigInteger)intRes); } else if (Converter.TryConvertToBigInteger(result, out bigintRes)) { return ReturnObject(context, cls, bigintRes); } else { throw PythonOps.TypeError("__trunc__ returned non-Integral (type {0})", PythonTypeOps.GetOldName(result)); } } if (x is OldInstance) { throw PythonOps.AttributeError("{0} instance has no attribute '__trunc__'", ((OldInstance)x)._class.Name); } else { throw PythonOps.TypeError("long() argument must be a string or a number, not '{0}'", DynamicHelpers.GetPythonType(x).Name); } } private static object ReturnObject(CodeContext context, PythonType cls, object value) { if (cls == TypeCache.BigInteger) { return value; } else { return cls.CreateInstance(context, value); } } [StaticExtensionMethod] public static object __new__(CodeContext context, PythonType cls) { if (cls == TypeCache.BigInteger) { return BigInteger.Zero; } else { return cls.CreateInstance(context, BigInteger.Zero); } } #region Binary operators [SpecialName] public static object Power(BigInteger x, object y, object z) { if (y is int) { return Power(x, (int)y, z); } else if (y is long) { return Power(x, (BigInteger)(long)y, z); } else if (y is BigInteger) { return Power(x, (BigInteger)y, z); } return NotImplementedType.Value; } [SpecialName] public static object Power(BigInteger x, int y, object z) { if (z is int) { return Power(x, y, (BigInteger)(int)z); } else if (z is long) { return Power(x, y, (BigInteger)(long)z); } else if (z is BigInteger) { return Power(x, y, (BigInteger)z); } else if (z == null) { return Power(x, y); } return NotImplementedType.Value; } [SpecialName] public static object Power(BigInteger x, BigInteger y, object z) { if (z is int) { return Power(x, y, (BigInteger)(int)z); } else if (z is long) { return Power(x, y, (BigInteger)(long)z); } else if (z is BigInteger) { return Power(x, y, (BigInteger)z); } else if (z == null) { return Power(x, y); } return NotImplementedType.Value; } [SpecialName] public static object Power(BigInteger x, int y, BigInteger z) { if (y < 0) { throw PythonOps.TypeError("power", y, "power must be >= 0"); } if (z == BigInteger.Zero) { throw PythonOps.ZeroDivisionError(); } BigInteger result = x.ModPow(y, z); // fix the sign for negative moduli or negative mantissas if ((z < BigInteger.Zero && result > BigInteger.Zero) || (z > BigInteger.Zero && result < BigInteger.Zero)) { result += z; } return result; } [SpecialName] public static object Power(BigInteger x, BigInteger y, BigInteger z) { if (y < BigInteger.Zero) { throw PythonOps.TypeError("power", y, "power must be >= 0"); } if (z == BigInteger.Zero) { throw PythonOps.ZeroDivisionError(); } BigInteger result = x.ModPow(y, z); // fix the sign for negative moduli or negative mantissas if ((z < BigInteger.Zero && result > BigInteger.Zero) || (z > BigInteger.Zero && result < BigInteger.Zero)) { result += z; } return result; } [SpecialName] public static object Power([NotNull]BigInteger x, int y) { if (y < 0) { return DoubleOps.Power(x.ToFloat64(), y); } return x.Power(y); } [SpecialName] public static object Power([NotNull]BigInteger x, [NotNull]BigInteger y) { int yl; if (y.AsInt32(out yl)) { return Power(x, yl); } else { if (x == BigInteger.Zero) { if (y.Sign < 0) throw PythonOps.ZeroDivisionError("0.0 cannot be raised to a negative power"); return BigInteger.Zero; } else if (x == BigInteger.One) { return BigInteger.One; } else { throw PythonOps.ValueError("Number too big"); } } } private static BigInteger DivMod(BigInteger x, BigInteger y, out BigInteger r) { BigInteger rr; BigInteger qq; #if !FEATURE_NUMERICS if (Object.ReferenceEquals(x, null)) throw PythonOps.TypeError("unsupported operands for div/mod: NoneType and long"); if (Object.ReferenceEquals(y, null)) throw PythonOps.TypeError("unsupported operands for div/mod: long and NoneType"); #endif qq = BigInteger.DivRem(x, y, out rr); if (x >= BigInteger.Zero) { if (y > BigInteger.Zero) { r = rr; return qq; } else { if (rr == BigInteger.Zero) { r = rr; return qq; } else { r = rr + y; return qq - BigInteger.One; } } } else { if (y > BigInteger.Zero) { if (rr == BigInteger.Zero) { r = rr; return qq; } else { r = rr + y; return qq - BigInteger.One; } } else { r = rr; return qq; } } } #if !FEATURE_NUMERICS [SpecialName] public static BigInteger Add([NotNull]BigInteger x, [NotNull]BigInteger y) { return x + y; } [SpecialName] public static BigInteger Subtract([NotNull]BigInteger x, [NotNull]BigInteger y) { return x - y; } [SpecialName] public static BigInteger Multiply([NotNull]BigInteger x, [NotNull]BigInteger y) { return x * y; } #else [PythonHidden] public static BigInteger Add(BigInteger x, BigInteger y) { return x + y; } [PythonHidden] public static BigInteger Subtract(BigInteger x, BigInteger y) { return x - y; } [PythonHidden] public static BigInteger Multiply(BigInteger x, BigInteger y) { return x * y; } #endif [SpecialName] public static BigInteger FloorDivide([NotNull]BigInteger x, [NotNull]BigInteger y) { return Divide(x, y); } [SpecialName] public static double TrueDivide([NotNull]BigInteger x, [NotNull]BigInteger y) { if (y == BigInteger.Zero) { throw new DivideByZeroException(); } // first see if we can keep the two inputs as floats to give a precise result double fRes, fDiv; if (x.TryToFloat64(out fRes) && y.TryToFloat64(out fDiv)) { return fRes / fDiv; } // otherwise give the user the truncated result if the result fits in a float BigInteger rem; BigInteger res = BigInteger.DivRem(x, y, out rem); if (res.TryToFloat64(out fRes)) { if(rem != BigInteger.Zero) { // try and figure out the fractional portion BigInteger fraction = y / rem; if (fraction.TryToFloat64(out fDiv)) { if (fDiv != 0) { fRes += 1 / fDiv; } } } return fRes; } // otherwise report an error throw PythonOps.OverflowError("long/long too large for a float"); } #if !FEATURE_NUMERICS [SpecialName] public static BigInteger Divide([NotNull]BigInteger x, [NotNull]BigInteger y) { BigInteger r; return DivMod(x, y, out r); } [SpecialName] public static BigInteger Mod([NotNull]BigInteger x, [NotNull]BigInteger y) { BigInteger r; DivMod(x, y, out r); return r; } [SpecialName] public static BigInteger LeftShift([NotNull]BigInteger x, int y) { if (y < 0) { throw PythonOps.ValueError("negative shift count"); } return x << y; } [SpecialName] public static BigInteger RightShift([NotNull]BigInteger x, int y) { if (y < 0) { throw PythonOps.ValueError("negative shift count"); } return x >> y; } [SpecialName] public static BigInteger LeftShift([NotNull]BigInteger x, [NotNull]BigInteger y) { return LeftShift(x, (int)y); } [SpecialName] public static BigInteger RightShift([NotNull]BigInteger x, [NotNull]BigInteger y) { return RightShift(x, (int)y); } #else // The op_* nomenclature is required here to avoid name collisions with the // PythonHidden methods Divide, Mod, and [Left,Right]Shift. [SpecialName] public static BigInteger op_Division(BigInteger x, BigInteger y) { BigInteger r; return DivMod(x, y, out r); } [SpecialName] public static BigInteger op_Modulus(BigInteger x, BigInteger y) { BigInteger r; DivMod(x, y, out r); return r; } [SpecialName] public static BigInteger op_LeftShift(BigInteger x, int y) { if (y < 0) { throw PythonOps.ValueError("negative shift count"); } return x << y; } [SpecialName] public static BigInteger op_RightShift(BigInteger x, int y) { if (y < 0) { throw PythonOps.ValueError("negative shift count"); } return x >> y; } [SpecialName] public static BigInteger op_LeftShift(BigInteger x, BigInteger y) { return op_LeftShift(x, (int)y); } [SpecialName] public static BigInteger op_RightShift(BigInteger x, BigInteger y) { return op_RightShift(x, (int)y); } #endif #endregion [SpecialName] public static PythonTuple DivMod(BigInteger x, BigInteger y) { BigInteger div, mod; div = DivMod(x, y, out mod); return PythonTuple.MakeTuple(div, mod); } #region Unary operators public static object __abs__(BigInteger x) { return x.Abs(); } public static bool __nonzero__(BigInteger x) { return !x.IsZero(); } [SpecialName] public static object Negate(BigInteger x) { return -x; } public static object __pos__(BigInteger x) { return x; } public static object __int__(BigInteger x) { // The python spec says __int__ should return a long if needed, rather than overflow. int i32; if (x.AsInt32(out i32)) { return Microsoft.Scripting.Runtime.ScriptingRuntimeHelpers.Int32ToObject(i32); } return x; } public static object __float__(BigInteger self) { return self.ToFloat64(); } public static string __oct__(BigInteger x) { if (x == BigInteger.Zero) { return "0L"; } else if (x > 0) { return "0" + x.ToString(8) + "L"; } else { return "-0" + (-x).ToString(8) + "L"; } } public static string __hex__(BigInteger x) { // CPython 2.5 prints letters in lowercase, with a capital L. if (x < 0) { return "-0x" + (-x).ToString(16).ToLower() + "L"; } else { return "0x" + x.ToString(16).ToLower() + "L"; } } public static object __getnewargs__(CodeContext context, BigInteger self) { #if !FEATURE_NUMERICS if (!Object.ReferenceEquals(self, null)) { return PythonTuple.MakeTuple(BigIntegerOps.__new__(context, TypeCache.BigInteger, self)); } throw PythonOps.TypeErrorForBadInstance("__getnewargs__ requires a 'long' object but received a '{0}'", self); #else return PythonTuple.MakeTuple(BigIntegerOps.__new__(context, TypeCache.BigInteger, self)); #endif } #endregion // These functions make the code generation of other types more regular #if !FEATURE_NUMERICS internal #else [PythonHidden] public #endif static BigInteger OnesComplement(BigInteger x) { return ~x; } internal static BigInteger FloorDivideImpl(BigInteger x, BigInteger y) { return FloorDivide(x, y); } #if !FEATURE_NUMERICS [SpecialName] public static BigInteger BitwiseAnd([NotNull]BigInteger x, [NotNull]BigInteger y) { return x & y; } [SpecialName] public static BigInteger BitwiseOr([NotNull]BigInteger x, [NotNull]BigInteger y) { return x | y; } [SpecialName] public static BigInteger ExclusiveOr([NotNull]BigInteger x, [NotNull]BigInteger y) { return x ^ y; } #else [PythonHidden] public static BigInteger BitwiseAnd(BigInteger x, BigInteger y) { return x & y; } [PythonHidden] public static BigInteger BitwiseOr(BigInteger x, BigInteger y) { return x | y; } [PythonHidden] public static BigInteger ExclusiveOr(BigInteger x, BigInteger y) { return x ^ y; } #endif [PropertyMethod, SpecialName] public static BigInteger Getreal(BigInteger self) { return self; } [PropertyMethod, SpecialName] public static BigInteger Getimag(BigInteger self) { return (BigInteger)0; } public static BigInteger conjugate(BigInteger self) { return self; } [PropertyMethod, SpecialName] public static BigInteger Getnumerator(BigInteger self) { return self; } [PropertyMethod, SpecialName] public static BigInteger Getdenominator(BigInteger self) { return (BigInteger)1; } public static int bit_length(BigInteger self) { return MathUtils.BitLength(self); } public static BigInteger __trunc__(BigInteger self) { return self; } [SpecialName, ImplicitConversionMethod] public static double ConvertToDouble(BigInteger self) { return self.ToFloat64(); } [SpecialName, ExplicitConversionMethod] public static int ConvertToInt32(BigInteger self) { int res; if (self.AsInt32(out res)) return res; throw Converter.CannotConvertOverflow("int", self); } [SpecialName, ExplicitConversionMethod] public static Complex ConvertToComplex(BigInteger self) { return MathUtils.MakeReal(ConvertToDouble(self)); } [SpecialName, ImplicitConversionMethod] public static BigInteger ConvertToBigInteger(bool self) { return self ? BigInteger.One : BigInteger.Zero; } [SpecialName] public static int Compare(BigInteger x, BigInteger y) { return x.CompareTo(y); } [SpecialName] public static int Compare(BigInteger x, int y) { int ix; if (x.AsInt32(out ix)) { return ix == y ? 0 : ix > y ? 1 : -1; } return BigInteger.Compare(x, y); } [SpecialName] public static int Compare(BigInteger x, uint y) { uint ix; if (x.AsUInt32(out ix)) { return ix == y ? 0 : ix > y ? 1 : -1; } return BigInteger.Compare(x, y); } [SpecialName] public static int Compare(BigInteger x, double y) { return -((int)DoubleOps.Compare(y, x)); } [SpecialName] public static int Compare(BigInteger x, [NotNull]Extensible<double> y) { return -((int)DoubleOps.Compare(y.Value, x)); } [SpecialName] public static int Compare(BigInteger x, decimal y) { return DecimalOps.__cmp__(x, y); } [SpecialName] public static int Compare(BigInteger x, bool y) { return Compare(x, y ? 1 : 0); } public static BigInteger __long__(BigInteger self) { return self; } public static BigInteger __index__(BigInteger self) { return self; } public static int __hash__(BigInteger self) { #if CLR4 // TODO: we might need our own hash code implementation. This avoids assertion failure. if (self == -2147483648) { return -2147483648; } #endif // check if it's in the Int64 or UInt64 range, and use the built-in hashcode for that instead // this ensures that objects added to dictionaries as (U)Int64 can be looked up with Python longs Int64 i64; if (self.AsInt64(out i64)) { return Int64Ops.__hash__(i64); } else { UInt64 u64; if (self.AsUInt64(out u64)) { return UInt64Ops.__hash__(u64); } } // Call the DLR's BigInteger hash function, which will return an int32 representation of // b if b is within the int32 range. We use that as an optimization for hashing, and // assert the assumption below. int hash = self.GetHashCode(); #if DEBUG int i; if (self.AsInt32(out i)) { Debug.Assert(i == hash, String.Format("hash({0}) == {1}", i, hash)); } #endif return hash; } public static string __repr__([NotNull]BigInteger/*!*/ self) { return self.ToString() + "L"; } public static object __coerce__(CodeContext context, BigInteger self, object o) { // called via builtin.coerce() BigInteger val; if (Converter.TryConvertToBigInteger(o, out val)) { return PythonTuple.MakeTuple(self, val); } return NotImplementedType.Value; } #region Backwards compatibility with BigIntegerV2 [PythonHidden] public static float ToFloat(BigInteger/*!*/ self) { return checked((float)self.ToFloat64()); } #if FEATURE_NUMERICS #region Binary Ops [PythonHidden] public static BigInteger Xor(BigInteger x, BigInteger y) { return x ^ y; } [PythonHidden] public static BigInteger Divide(BigInteger x, BigInteger y) { return op_Division(x, y); } [PythonHidden] public static BigInteger Mod(BigInteger x, BigInteger y) { return op_Modulus(x, y); } [PythonHidden] public static BigInteger LeftShift(BigInteger x, int y) { return op_LeftShift(x, y); } [PythonHidden] public static BigInteger RightShift(BigInteger x, int y) { return op_RightShift(x, y); } [PythonHidden] public static BigInteger LeftShift(BigInteger x, BigInteger y) { return op_LeftShift(x, y); } [PythonHidden] public static BigInteger RightShift(BigInteger x, BigInteger y) { return op_RightShift(x, y); } #endregion #region 'As' Conversions [PythonHidden] public static bool AsDecimal(BigInteger self, out decimal res) { if (self <= (BigInteger)decimal.MaxValue && self >= (BigInteger)decimal.MinValue) { res = (decimal)self; return true; } res = default(decimal); return false; } [PythonHidden] public static bool AsInt32(BigInteger self, out int res) { return self.AsInt32(out res); } [PythonHidden] public static bool AsInt64(BigInteger self, out long res) { return self.AsInt64(out res); } [CLSCompliant(false), PythonHidden] public static bool AsUInt32(BigInteger self, out uint res) { return self.AsUInt32(out res); } [CLSCompliant(false), PythonHidden] public static bool AsUInt64(BigInteger self, out ulong res) { return self.AsUInt64(out res); } #endregion #region Direct Conversions [PythonHidden] public static int ToInt32(BigInteger self) { return (int)self; } [PythonHidden] public static long ToInt64(BigInteger self) { return (long)self; } [CLSCompliant(false), PythonHidden] public static uint ToUInt32(BigInteger self) { return (uint)self; } [CLSCompliant(false), PythonHidden] public static ulong ToUInt64(BigInteger self) { return (ulong)self; } #endregion #region Mimic some IConvertible members [PythonHidden] public static bool ToBoolean(BigInteger self, IFormatProvider provider) { return !self.IsZero; } [PythonHidden] public static byte ToByte(BigInteger self, IFormatProvider provider) { return (byte)self; } [CLSCompliant(false), PythonHidden] public static sbyte ToSByte(BigInteger self, IFormatProvider provider) { return (sbyte)self; } [PythonHidden] public static char ToChar(BigInteger self, IFormatProvider provider) { int res; if (self.AsInt32(out res) && res <= Char.MaxValue && res >= Char.MinValue) { return (char)res; } throw new OverflowException("big integer won't fit into char"); } [PythonHidden] public static decimal ToDecimal(BigInteger self, IFormatProvider provider) { return (decimal)self; } [PythonHidden] public static double ToDouble(BigInteger self, IFormatProvider provider) { return ConvertToDouble(self); } [PythonHidden] public static float ToSingle(BigInteger self, IFormatProvider provider) { return ToFloat(self); } [PythonHidden] public static short ToInt16(BigInteger self, IFormatProvider provider) { return (short)self; } [PythonHidden] public static int ToInt32(BigInteger self, IFormatProvider provider) { return (int)self; } [PythonHidden] public static long ToInt64(BigInteger self, IFormatProvider provider) { return (long)self; } [CLSCompliant(false), PythonHidden] public static ushort ToUInt16(BigInteger self, IFormatProvider provider) { return (ushort)self; } [CLSCompliant(false), PythonHidden] public static uint ToUInt32(BigInteger self, IFormatProvider provider) { return (uint)self; } [CLSCompliant(false), PythonHidden] public static ulong ToUInt64(BigInteger self, IFormatProvider provider) { return (ulong)self; } [PythonHidden] public static object ToType(BigInteger self, Type conversionType, IFormatProvider provider) { if (conversionType == typeof(BigInteger)) { return self; } throw new NotImplementedException(); } [PythonHidden] public static TypeCode GetTypeCode(BigInteger self) { return TypeCode.Object; } #endregion [PythonHidden] public static BigInteger Square(BigInteger self) { return self * self; } [PythonHidden] public static bool IsNegative(BigInteger self) { return self.Sign < 0; } [PythonHidden] public static bool IsPositive(BigInteger self) { return self.Sign > 0; } [PythonHidden] public static int GetBitCount(BigInteger self) { return self.GetBitCount(); } [PythonHidden] public static int GetByteCount(BigInteger self) { return self.GetByteCount(); } #region 'Create' Methods [PythonHidden] public static BigInteger Create(byte[] v) { return new BigInteger(v); } [PythonHidden] public static BigInteger Create(int v) { return new BigInteger(v); } [PythonHidden] public static BigInteger Create(long v) { return new BigInteger(v); } [CLSCompliant(false), PythonHidden] public static BigInteger Create(uint v) { return new BigInteger(v); } [CLSCompliant(false), PythonHidden] public static BigInteger Create(ulong v) { return (BigInteger)v; } [PythonHidden] public static BigInteger Create(decimal v) { return new BigInteger(v); } [PythonHidden] public static BigInteger Create(double v) { return new BigInteger(v); } #endregion #region Expose BigIntegerV2-style uint data [CLSCompliant(false), PythonHidden] public static uint[] GetWords(BigInteger self) { return self.GetWords(); } [CLSCompliant(false), PythonHidden] public static uint GetWord(BigInteger self, int index) { return self.GetWord(index); } [PythonHidden] public static int GetWordCount(BigInteger self) { return self.GetWordCount(); } #endregion #endif #endregion public static string/*!*/ __format__(CodeContext/*!*/ context, BigInteger/*!*/ self, [NotNull]string/*!*/ formatSpec) { StringFormatSpec spec = StringFormatSpec.FromString(formatSpec); if (spec.Precision != null) { throw PythonOps.ValueError("Precision not allowed in integer format specifier"); } BigInteger val = self; if (self < 0) { val = -self; } string digits; switch (spec.Type) { case 'n': CultureInfo culture = PythonContext.GetContext(context).NumericCulture; if (culture == CultureInfo.InvariantCulture) { // invariant culture maps to CPython's C culture, which doesn't // include any formatting info. goto case 'd'; } digits = ToCultureString(val, PythonContext.GetContext(context).NumericCulture); break; #if !FEATURE_NUMERICS case null: case 'd': digits = val.ToString(); break; case '%': if (val == BigInteger.Zero) { digits = "0.000000%"; } else { digits = val.ToString() + "00.000000%"; } break; case 'e': digits = ToExponent(val, true, 6, 7); break; case 'E': digits = ToExponent(val, false, 6, 7); break; case 'f': if (val != BigInteger.Zero) { digits = val.ToString() + ".000000"; } else { digits = "0.000000"; } break; case 'F': if (val != BigInteger.Zero) { digits = val.ToString() + ".000000"; } else { digits = "0.000000"; } break; case 'g': if (val >= 1000000) { digits = ToExponent(val, true, 0, 6); } else { digits = val.ToString(); } break; case 'G': if (val >= 1000000) { digits = ToExponent(val, false, 0, 6); } else { digits = val.ToString(); } break; #else case null: case 'd': if (spec.ThousandsComma) { digits = val.ToString("#,0", CultureInfo.InvariantCulture); } else { digits = val.ToString("D", CultureInfo.InvariantCulture); } break; case '%': if (spec.ThousandsComma) { digits = val.ToString("#,0.000000%", CultureInfo.InvariantCulture); } else { digits = val.ToString("0.000000%", CultureInfo.InvariantCulture); } break; case 'e': if (spec.ThousandsComma) { digits = val.ToString("#,0.000000e+00", CultureInfo.InvariantCulture); } else { digits = val.ToString("0.000000e+00", CultureInfo.InvariantCulture); } break; case 'E': if (spec.ThousandsComma) { digits = val.ToString("#,0.000000E+00", CultureInfo.InvariantCulture); } else { digits = val.ToString("0.000000E+00", CultureInfo.InvariantCulture); } break; case 'f': case 'F': if (spec.ThousandsComma) { digits = val.ToString("#,########0.000000", CultureInfo.InvariantCulture); } else { digits = val.ToString("#########0.000000", CultureInfo.InvariantCulture); } break; case 'g': if (val >= 1000000) { digits = val.ToString("0.#####e+00", CultureInfo.InvariantCulture); } else if (spec.ThousandsComma) { digits = val.ToString("#,0", CultureInfo.InvariantCulture); } else { digits = val.ToString(CultureInfo.InvariantCulture); } break; case 'G': if (val >= 1000000) { digits = val.ToString("0.#####E+00", CultureInfo.InvariantCulture); } else if (spec.ThousandsComma) { digits = val.ToString("#,0", CultureInfo.InvariantCulture); } else { digits = val.ToString(CultureInfo.InvariantCulture); } break; #endif case 'X': digits = AbsToHex(val, false); break; case 'x': digits = AbsToHex(val, true); break; case 'o': // octal digits = ToOctal(val, true); break; case 'b': // binary digits = ToBinary(val, false, true); break; case 'c': // single char int iVal; if (spec.Sign != null) { throw PythonOps.ValueError("Sign not allowed with integer format specifier 'c'"); } else if (!self.AsInt32(out iVal)) { throw PythonOps.OverflowError("long int too large to convert to int"); } else if(iVal < 0 || iVal > 0xFF) { throw PythonOps.OverflowError("%c arg not in range(0x10000)"); } digits = ScriptingRuntimeHelpers.CharToString((char)iVal); break; default: throw PythonOps.ValueError("Unknown format code '{0}'", spec.Type.ToString()); } Debug.Assert(digits[0] != '-'); return spec.AlignNumericText(digits, self.IsZero(), self.IsPositive()); } internal static string AbsToHex(BigInteger val, bool lowercase) { return ToDigits(val, 16, lowercase); } private static string ToOctal(BigInteger val, bool lowercase) { return ToDigits(val, 8, lowercase); } internal static string ToBinary(BigInteger val) { string res = ToBinary(val.Abs(), true, true); if (val.IsNegative()) { res = "-" + res; } return res; } private static string ToBinary(BigInteger val, bool includeType, bool lowercase) { Debug.Assert(!val.IsNegative()); string digits; digits = ToDigits(val, 2, lowercase); if (includeType) { digits = (lowercase ? "0b" : "0B") + digits; } return digits; } private static string/*!*/ ToCultureString(BigInteger/*!*/ val, CultureInfo/*!*/ ci) { string digits; string separator = ci.NumberFormat.NumberGroupSeparator; int[] separatorLocations = ci.NumberFormat.NumberGroupSizes; digits = val.ToString(); if (separatorLocations.Length > 0) { StringBuilder res = new StringBuilder(digits); int curGroup = 0, curDigit = digits.Length - 1; while (curDigit > 0) { // insert the seperator int groupLen = separatorLocations[curGroup]; if (groupLen == 0) { break; } curDigit -= groupLen; if (curDigit >= 0) { res.Insert(curDigit + 1, separator); } // advance the group if (curGroup + 1 < separatorLocations.Length) { if (separatorLocations[curGroup + 1] == 0) { // last value doesn't propagate break; } curGroup++; } } digits = res.ToString(); } return digits; } private static string/*!*/ ToExponent(BigInteger/*!*/ self, bool lower, int minPrecision, int maxPrecision) { Debug.Assert(minPrecision <= maxPrecision); // get all the digits string digits = self.ToString(); StringBuilder tmp = new StringBuilder(); tmp.Append(digits[0]); for (int i = 1; i < maxPrecision && i < digits.Length; i++) { // append if we have a significant digit or if we are forcing a minimum precision if (digits[i] != '0' || i <= minPrecision) { if (tmp.Length == 1) { // first time we've appended, add the decimal point now tmp.Append('.'); } while (i > tmp.Length - 1) { // add any digits that we skipped before tmp.Append('0'); } // round up last digit if necessary if (i == maxPrecision - 1 && i != digits.Length - 1 && digits[i + 1] >= '5') { tmp.Append((char)(digits[i] + 1)); } else { tmp.Append(digits[i]); } } } if (digits.Length <= minPrecision) { if (tmp.Length == 1) { // first time we've appended, add the decimal point now tmp.Append('.'); } while (minPrecision >= tmp.Length - 1) { tmp.Append('0'); } } tmp.Append(lower ? "e+" : "E+"); int digitCnt = digits.Length - 1; if (digitCnt < 10) { tmp.Append('0'); tmp.Append((char)('0' + digitCnt)); } else { tmp.Append(digitCnt.ToString()); } digits = tmp.ToString(); return digits; } private static string/*!*/ ToDigits(BigInteger/*!*/ val, int radix, bool lower) { if (val.IsZero()) { return "0"; } StringBuilder str = new StringBuilder(); while (val != 0) { int digit = (int)(val % radix); if (digit < 10) str.Append((char)((digit) + '0')); else if (lower) str.Append((char)((digit - 10) + 'a')); else str.Append((char)((digit - 10) + 'A')); val /= radix; } StringBuilder res = new StringBuilder(str.Length); for (int i = str.Length - 1; i >= 0; i--) { res.Append(str[i]); } return res.ToString(); } } }
//*************************************************** //* This file was generated by tool //* SharpKit //* At: 29/08/2012 03:59:39 p.m. //*************************************************** using SharpKit.JavaScript; namespace Ext.chart { #region Shape /// <inheritdocs /> /// <summary> /// <p><strong>NOTE</strong> This is a private utility class for internal use by the framework. Don't rely on its existence.</p> /// </summary> [JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)] public partial class Shape : Ext.Base { /// <summary> /// Defaults to: <c>&quot;Ext.Base&quot;</c> /// </summary> [JsProperty(Name="$className")] private static JsString @className{get;set;} /// <summary> /// Defaults to: <c>{}</c> /// </summary> private static JsObject configMap{get;set;} /// <summary> /// Defaults to: <c>[]</c> /// </summary> private static JsArray initConfigList{get;set;} /// <summary> /// Defaults to: <c>{}</c> /// </summary> private static JsObject initConfigMap{get;set;} /// <summary> /// Defaults to: <c>true</c> /// </summary> private static bool isInstance{get;set;} /// <summary> /// Get the reference to the current class from which this object was instantiated. Unlike statics, /// this.self is scope-dependent and it's meant to be used for dynamic inheritance. See statics /// for a detailed comparison /// <code><see cref="Ext.ExtContext.define">Ext.define</see>('My.Cat', { /// statics: { /// speciesName: 'Cat' // My.Cat.speciesName = 'Cat' /// }, /// constructor: function() { /// alert(this.self.speciesName); // dependent on 'this' /// }, /// clone: function() { /// return new this.self(); /// } /// }); /// <see cref="Ext.ExtContext.define">Ext.define</see>('My.SnowLeopard', { /// extend: 'My.Cat', /// statics: { /// speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard' /// } /// }); /// var cat = new My.Cat(); // alerts 'Cat' /// var snowLeopard = new My.SnowLeopard(); // alerts 'Snow Leopard' /// var clone = snowLeopard.clone(); /// alert(<see cref="Ext.ExtContext.getClassName">Ext.getClassName</see>(clone)); // alerts 'My.SnowLeopard' /// </code> /// </summary> protected static Class self{get;set;} /// <summary> /// Call the original method that was previously overridden with override /// <code><see cref="Ext.ExtContext.define">Ext.define</see>('My.Cat', { /// constructor: function() { /// alert("I'm a cat!"); /// } /// }); /// My.Cat.override({ /// constructor: function() { /// alert("I'm going to be a cat!"); /// this.callOverridden(); /// alert("Meeeeoooowwww"); /// } /// }); /// var kitty = new My.Cat(); // alerts "I'm going to be a cat!" /// // alerts "I'm a cat!" /// // alerts "Meeeeoooowwww" /// </code> /// <p>This method has been <strong>deprecated</strong> </p> /// <p>as of 4.1. Use <see cref="Ext.Base.callParent">callParent</see> instead.</p> /// </summary> /// <param name="args"><p>The arguments, either an array or the <c>arguments</c> object /// from the current method, for example: <c>this.callOverridden(arguments)</c></p> /// </param> /// <returns> /// <span><see cref="Object">Object</see></span><div><p>Returns the result of calling the overridden method</p> /// </div> /// </returns> protected static object callOverridden(object args=null){return null;} /// <summary> /// Call the "parent" method of the current method. That is the method previously /// overridden by derivation or by an override (see Ext.define). /// <code> <see cref="Ext.ExtContext.define">Ext.define</see>('My.Base', { /// constructor: function (x) { /// this.x = x; /// }, /// statics: { /// method: function (x) { /// return x; /// } /// } /// }); /// <see cref="Ext.ExtContext.define">Ext.define</see>('My.Derived', { /// extend: 'My.Base', /// constructor: function () { /// this.callParent([21]); /// } /// }); /// var obj = new My.Derived(); /// alert(obj.x); // alerts 21 /// </code> /// This can be used with an override as follows: /// <code> <see cref="Ext.ExtContext.define">Ext.define</see>('My.DerivedOverride', { /// override: 'My.Derived', /// constructor: function (x) { /// this.callParent([x*2]); // calls original My.Derived constructor /// } /// }); /// var obj = new My.Derived(); /// alert(obj.x); // now alerts 42 /// </code> /// This also works with static methods. /// <code> <see cref="Ext.ExtContext.define">Ext.define</see>('My.Derived2', { /// extend: 'My.Base', /// statics: { /// method: function (x) { /// return this.callParent([x*2]); // calls My.Base.method /// } /// } /// }); /// alert(My.Base.method(10); // alerts 10 /// alert(My.Derived2.method(10); // alerts 20 /// </code> /// Lastly, it also works with overridden static methods. /// <code> <see cref="Ext.ExtContext.define">Ext.define</see>('My.Derived2Override', { /// override: 'My.Derived2', /// statics: { /// method: function (x) { /// return this.callParent([x*2]); // calls My.Derived2.method /// } /// } /// }); /// alert(My.Derived2.method(10); // now alerts 40 /// </code> /// </summary> /// <param name="args"><p>The arguments, either an array or the <c>arguments</c> object /// from the current method, for example: <c>this.callParent(arguments)</c></p> /// </param> /// <returns> /// <span><see cref="Object">Object</see></span><div><p>Returns the result of calling the parent method</p> /// </div> /// </returns> protected static object callParent(object args=null){return null;} /// <summary> /// </summary> private static void configClass(){} /// <summary> /// Overrides: <see cref="Ext.AbstractComponent.destroy">Ext.AbstractComponent.destroy</see>, <see cref="Ext.AbstractPlugin.destroy">Ext.AbstractPlugin.destroy</see>, <see cref="Ext.layout.Layout.destroy">Ext.layout.Layout.destroy</see> /// </summary> private static void destroy(){} /// <summary> /// Parameters<li><span>name</span> : <see cref="Object">Object</see><div> /// </div></li> /// </summary> /// <param name="name"> /// </param> private static void getConfig(object name){} /// <summary> /// Returns the initial configuration passed to constructor when instantiating /// this class. /// </summary> /// <param name="name"><p>Name of the config option to return.</p> /// </param> /// <returns> /// <span><see cref="Object">Object</see>/Mixed</span><div><p>The full config object or a single config value /// when <c>name</c> parameter specified.</p> /// </div> /// </returns> public static object getInitialConfig(object name=null){return null;} /// <summary> /// Parameters<li><span>config</span> : <see cref="Object">Object</see><div> /// </div></li> /// </summary> /// <param name="config"> /// </param> private static void hasConfig(object config){} /// <summary> /// Initialize configuration for this class. a typical example: /// <code><see cref="Ext.ExtContext.define">Ext.define</see>('My.awesome.Class', { /// // The default config /// config: { /// name: 'Awesome', /// isAwesome: true /// }, /// constructor: function(config) { /// this.initConfig(config); /// } /// }); /// var awesome = new My.awesome.Class({ /// name: 'Super Awesome' /// }); /// alert(awesome.getName()); // 'Super Awesome' /// </code> /// </summary> /// <param name="config"> /// </param> /// <returns> /// <span><see cref="Ext.Base">Ext.Base</see></span><div><p>this</p> /// </div> /// </returns> protected static Ext.Base initConfig(object config){return null;} /// <summary> /// Parameters<li><span>names</span> : <see cref="Object">Object</see><div> /// </div></li><li><span>callback</span> : <see cref="Object">Object</see><div> /// </div></li><li><span>scope</span> : <see cref="Object">Object</see><div> /// </div></li> /// </summary> /// <param name="names"> /// </param> /// <param name="callback"> /// </param> /// <param name="scope"> /// </param> private static void onConfigUpdate(object names, object callback, object scope){} /// <summary> /// Parameters<li><span>config</span> : <see cref="Object">Object</see><div> /// </div></li><li><span>applyIfNotSet</span> : <see cref="Object">Object</see><div> /// </div></li> /// </summary> /// <param name="config"> /// </param> /// <param name="applyIfNotSet"> /// </param> private static void setConfig(object config, object applyIfNotSet){} /// <summary> /// Get the reference to the class from which this object was instantiated. Note that unlike self, /// this.statics() is scope-independent and it always returns the class from which it was called, regardless of what /// this points to during run-time /// <code><see cref="Ext.ExtContext.define">Ext.define</see>('My.Cat', { /// statics: { /// totalCreated: 0, /// speciesName: 'Cat' // My.Cat.speciesName = 'Cat' /// }, /// constructor: function() { /// var statics = this.statics(); /// alert(statics.speciesName); // always equals to 'Cat' no matter what 'this' refers to /// // equivalent to: My.Cat.speciesName /// alert(this.self.speciesName); // dependent on 'this' /// statics.totalCreated++; /// }, /// clone: function() { /// var cloned = new this.self; // dependent on 'this' /// cloned.groupName = this.statics().speciesName; // equivalent to: My.Cat.speciesName /// return cloned; /// } /// }); /// <see cref="Ext.ExtContext.define">Ext.define</see>('My.SnowLeopard', { /// extend: 'My.Cat', /// statics: { /// speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard' /// }, /// constructor: function() { /// this.callParent(); /// } /// }); /// var cat = new My.Cat(); // alerts 'Cat', then alerts 'Cat' /// var snowLeopard = new My.SnowLeopard(); // alerts 'Cat', then alerts 'Snow Leopard' /// var clone = snowLeopard.clone(); /// alert(<see cref="Ext.ExtContext.getClassName">Ext.getClassName</see>(clone)); // alerts 'My.SnowLeopard' /// alert(clone.groupName); // alerts 'Cat' /// alert(My.Cat.totalCreated); // alerts 3 /// </code> /// </summary> /// <returns> /// <span><see cref="Ext.Class">Ext.Class</see></span><div> /// </div> /// </returns> protected static Class statics(){return null;} public Shape(ShapeConfig config){} public Shape(){} public Shape(params object[] args){} } #endregion #region ShapeConfig /// <inheritdocs /> [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)] public partial class ShapeConfig : Ext.BaseConfig { public ShapeConfig(params object[] args){} } #endregion #region ShapeEvents /// <inheritdocs /> [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)] public partial class ShapeEvents : Ext.BaseEvents { public ShapeEvents(params object[] args){} } #endregion }
/* * SubSonic - http://subsonicproject.com * * The contents of this file are subject to the Mozilla Public * License Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. */ using System; using System.Collections.Generic; using MbUnit.Framework; using Northwind; namespace SubSonic.Tests.SqlQuery { [TestFixture] public class SelectTests { #region Simple Select Record Counts [Test] public void Exec_Simple() { int records = new Select("productID").From("Products").GetRecordCount(); Assert.IsTrue(records == 77); } [Test] public void Exec_SimpleWithTypedColumns() { int records = new Select(Product.ProductIDColumn, Product.ProductNameColumn).From<Product>().GetRecordCount(); Assert.IsTrue(records == 77); } [Test] public void Exec_SimpleAsSingle() { Product p = new Select().From<Product>().Where("ProductID").IsEqualTo(1).ExecuteSingle<Product>(); Assert.IsNotNull(p); } [Test] public void Exec_WithAllColumns() { int records = new Select().From("Products").GetRecordCount(); Assert.IsTrue(records == 77); } [Test] public void Exec_SimpleWhere() { int records = new Select().From("Products").Where("categoryID").IsEqualTo(5).GetRecordCount(); Assert.AreEqual(7, records); } [Test] public void Exec_SimpleWhere2() { int records = new Select().From("Products").Where(Product.CategoryIDColumn).IsEqualTo(5).GetRecordCount(); Assert.AreEqual(7, records); } [Test] public void Exec_SimpleWhereAnd() { ProductCollection products = DB.Select().From("Products") .Where("categoryID").IsEqualTo(5) .And("productid").IsGreaterThan(50) .ExecuteAsCollection<ProductCollection>(); int records = new Select().From("Products").Where("categoryID").IsEqualTo(5).And("productid").IsGreaterThan(50).GetRecordCount(); Assert.IsTrue(records == 4); } [Test] public void Exec_SimpleJoin() { SubSonic.SqlQuery q = new Select("productid").From(OrderDetail.Schema) .InnerJoin(Product.Schema) .Where("CategoryID").IsEqualTo(5); string sql = q.ToString(); int records = q.GetRecordCount(); Assert.IsTrue(records == 196); } [Test] public void Exec_SimpleJoin2() { SubSonic.SqlQuery q = new Select("productid").From<OrderDetail>() .InnerJoin(Product.Schema) .Where("CategoryID").IsEqualTo(5); string sql = q.ToString(); int records = q.GetRecordCount(); Assert.IsTrue(records == 196); } [Test] public void Exec_SimpleJoin3() { SubSonic.SqlQuery q = new Select().From(Tables.OrderDetail) .InnerJoin(Tables.Product) .Where("CategoryID").IsEqualTo(5); string sql = q.ToString(); int records = q.GetRecordCount(); Assert.IsTrue(records == 196); } [Test] public void Exec_MultiJoin() { CustomerCollection customersByCategory = new Select() .From(Customer.Schema) .InnerJoin(Order.Schema) .InnerJoin(OrderDetail.OrderIDColumn, Order.OrderIDColumn) .InnerJoin(Product.ProductIDColumn, OrderDetail.ProductIDColumn) .Where("CategoryID").IsEqualTo(5) .ExecuteAsCollection<CustomerCollection>(); Assert.IsTrue(customersByCategory.Count == 196); } [Test] public void Exec_LeftOuterJoin_With_TableColumn() { SubSonic.SqlQuery query = DB.Select(Aggregate.GroupBy("CompanyName")) .From(Customer.Schema) .LeftOuterJoin(Order.CustomerIDColumn, Customer.CustomerIDColumn); int records = query.GetRecordCount(); Assert.AreEqual(91, records); } [Test] public void Exec_LeftOuterJoin_With_Generics() { SubSonic.SqlQuery query = DB.Select(Aggregate.GroupBy("CompanyName")) .From<Customer>() .LeftOuterJoin<Order>(); int records = query.GetRecordCount(); Assert.AreEqual(91, records); } [Test] public void Exec_LeftOuterJoin_With_String() { SubSonic.SqlQuery query = DB.Select(Aggregate.GroupBy("CompanyName")) .From("Customers") .LeftOuterJoin("Orders"); int records = query.GetRecordCount(); Assert.AreEqual(91, records); } #endregion #region TOP [Test] public void Exec_Select_Top_Ten() { SubSonic.SqlQuery query = DB.Select().Top("10") .From("Customers"); int records = query.ExecuteTypedList<Customer>().Count; Assert.AreEqual(10, records); } #endregion #region Collection Tests [Test] public void Exec_Collection_Simple() { ProductCollection p = Select.AllColumnsFrom<Product>() .ExecuteAsCollection<ProductCollection>(); Assert.IsTrue(p.Count == 77); } [Test] public void Exec_Collection_Joined() { ProductCollection p = Select.AllColumnsFrom<Product>() .InnerJoin(Category.Schema) .Where("CategoryName").IsEqualTo("Beverages") .ExecuteAsCollection<ProductCollection>(); Assert.IsTrue(p.Count == 12); } [Test] public void Exec_Collection_JoinedWithLike() { ProductCollection p = DB.Select() .From(Product.Schema) .InnerJoin(Category.Schema) .Where("CategoryName").Like("c%") .ExecuteAsCollection<ProductCollection>(); Assert.IsTrue(p.Count == 25); } [Test] public void Exec_Collection_JoinedWithLike_Typed() { ProductCollection p = DB.Select() .From<Product>() .InnerJoin<Category>() .Where("CategoryName").Like("c%") .ExecuteAsCollection<ProductCollection>(); Assert.IsTrue(p.Count == 25); } #endregion #region Expression Tests [Test] public void Exec_ExpressionSimpleOr() { ProductCollection products = Select.AllColumnsFrom<Product>() .WhereExpression("categoryID").IsEqualTo(5).And("productid").IsGreaterThan(10) .OrExpression("categoryID").IsEqualTo(2).And("productID").IsBetweenAnd(2, 5) .ExecuteAsCollection<ProductCollection>(); Assert.IsTrue(products.Count == 10); } [Test] public void Exec_NestedExpression() { ProductCollection products = Select.AllColumnsFrom<Product>() .WhereExpression("categoryID").IsEqualTo(5).And("productid").IsGreaterThan(10) .Or("categoryID").IsEqualTo(2).AndExpression("productID").IsBetweenAnd(2, 5) .ExecuteAsCollection<ProductCollection>(); Assert.IsTrue(products.Count == 3); } #endregion #region DISTINCT class Prod { private int _id; public int ProductID { get { return _id; } set { _id = value; } } } [Test] public void Exec_DistinctTypedList() { List<Prod> p = new Select("ProductID").Distinct().From("Order Details").ExecuteTypedList<Prod>(); Assert.IsTrue(p.Count == 77 ); } #endregion [Test] public void Exec_DistinctWithWhere() { OrderDetailCollection odc = new Select("ProductID","Quantity").Distinct() .From("Order Details") .Where("ProductID").IsLessThan(30) .ExecuteAsCollection<OrderDetailCollection>(); Assert.IsTrue(odc.Count == 429); } [Test] public void Exec_Distinct_JoinedWithLike() { ProductCollection p = DB.Select("CategoryID","ProductID") .Distinct() .From(Product.Schema) .InnerJoin(Category.Schema) .Where("CategoryName").Like("c%") .ExecuteAsCollection<ProductCollection>(); Assert.IsTrue(p.Count == 25); } #region Aggregates [Test] public void Exec_AggregateExpression() { double result = new Select(Aggregate.Sum("UnitPrice*Quantity", "ProductSales")) .From(OrderDetail.Schema) .ExecuteScalar<double>(); result = Math.Round(result, 2); Assert.IsTrue(result == 1354458.59); } #endregion #region Paging [Test] public void Exec_PagedSimple() { SubSonic.SqlQuery q = Select.AllColumnsFrom<Product>().Paged(1, 20).Where("productid").IsLessThan(100); int records = q.GetRecordCount(); Assert.IsTrue(records == 20); } [Test] public void Exec_PagedWithAggregate() { SubSonic.SqlQuery query = new SubSonic.Select( SubSonic.Aggregate.GroupBy(Product.Columns.CategoryID)) .Paged(1, 3) .From(Product.Schema) .Where(Product.Columns.ProductID).IsGreaterThan(0); string exMsg = ""; try { ProductCollection plist = query.ExecuteAsCollection<ProductCollection>(); } catch (Exception ex) { exMsg = ex.Message; } Assert.IsTrue(!exMsg.Contains("syntax near the keyword 'WHERE'"), exMsg + "\r\n" + query.BuildSqlStatement()); } [Test] public void Exec_PagedJoined() { //IDataReader rdr = Northwind.DB.Select("ProductId", "ProductName", "CategoryName") // .From("Products") // .InnerJoin(Northwind.Category.Schema) // .Paged(1, 20) // .ExecuteReader(); SubSonic.SqlQuery q = new Select("ProductId", "ProductName", "CategoryName").From("Products").InnerJoin(Category.Schema).Paged(1, 20); int records = q.GetRecordCount(); Assert.IsTrue(records == 20); } [Test] public void Exec_PagedView() { SubSonic.SqlQuery q = new Select().From(Invoice.Schema).Paged(1, 20); int records = q.GetRecordCount(); Assert.IsTrue(records == 20); } [Test] public void Exec_PagedViewJoined() { SubSonic.SqlQuery q = new Select().From(Invoice.Schema).Paged(1, 20).InnerJoin(Product.Schema); int records = q.GetRecordCount(); Assert.IsTrue(records == 20); } #endregion #region ANDs [Test] public void Exec_SimpleAnd() { int records = new Select() .From<Product>() .Where("UnitsInStock") .IsGreaterThan(10) .And("UnitsOnOrder") .IsGreaterThan(30) .GetRecordCount(); Assert.AreEqual(5, records); } [Test] public void Exec_SimpleAnd2() { int records = new Select() .From<Product>() .Where(Product.UnitsInStockColumn) .IsGreaterThan(10) .And(Product.UnitsOnOrderColumn) .IsGreaterThan(30) .GetRecordCount(); Assert.AreEqual(5, records); } [Test] public void Exec_SimpleAnd3() { SubSonic.SqlQuery query = new Select(Aggregate.GroupBy("ProductID"), Aggregate.Avg("UnitPrice"), Aggregate.Avg("Quantity")) .From("Order Details"); query .Where(Aggregate.Avg("UnitPrice")) .IsGreaterThan(30) .And(Aggregate.Avg("Quantity")) .IsGreaterThan(20); int records = query.GetRecordCount(); Assert.AreEqual(16, records); } #endregion #region INs [Test] public void Exec_SimpleIn() { int records = new Select().From(Product.Schema) .Where("productid").In(1, 2, 3, 4, 5) .GetRecordCount(); Assert.IsTrue(records == 5); } [Test] public void Exec_InWithSelect() { int records = Select.AllColumnsFrom<Product>() .Where("productid") .In( new Select("productid").From(Product.Schema) .Where("categoryid").IsEqualTo(5) ) .GetRecordCount(); Assert.IsTrue(records == 7); } [Test] public void Exec_MultipleInWithAnd() { SubSonic.SqlQuery query = new Select() .From(Product.Schema) .Where(Product.CategoryIDColumn).In(2) .And(Product.SupplierIDColumn).In(3); string sql = query.ToString(); int records = query.GetRecordCount(); Assert.AreEqual(2, records); } #endregion #region ORs [Test] public void Exec_SimpleOr() { int records = new Select() .From<Product>() .Where("UnitsInStock") .IsGreaterThan(100) .Or("UnitsOnOrder") .IsGreaterThan(50) .GetRecordCount(); Assert.AreEqual(17, records); } [Test] public void Exec_SimpleOr2() { int records = new Select() .From<Product>() .Where(Product.UnitsInStockColumn) .IsGreaterThan(100) .Or(Product.UnitsOnOrderColumn) .IsGreaterThan(50) .GetRecordCount(); Assert.AreEqual(17, records); } [Test] public void Exec_SimpleOr3() { int records = new Select(Aggregate.GroupBy("ProductID"), Aggregate.Avg("UnitPrice"), Aggregate.Avg("Quantity")) .From("Order Details") .Where(Aggregate.Avg("UnitPrice")) .IsGreaterThan(50) .Or(Aggregate.Avg("Quantity")) .IsGreaterThan(30) .GetRecordCount(); Assert.AreEqual(9, records); } #endregion #region Typed Collection Load [Test] public void Collection_LoadTypedObject() { List<PID> result = new Select("productid", "productname", "unitprice") .From(Product.Schema) .OrderAsc("productid") .ExecuteTypedList<PID>(); Assert.AreEqual(77, result.Count); Assert.AreEqual("Chai", result[0].ProductName); Assert.AreEqual(1, result[0].ProductID); Assert.AreEqual(50, result[0].UnitPrice); } [Test] public void Collection_LoadTypedActiveRecord() { List<Product> result = new Select("productid", "productname", "unitprice") .From<Product>() .OrderAsc("productid") .ExecuteTypedList<Product>(); Assert.IsTrue(result.Count == 77); Assert.IsTrue(result[0].ProductName == "Chai"); Assert.IsTrue(result[0].ProductID == 1); Assert.IsTrue(result[0].UnitPrice == 50); } private class PID { private int _id; private string _name; private decimal _price; public int ProductID { get { return _id; } set { _id = value; } } public string ProductName { get { return _name; } set { _name = value; } } public decimal UnitPrice { get { return _price; } set { _price = value; } } } #endregion #region Product Snippets (thanks Shawn Oster!) /// /// Product load. Uses same code as in sample documentation, should be tested /// to make sure the sample snippets are always valid. Sample snippets taken from: /// http://www.subsonicproject.com/view/using-the-generated-objects.aspx /// [Test] public void Products_Sample() { // sample snippet #1 Product p = new Product(1); Assert.AreEqual(1, p.ProductID); Assert.AreEqual("Chai", p.ProductName); // sample snippet #2 const string productGuid = "aa7aa741-8fd2-476b-b37d-b16e784874e6"; p = new Product("ProductGUID", productGuid); Assert.AreEqual(productGuid, p.ProductGUID.ToString()); Assert.AreEqual("Scottish Longbreads", p.ProductName); } /// /// Products_s the collection load 2. Tests the more common approach. /// [Test] public void Products_CollectionLoad2() { ProductCollection products = new ProductCollection().Load(); Assert.AreEqual(77, products.Count); } /// /// Product collection load with where clause. Uses same code as in sample documentation, should be tested /// to make sure the sample snippets are always valid. Sample snippets taken from: /// http://www.subsonicproject.com/view/using-the-generated-objects.aspx /// [Test] public void Products_CollectionSample() { // sample snippet #1 ProductCollection products = new ProductCollection().Where("categoryID", 1).Load(); Assert.AreEqual(12, products.Count); // sample snippet #2 products = new ProductCollection().Where("categoryID", 1).OrderByAsc("ProductName").Load(); Assert.AreEqual(12, products.Count); Assert.AreEqual("Chai", products[0].ProductName); Assert.AreEqual("Steeleye Stout", products[11].ProductName); } #endregion /// <summary> /// Testing that the gazillion ways to generate a .NotIn() Select /// all work the same way. /// </summary> [Test] public void Exec_NotInWithSelect() { // "verbose" style SubSonic.SqlQuery query1 = DB.Select() .From(Category.Schema) .Where(Category.Columns.CategoryID) .NotIn( DB.Select(Product.Columns.CategoryID) .From(Product.Schema) ); // "generics" style SubSonic.SqlQuery query2 = Select.AllColumnsFrom<Category>() .Where(Category.Columns.CategoryID) .NotIn( new Select(Product.Columns.CategoryID) .From(Product.Schema) ); // do both produce the same sql? string sql1 = query1.ToString(); string sql2 = query2.ToString(); Assert.AreEqual(sql1, sql2); // does the sql work? int records = query1.GetRecordCount(); Assert.IsTrue(records == 0); } [Test] public void StoredProc_TypedList() { List<CustomerOrder> orders = Northwind.SPs.CustOrderHist("ALFKI") .ExecuteTypedList<CustomerOrder>(); Assert.IsTrue(orders.Count == 11); } [Test] public void Select_Should_Work_With_SameColumn_Joins_UsingQualifiedColumns() { //http://www.codeplex.com/subsonic/WorkItem/View.aspx?WorkItemId=17149 SubSonic.SqlQuery s = new Select(Product.ProductIDColumn, Category.CategoryIDColumn) .From(Product.Schema) .InnerJoin(Category.CategoryIDColumn, Product.CategoryIDColumn) .Where(Category.CategoryIDColumn).IsEqualTo(5); Assert.AreEqual("[dbo].[Categories].[CategoryID]", s.Constraints[0].QualifiedColumnName); } [Test] public void Select_Using_StartsWith_C_ShouldReturn_9_Records() { int records = new Select().From<Product>() .Where(Northwind.Product.ProductNameColumn).StartsWith("c") .GetRecordCount(); Assert.AreEqual(9, records); } [Test] public void Select_Using_EndsWith_S_ShouldReturn_9_Records() { int records = new Select().From<Product>() .Where(Northwind.Product.ProductNameColumn) .EndsWith("s").GetRecordCount(); Assert.AreEqual(9, records); } [Test] public void Select_Using_Contains_Ch_ShouldReturn_14_Records() { int records = new Select().From<Product>() .Where(Northwind.Product.ProductNameColumn) .ContainsString("ch").GetRecordCount(); Assert.AreEqual(14, records); } #region Nested type: CustomerOrder /// <summary> /// Class for holding SP Results for CustOrderHist /// </summary> private class CustomerOrder { private string productName; private int total; public string ProductName { get { return productName; } set { productName = value; } } public int Total { get { return total; } set { total = value; } } } #endregion #region Distinct Support [Test] public void SqlQuery_when_setting_distinct_it_should_set_IsDistinct() { SubSonic.SqlQuery query= new Select(Product.SupplierIDColumn).From<Product>().Distinct(); Assert.IsTrue(query.IsDistinct); } [Test] public void SqlQuery_should_handle_distinct() { // ProductCollection select = new Select(Product.SupplierIDColumn).From<Product>().Distinct().ExecuteAsCollection<ProductCollection>(); // // - this fails because .From returns an SqlQuery object not a Select object, and the SqlQuery version of .Distinct() // doesn't set the 'Distinct' fragment to a non-empty string. This is beyond me without a lot more head scratching // (there are some situations where DISTINCT should be suppressed), so I'll just remember to put the .Distinct after the Select. ProductCollection select = new Select(Product.SupplierIDColumn).Distinct().From<Product>().ExecuteAsCollection<ProductCollection>(); Assert.AreEqual(29, select.Count); } [Test] public void SqlQuery_GetRecordCount_should_handle_distinct() { int select = new Select(Product.SupplierIDColumn).Distinct().From<Product>().GetRecordCount(); Assert.AreEqual(29, select); } [Test] public void SqlQuery_Can_Compare_Columns() { //var result = new Select().From("Products").WhereExpression(; } #endregion [Test] public void ActiveRecord_IsLoaded_ShouldBe_False_When_Record_Not_Present_Using_PK_Constructor() { Product p = new Product(1); Assert.IsTrue(p.IsLoaded); p = new Product(1111111); Assert.IsFalse(p.IsLoaded); } [Test] public void ActiveRecord_IsLoaded_ShouldBe_False_When_Record_Not_Present_Using_Key_Constructor() { Product p = new Product(1); Assert.IsTrue(p.IsLoaded); p = new Product("ProductID",111111); Assert.IsFalse(p.IsLoaded); } [Test] public void Constraints_Should_Be_Valid_When_Table_Not_In_From() { ProductCollection result = new Select().From(Product.Schema) .InnerJoin(Category.CategoryIDColumn, Product.CategoryIDColumn) .Where(Category.CategoryIDColumn) .IsEqualTo(5).And(Product.UnitPriceColumn) .IsGreaterThan(1) .OrderAsc("ProductID") .ExecuteAsCollection<ProductCollection>(); Assert.IsTrue(result.Count > 0); } [Test] public void SelectAllColumns_With_WhereExpression_And_QualifiedColumn_Formats_Where_Correctly() { string sql=DB.SelectAllColumnsFrom<Product>() .WhereExpression(Product.ProductIDColumn.QualifiedName).IsEqualTo(1) .And(Product.ProductNameColumn.QualifiedName).IsEqualTo("ABC") .BuildSqlStatement(); Assert.IsFalse(sql.Contains("WHERE ([dbo].[Products].[[dbo].[Products]")); } [Test] public void SelectAllColumns_With_WhereExpression_And_QualifiedColumn_Formats_Where_Correctly_And_Executes() { int recordCount = DB.SelectAllColumnsFrom<Product>() .WhereExpression(Product.ProductIDColumn.QualifiedName).IsEqualTo(1) .And(Product.ProductIDColumn.QualifiedName).IsLessThan(2) .GetRecordCount(); Assert.AreEqual(1, recordCount); } [Test] public void Select_Paged_Can_Covert_To_SqlQuery() { bool threw = false; try { SubSonic.SqlQuery q2 = new SubSonic.SqlQuery().From(Product.Schema) .InnerJoin(Category.Schema) .Where("productid").IsLessThan(10) .Paged(1, 20); ProductCollection pc2 = q2.ExecuteAsCollection<ProductCollection>(); } catch { //nada threw = true; } Assert.IsFalse(threw); } [Test] public void Select_With_ExecuteTypedList_Should_Work_With_List_of_Guid() { List<Guid> list = new Select("ProductGUID").From<Product>().ExecuteTypedList<Guid>(); Assert.AreNotEqual(Guid.Empty, list[0]); } [Test] public void Saving_String_Property_With_StringValue_Null_Results_In_NullValue_In_DB() { Product p = new Product(2); p.QuantityPerUnit = "null"; p.Save(); p = new Product(2); Assert.IsNotNull(p.QuantityPerUnit); Assert.AreEqual("null", p.QuantityPerUnit); } [Test] public void MySql_Should_Set_Logical_Deletes() { //SouthwindRepository.Logicaldelete item=SouthwindRepository.DB.Get<SouthwindRepository.Logicaldelete>(1); //SouthwindRepository.DB.Delete<SouthwindRepository.Logicaldelete>(item); //pull it back out //item = SouthwindRepository.DB.Get<SouthwindRepository.Logicaldelete>(1); //Assert.AreEqual(true, item.IsDeleted); } } }
/* --------------------------------------------------------------------------- * * Copyright (c) Routrek Networks, Inc. All Rights Reserved.. * * This file is a part of the Granados SSH Client Library that is subject to * the license included in the distributed package. * You may not use this file except in compliance with the license. * * --------------------------------------------------------------------------- */ using System; using System.Collections; using System.IO; using System.Threading; using System.Diagnostics; using System.Net.Sockets; using System.Text; using System.Security.Cryptography; using Routrek.PKI; using Routrek.SSHC; using Routrek.Toolkit; namespace Routrek.SSHCV2 { public sealed class SSH2Connection : SSHConnection { //packet count for transmission and reception private int _tSequence; //MAC for transmission and reception private MAC _tMAC; private SSH2PacketBuilder _packetBuilder; //server info private SSH2ConnectionInfo _cInfo; private bool _waitingForPortForwardingResponse; private KeyExchanger _asyncKeyExchanger; public SSH2Connection(SSHConnectionParameter param, ISSHConnectionEventReceiver r, string serverversion, string clientversion) : base(param, r) { _cInfo = new SSH2ConnectionInfo(); _cInfo._serverVersionString = serverversion; _cInfo._clientVersionString = clientversion; _packetBuilder = new SSH2PacketBuilder(new SynchronizedSSH2PacketHandler()); } internal override IByteArrayHandler PacketBuilder { get { return _packetBuilder; } } public override SSHConnectionInfo ConnectionInfo { get { return _cInfo; } } internal override AuthenticationResult Connect(AbstractSocket s) { _stream = s; KeyExchanger kex = new KeyExchanger(this, null); if(!kex.SynchronousKexExchange()) { _stream.Close(); return AuthenticationResult.Failure; } //Step3 user authentication ServiceRequest("ssh-userauth"); _authenticationResult = UserAuth(); return _authenticationResult; } private void ServiceRequest(string servicename) { SSH2DataWriter wr = new SSH2DataWriter(); wr.WritePacketType(PacketType.SSH_MSG_SERVICE_REQUEST); wr.Write(servicename); TransmitPacket(wr.ToByteArray()); byte[] response = ReceivePacket().Data; SSH2DataReader re = new SSH2DataReader(response); PacketType t = re.ReadPacketType(); if(t!=PacketType.SSH_MSG_SERVICE_ACCEPT) { throw new SSHException("service establishment failed "+t); } string s = Encoding.ASCII.GetString(re.ReadString()); if(servicename!=s) throw new SSHException("protocol error"); } private AuthenticationResult UserAuth() { string sn = "ssh-connection"; SSH2DataWriter wr = new SSH2DataWriter(); wr.WritePacketType(PacketType.SSH_MSG_USERAUTH_REQUEST); wr.Write(_param.UserName); if(_param.AuthenticationType==AuthenticationType.Password) { //Password authentication wr.Write(sn); wr.Write("password"); wr.Write(false); wr.Write(_param.Password); } else if(_param.AuthenticationType==AuthenticationType.KeyboardInteractive) { wr.Write(sn); wr.Write("keyboard-interactive"); wr.Write(""); //lang wr.Write(""); //submethod } else { //public key authentication SSH2UserAuthKey kp = SSH2UserAuthKey.FromSECSHStyleFile(_param.IdentityFile, _param.Password); SSH2DataWriter signsource = new SSH2DataWriter(); signsource.WriteAsString(_sessionID); signsource.WritePacketType(PacketType.SSH_MSG_USERAUTH_REQUEST); signsource.Write(_param.UserName); signsource.Write(sn); signsource.Write("publickey"); signsource.Write(true); signsource.Write(SSH2Util.PublicKeyAlgorithmName(kp.Algorithm)); signsource.WriteAsString(kp.GetPublicKeyBlob()); SSH2DataWriter signpack = new SSH2DataWriter(); signpack.Write(SSH2Util.PublicKeyAlgorithmName(kp.Algorithm)); signpack.WriteAsString(kp.Sign(signsource.ToByteArray())); wr.Write(sn); wr.Write("publickey"); wr.Write(true); wr.Write(SSH2Util.PublicKeyAlgorithmName(kp.Algorithm)); wr.WriteAsString(kp.GetPublicKeyBlob()); wr.WriteAsString(signpack.ToByteArray()); } TransmitPacket(wr.ToByteArray()); _authenticationResult = ProcessAuthenticationResponse(); if(_authenticationResult==AuthenticationResult.Failure) throw new SSHException(Strings.GetString("AuthenticationFailed")); return _authenticationResult; } private AuthenticationResult ProcessAuthenticationResponse() { do { SSH2DataReader response = new SSH2DataReader(ReceivePacket().Data); PacketType h = response.ReadPacketType(); if(h==PacketType.SSH_MSG_USERAUTH_FAILURE) { string msg = Encoding.ASCII.GetString(response.ReadString()); return AuthenticationResult.Failure; } else if(h==PacketType.SSH_MSG_USERAUTH_BANNER) { Debug.WriteLine("USERAUTH_BANNER"); } else if(h==PacketType.SSH_MSG_USERAUTH_SUCCESS) { _packetBuilder.Handler = new CallbackSSH2PacketHandler(this); return AuthenticationResult.Success; //successfully exit } else if(h==PacketType.SSH_MSG_USERAUTH_INFO_REQUEST) { string name = Encoding.ASCII.GetString(response.ReadString()); string inst = Encoding.ASCII.GetString(response.ReadString()); string lang = Encoding.ASCII.GetString(response.ReadString()); int num = response.ReadInt32(); string[] prompts = new string[num]; for(int i=0; i<num; i++) { prompts[i] = Encoding.ASCII.GetString(response.ReadString()); bool echo = response.ReadBool(); } _eventReceiver.OnAuthenticationPrompt(prompts); return AuthenticationResult.Prompt; } else throw new SSHException("protocol error: unexpected packet type "+h); } while(true); } public AuthenticationResult DoKeyboardInteractiveAuth(string[] input) { if(_param.AuthenticationType!=AuthenticationType.KeyboardInteractive) throw new SSHException("DoKeyboardInteractiveAuth() must be called with keyboard-interactive authentication"); SSH2DataWriter re = new SSH2DataWriter(); re.WritePacketType(PacketType.SSH_MSG_USERAUTH_INFO_RESPONSE); re.Write(input.Length); foreach(string t in input) re.Write(t); TransmitPacket(re.ToByteArray()); _authenticationResult = ProcessAuthenticationResponse(); //try again on failure if(_authenticationResult==AuthenticationResult.Failure) { SSH2DataWriter wr = new SSH2DataWriter(); wr.WritePacketType(PacketType.SSH_MSG_USERAUTH_REQUEST); wr.Write(_param.UserName); wr.Write("ssh-connection"); wr.Write("keyboard-interactive"); wr.Write(""); //lang wr.Write(""); //submethod TransmitPacket(wr.ToByteArray()); _authenticationResult = ProcessAuthenticationResponse(); } return _authenticationResult; } public override SSHChannel OpenShell(ISSHChannelEventReceiver receiver) { //open channel SSH2DataWriter wr = new SSH2DataWriter(); wr.WritePacketType(PacketType.SSH_MSG_CHANNEL_OPEN); wr.Write("session"); int local_channel = this.RegisterChannelEventReceiver(null, receiver)._localID; wr.Write(local_channel); wr.Write(_param.WindowSize); //initial window size int windowsize = _param.WindowSize; wr.Write(_param.MaxPacketSize); //max packet size SSH2Channel channel = new SSH2Channel(this, ChannelType.Shell, local_channel); TransmitPacket(wr.ToByteArray()); return channel; } public override SSHChannel ForwardPort(ISSHChannelEventReceiver receiver, string remote_host, int remote_port, string originator_host, int originator_port) { SSH2DataWriter wr = new SSH2DataWriter(); wr.WritePacketType(PacketType.SSH_MSG_CHANNEL_OPEN); wr.Write("direct-tcpip"); int local_id = RegisterChannelEventReceiver(null, receiver)._localID; wr.Write(local_id); wr.Write(_param.WindowSize); //initial window size int windowsize = _param.WindowSize; wr.Write(_param.MaxPacketSize); //max packet size wr.Write(remote_host); wr.Write(remote_port); wr.Write(originator_host); wr.Write(originator_port); SSH2Channel channel = new SSH2Channel(this, ChannelType.ForwardedLocalToRemote, local_id); TransmitPacket(wr.ToByteArray()); return channel; } public override void ListenForwardedPort(string allowed_host, int bind_port) { SSH2DataWriter wr = new SSH2DataWriter(); wr.WritePacketType(PacketType.SSH_MSG_GLOBAL_REQUEST); wr.Write("tcpip-forward"); wr.Write(true); wr.Write(allowed_host); wr.Write(bind_port); _waitingForPortForwardingResponse = true; TransmitPacket(wr.ToByteArray()); } public override void CancelForwardedPort(string host, int port) { SSH2DataWriter wr = new SSH2DataWriter(); wr.WritePacketType(PacketType.SSH_MSG_GLOBAL_REQUEST); wr.Write("cancel-tcpip-forward"); wr.Write(true); wr.Write(host); wr.Write(port); TransmitPacket(wr.ToByteArray()); } private void ProcessPortforwardingRequest(ISSHConnectionEventReceiver receiver, SSH2DataReader reader) { string method = Encoding.ASCII.GetString(reader.ReadString()); int remote_channel = reader.ReadInt32(); int window_size = reader.ReadInt32(); //skip initial window size int servermaxpacketsize = reader.ReadInt32(); string host = Encoding.ASCII.GetString(reader.ReadString()); int port = reader.ReadInt32(); string originator_ip = Encoding.ASCII.GetString(reader.ReadString()); int originator_port = reader.ReadInt32(); PortForwardingCheckResult r = receiver.CheckPortForwardingRequest(host,port,originator_ip,originator_port); SSH2DataWriter wr = new SSH2DataWriter(); if(r.allowed) { //send OPEN_CONFIRMATION SSH2Channel channel = new SSH2Channel(this, ChannelType.ForwardedRemoteToLocal, RegisterChannelEventReceiver(null, r.channel)._localID, remote_channel, servermaxpacketsize); wr.WritePacketType(PacketType.SSH_MSG_CHANNEL_OPEN_CONFIRMATION); wr.Write(remote_channel); wr.Write(channel.LocalChannelID); wr.Write(_param.WindowSize); //initial window size wr.Write(_param.MaxPacketSize); //max packet size receiver.EstablishPortforwarding(r.channel, channel); } else { wr.WritePacketType(PacketType.SSH_MSG_CHANNEL_OPEN_FAILURE); wr.Write(remote_channel); wr.Write(r.reason_code); wr.Write(r.reason_message); wr.Write(""); //lang tag } TransmitPacket(wr.ToByteArray()); } internal SSH2Packet TransmitPacket(byte[] payload) { lock(_tLockObject) { SSH2Packet p = SSH2Packet.FromPlainPayload(payload, _tCipher==null? 8 : _tCipher.BlockSize, _param.Random); if(_tMAC!=null) p.CalcHash(_tMAC, _tSequence); _tSequence++; p.WriteTo(_stream, _tCipher); return p; } } //synchronous reception internal SSH2Packet ReceivePacket() { while(true) { SSH2Packet p = null; SynchronizedSSH2PacketHandler handler = (SynchronizedSSH2PacketHandler)_packetBuilder.Handler; if(!handler.HasPacket) { handler.Wait(); if(handler.State==ReceiverState.Error) throw new SSHException(handler.ErrorMessage); else if(handler.State==ReceiverState.Closed) throw new SSHException("socket closed"); } p = handler.PopPacket(); SSH2DataReader r = new SSH2DataReader(p.Data); PacketType pt = r.ReadPacketType(); if(pt==PacketType.SSH_MSG_IGNORE) { if(_eventReceiver!=null) _eventReceiver.OnIgnoreMessage(r.ReadString()); } else if(pt==PacketType.SSH_MSG_DEBUG) { bool f = r.ReadBool(); if(_eventReceiver!=null) _eventReceiver.OnDebugMessage(f, r.ReadString()); } else return p; } } internal void AsyncReceivePacket(SSH2Packet packet) { try { ProcessPacket(packet); } catch(Exception ex) { //Debug.WriteLine(ex.StackTrace); if(!_closed) _eventReceiver.OnError(ex, ex.Message); } } private bool ProcessPacket(SSH2Packet packet) { SSH2DataReader r = new SSH2DataReader(packet.Data); PacketType pt = r.ReadPacketType(); //Debug.WriteLine("ProcessPacket pt="+pt); if(pt==PacketType.SSH_MSG_DISCONNECT) { int errorcode = r.ReadInt32(); //string description = Encoding.ASCII.GetString(r.ReadString()); _eventReceiver.OnConnectionClosed(); return false; } else if(_waitingForPortForwardingResponse) { if(pt!=PacketType.SSH_MSG_REQUEST_SUCCESS) _eventReceiver.OnUnknownMessage((byte)pt, r.Image); _waitingForPortForwardingResponse = false; return true; } else if(pt==PacketType.SSH_MSG_CHANNEL_OPEN) { ProcessPortforwardingRequest(_eventReceiver, r); return true; } else if(pt>=PacketType.SSH_MSG_CHANNEL_OPEN_CONFIRMATION && pt<=PacketType.SSH_MSG_CHANNEL_FAILURE) { int local_channel = r.ReadInt32(); ChannelEntry e = FindChannelEntry(local_channel); if(e!=null) //throw new SSHException("Unknown channel "+local_channel); ((SSH2Channel)e._channel).ProcessPacket(e._receiver, pt, 5+r.Rest, r); else Debug.WriteLine("unexpected channel pt="+pt+" local_channel="+local_channel.ToString()); return true; } else if(pt==PacketType.SSH_MSG_IGNORE) { _eventReceiver.OnIgnoreMessage(r.ReadString()); return true; } else if(_asyncKeyExchanger!=null) { _asyncKeyExchanger.AsyncProcessPacket(packet); return true; } else if(pt==PacketType.SSH_MSG_KEXINIT) { Debug.WriteLine("Host sent KEXINIT"); _asyncKeyExchanger = new KeyExchanger(this, _sessionID); _asyncKeyExchanger.AsyncProcessPacket(packet); return true; } else { _eventReceiver.OnUnknownMessage((byte)pt, r.Image); return false; } } public override void Disconnect(string msg) { if(_closed) return; SSH2DataWriter wr = new SSH2DataWriter(); wr.WritePacketType(PacketType.SSH_MSG_DISCONNECT); wr.Write(0); wr.Write(msg); wr.Write(""); //language TransmitPacket(wr.ToByteArray()); _stream.Flush(); _closed = true; _stream.Close(); } public override void Close() { if(_closed) return; _closed = true; _stream.Close(); } public override void SendIgnorableData(string msg) { SSH2DataWriter w = new SSH2DataWriter(); w.WritePacketType(PacketType.SSH_MSG_IGNORE); w.Write(msg); TransmitPacket(w.ToByteArray()); } public void ReexchangeKeys() { _asyncKeyExchanger = new KeyExchanger(this, _sessionID); _asyncKeyExchanger.AsyncStartReexchange(); } internal void LockCommunication() { _packetBuilder.SetSignal(false); } internal void UnlockCommunication() { _packetBuilder.SetSignal(true); } internal void RefreshKeys(byte[] sessionID, Cipher tc, Cipher rc, MAC tm, MAC rm) { _sessionID = sessionID; _tCipher = tc; _tMAC = tm; _packetBuilder.SetCipher(rc, _param.CheckMACError? rm : null); _asyncKeyExchanger = null; } } public class SSH2Channel : SSHChannel { //channel property protected int _windowSize; protected int _leftWindowSize; protected int _serverMaxPacketSize; //negotiation status protected int _negotiationStatus; public SSH2Channel(SSHConnection con, ChannelType type, int local_id) : base(con, type, local_id) { _windowSize = _leftWindowSize = con.Param.WindowSize; _negotiationStatus = type==ChannelType.Shell? 3 : type==ChannelType.ForwardedLocalToRemote? 1 : type==ChannelType.Session? 1 : 0; } public SSH2Channel(SSHConnection con, ChannelType type, int local_id, int remote_id, int maxpacketsize) : base(con, type, local_id) { _windowSize = _leftWindowSize = con.Param.WindowSize; Debug.Assert(type==ChannelType.ForwardedRemoteToLocal); _remoteID = remote_id; _serverMaxPacketSize = maxpacketsize; _negotiationStatus = 0; } public override void ResizeTerminal(int width, int height, int pixel_width, int pixel_height) { SSH2DataWriter wr = new SSH2DataWriter(); wr.WritePacketType(PacketType.SSH_MSG_CHANNEL_REQUEST); wr.Write(_remoteID); wr.Write("window-change"); wr.Write(false); wr.Write(width); wr.Write(height); wr.Write(pixel_width); //no graphics wr.Write(pixel_height); TransmitPacket(wr.ToByteArray()); } public override void Transmit(byte[] data) { //!!it is better idea that we wait a WINDOW_ADJUST if the left size is lack SSH2DataWriter wr = new SSH2DataWriter(); wr.WritePacketType(PacketType.SSH_MSG_CHANNEL_DATA); wr.Write(_remoteID); wr.WriteAsString(data); TransmitPacket(wr.ToByteArray()); } public override void Transmit(byte[] data, int offset, int length) { SSH2DataWriter wr = new SSH2DataWriter(); wr.WritePacketType(PacketType.SSH_MSG_CHANNEL_DATA); wr.Write(_remoteID); wr.WriteAsString(data, offset, length); TransmitPacket(wr.ToByteArray()); } public override void SendEOF() { if(_connection.IsClosed) return; SSH2DataWriter wr = new SSH2DataWriter(); wr.WritePacketType(PacketType.SSH_MSG_CHANNEL_EOF); wr.Write(_remoteID); TransmitPacket(wr.ToByteArray()); } public override void Close() { if(_connection.IsClosed) return; SSH2DataWriter wr = new SSH2DataWriter(); wr.WritePacketType(PacketType.SSH_MSG_CHANNEL_CLOSE); wr.Write(_remoteID); TransmitPacket(wr.ToByteArray()); } //maybe this is SSH2 only feature public void SetEnvironmentVariable(string name, string value) { SSH2DataWriter wr = new SSH2DataWriter(); wr.WritePacketType(PacketType.SSH_MSG_CHANNEL_REQUEST); wr.Write(_remoteID); wr.Write("env"); wr.Write(false); wr.Write(name); wr.Write(value); TransmitPacket(wr.ToByteArray()); } public void SendBreak(int time) { SSH2DataWriter wr = new SSH2DataWriter(); wr.WritePacketType(PacketType.SSH_MSG_CHANNEL_REQUEST); wr.Write(_remoteID); wr.Write("break"); wr.Write(true); wr.Write(time); TransmitPacket(wr.ToByteArray()); } internal void ProcessPacket(ISSHChannelEventReceiver receiver, PacketType pt, int data_length, SSH2DataReader re) { //NOTE: the offset of 're' is next to 'receipiant channel' field _leftWindowSize -= data_length; while(_leftWindowSize <= _windowSize) { SSH2DataWriter adj = new SSH2DataWriter(); adj.WritePacketType(PacketType.SSH_MSG_CHANNEL_WINDOW_ADJUST); adj.Write(_remoteID); adj.Write(_windowSize); TransmitPacket(adj.ToByteArray()); _leftWindowSize += _windowSize; //Debug.WriteLine("Window size is adjusted to " + _leftWindowSize); } if(pt==PacketType.SSH_MSG_CHANNEL_WINDOW_ADJUST) { int w = re.ReadInt32(); //Debug.WriteLine(String.Format("Window Adjust +={0}",w)); } else if(_negotiationStatus!=0) { //when the negotiation is not completed if(_type==ChannelType.Shell) OpenShell(receiver, pt, re); else if(_type==ChannelType.ForwardedLocalToRemote) ReceivePortForwardingResponse(receiver, pt, re); else if(_type==ChannelType.Session) EstablishSession(receiver, pt, re); } else { switch(pt) { case PacketType.SSH_MSG_CHANNEL_DATA: { int len = re.ReadInt32(); receiver.OnData(re.Image, re.Offset, len); } break; case PacketType.SSH_MSG_CHANNEL_EXTENDED_DATA: { int t = re.ReadInt32(); byte[] data = re.ReadString(); receiver.OnExtendedData(t, data); } break; case PacketType.SSH_MSG_CHANNEL_REQUEST: { string request = Encoding.ASCII.GetString(re.ReadString()); bool reply = re.ReadBool(); if(request=="exit-status") { int status = re.ReadInt32(); } else if(reply) { //we reject unknown requests including keep-alive check SSH2DataWriter wr = new SSH2DataWriter(); wr.Write((byte)PacketType.SSH_MSG_CHANNEL_FAILURE); wr.Write(_remoteID); TransmitPacket(wr.ToByteArray()); } } break; case PacketType.SSH_MSG_CHANNEL_EOF: receiver.OnChannelEOF(); break; case PacketType.SSH_MSG_CHANNEL_CLOSE: _connection.UnregisterChannelEventReceiver(_localID); receiver.OnChannelClosed(); break; case PacketType.SSH_MSG_CHANNEL_FAILURE: case PacketType.SSH_MSG_CHANNEL_SUCCESS: receiver.OnMiscPacket((byte)pt, re.Image, re.Offset, re.Rest); break; default: receiver.OnMiscPacket((byte)pt, re.Image, re.Offset, re.Rest); Debug.WriteLine("Unknown Packet "+pt); break; } } } private void TransmitPacket(byte[] data) { ((SSH2Connection)_connection).TransmitPacket(data); } private void OpenShell(ISSHChannelEventReceiver receiver, PacketType pt, SSH2DataReader reader) { if(_negotiationStatus==3) { if(pt!=PacketType.SSH_MSG_CHANNEL_OPEN_CONFIRMATION) { if(pt!=PacketType.SSH_MSG_CHANNEL_OPEN_FAILURE) receiver.OnChannelError(null, "opening channel failed; packet type="+pt); else { int errcode = reader.ReadInt32(); string msg = Encoding.ASCII.GetString(reader.ReadString()); receiver.OnChannelError(null, msg); } Close(); } else { _remoteID = reader.ReadInt32(); _serverMaxPacketSize = reader.ReadInt32(); //open pty SSH2DataWriter wr = new SSH2DataWriter(); wr.WritePacketType(PacketType.SSH_MSG_CHANNEL_REQUEST); wr.Write(_remoteID); wr.Write("pty-req"); wr.Write(true); wr.Write(_connection.Param.TerminalName); wr.Write(_connection.Param.TerminalWidth); wr.Write(_connection.Param.TerminalHeight); wr.Write(_connection.Param.TerminalPixelWidth); wr.Write(_connection.Param.TerminalPixelHeight); wr.WriteAsString(new byte[0]); TransmitPacket(wr.ToByteArray()); _negotiationStatus = 2; } } else if(_negotiationStatus==2) { if(pt!=PacketType.SSH_MSG_CHANNEL_SUCCESS) { receiver.OnChannelError(null, "opening pty failed"); Close(); } else { //open shell SSH2DataWriter wr = new SSH2DataWriter(); wr.Write((byte)PacketType.SSH_MSG_CHANNEL_REQUEST); wr.Write(_remoteID); wr.Write("shell"); wr.Write(true); TransmitPacket(wr.ToByteArray()); _negotiationStatus = 1; } } else if(_negotiationStatus==1) { if(pt!=PacketType.SSH_MSG_CHANNEL_SUCCESS) { receiver.OnChannelError(null, "Opening shell failed: packet type="+pt.ToString()); Close(); } else { receiver.OnChannelReady(); _negotiationStatus = 0; //goal! } } else Debug.Assert(false); } private void ReceivePortForwardingResponse(ISSHChannelEventReceiver receiver, PacketType pt, SSH2DataReader reader) { if(_negotiationStatus==1) { if(pt!=PacketType.SSH_MSG_CHANNEL_OPEN_CONFIRMATION) { if(pt!=PacketType.SSH_MSG_CHANNEL_OPEN_FAILURE) receiver.OnChannelError(null, "opening channel failed; packet type="+pt); else { int errcode = reader.ReadInt32(); string msg = Encoding.ASCII.GetString(reader.ReadString()); receiver.OnChannelError(null, msg); } Close(); } else { _remoteID = reader.ReadInt32(); _serverMaxPacketSize = reader.ReadInt32(); _negotiationStatus = 0; receiver.OnChannelReady(); } } else Debug.Assert(false); } private void EstablishSession(ISSHChannelEventReceiver receiver, PacketType pt, SSH2DataReader reader) { if(_negotiationStatus==1) { if(pt!=PacketType.SSH_MSG_CHANNEL_OPEN_CONFIRMATION) { if(pt!=PacketType.SSH_MSG_CHANNEL_OPEN_FAILURE) receiver.OnChannelError(null, "opening channel failed; packet type="+pt); else { int remote_id = reader.ReadInt32(); int errcode = reader.ReadInt32(); string msg = Encoding.ASCII.GetString(reader.ReadString()); receiver.OnChannelError(null, msg); } Close(); } else { _remoteID = reader.ReadInt32(); _serverMaxPacketSize = reader.ReadInt32(); _negotiationStatus = 0; receiver.OnChannelReady(); } } else Debug.Assert(false); } } internal class KeyExchanger { private SSH2Connection _con; private SSHConnectionParameter _param; private SSH2ConnectionInfo _cInfo; //payload of KEXINIT message private byte[] _serverKEXINITPayload; private byte[] _clientKEXINITPayload; //true if the host sent KEXINIT first private bool _startedByHost; private ManualResetEvent _newKeyEvent; //status private enum Status { INITIAL, WAIT_KEXINIT, WAIT_KEXDH_REPLY, WAIT_NEWKEYS, FINISHED } private Status _status; private BigInteger _x; private BigInteger _e; private BigInteger _k; private byte[] _hash; private byte[] _sessionID; //results Cipher _rc; Cipher _tc; MAC _rm; MAC _tm; private void TransmitPacket(byte[] payload) { _con.TransmitPacket(payload); } public KeyExchanger(SSH2Connection con, byte[] sessionID) { _con = con; _param = con.Param; _cInfo = (SSH2ConnectionInfo)con.ConnectionInfo; _sessionID = sessionID; _status = Status.INITIAL; } public bool SynchronousKexExchange() { SendKEXINIT(); ProcessKEXINIT(_con.ReceivePacket()); SendKEXDHINIT(); if(!ProcessKEXDHREPLY(_con.ReceivePacket())) return false; SendNEWKEYS(); ProcessNEWKEYS(_con.ReceivePacket()); return true; } public void AsyncStartReexchange() { _startedByHost = false; _status = Status.WAIT_KEXINIT; SendKEXINIT(); } public void AsyncProcessPacket(SSH2Packet packet) { switch(_status) { case Status.INITIAL: _startedByHost = true; ProcessKEXINIT(packet); SendKEXINIT(); SendKEXDHINIT(); break; case Status.WAIT_KEXINIT: ProcessKEXINIT(packet); SendKEXDHINIT(); break; case Status.WAIT_KEXDH_REPLY: ProcessKEXDHREPLY(packet); SendNEWKEYS(); break; case Status.WAIT_NEWKEYS: ProcessNEWKEYS(packet); Debug.Assert(_status==Status.FINISHED); break; } } private void SendKEXINIT() { SSH2DataWriter wr = new SSH2DataWriter(); wr.WritePacketType(PacketType.SSH_MSG_KEXINIT); byte[] cookie = new byte[16]; _param.Random.NextBytes(cookie); wr.Write(cookie); wr.Write("diffie-hellman-group1-sha1"); // kex_algorithms wr.Write(FormatHostKeyAlgorithmDescription()); // server_host_key_algorithms wr.Write(FormatCipherAlgorithmDescription()); // encryption_algorithms_client_to_server wr.Write(FormatCipherAlgorithmDescription()); // encryption_algorithms_server_to_client wr.Write("hmac-sha1"); // mac_algorithms_client_to_server wr.Write("hmac-sha1"); // mac_algorithms_server_to_client wr.Write("none"); // compression_algorithms_client_to_server wr.Write("none"); // compression_algorithms_server_to_client wr.Write(""); // languages_client_to_server wr.Write(""); // languages_server_to_client wr.Write(false); //Indicates whether a guessed key exchange packet follows wr.Write(0); //reserved for future extension _clientKEXINITPayload = wr.ToByteArray(); _status = Status.WAIT_KEXINIT; TransmitPacket(_clientKEXINITPayload); } private void ProcessKEXINIT(SSH2Packet packet) { _serverKEXINITPayload = packet.Data; SSH2DataReader re = new SSH2DataReader(_serverKEXINITPayload); byte[] head = re.Read(17); //Type and cookie if(head[0]!=(byte)PacketType.SSH_MSG_KEXINIT) throw new SSHException(String.Format("Server response is not SSH_MSG_KEXINIT but {0}", head[0])); Encoding enc = Encoding.ASCII; string kex = enc.GetString(re.ReadString()); _cInfo._supportedKEXAlgorithms = kex; CheckAlgorithmSupport("keyexchange", kex, "diffie-hellman-group1-sha1"); string host_key = enc.GetString(re.ReadString()); _cInfo._supportedHostKeyAlgorithms = host_key; _cInfo._algorithmForHostKeyVerification = DecideHostKeyAlgorithm(host_key); string enc_cs = enc.GetString(re.ReadString()); _cInfo._supportedCipherAlgorithms = enc_cs; _cInfo._algorithmForTransmittion = DecideCipherAlgorithm(enc_cs); string enc_sc = enc.GetString(re.ReadString()); _cInfo._algorithmForReception = DecideCipherAlgorithm(enc_sc); string mac_cs = enc.GetString(re.ReadString()); CheckAlgorithmSupport("mac", mac_cs, "hmac-sha1"); string mac_sc = enc.GetString(re.ReadString()); CheckAlgorithmSupport("mac", mac_sc, "hmac-sha1"); string comp_cs = enc.GetString(re.ReadString()); CheckAlgorithmSupport("compression", comp_cs, "none"); string comp_sc = enc.GetString(re.ReadString()); CheckAlgorithmSupport("compression", comp_sc, "none"); string lang_cs = enc.GetString(re.ReadString()); string lang_sc = enc.GetString(re.ReadString()); bool flag = re.ReadBool(); int reserved = re.ReadInt32(); Debug.Assert(re.Rest==0); if(flag) throw new SSHException("Algorithm negotiation failed"); } private void SendKEXDHINIT() { //Round1 computes and sends [e] byte[] sx = new byte[16]; _param.Random.NextBytes(sx); _x = new BigInteger(sx); _e = new BigInteger(2).modPow(_x, DH_PRIME); SSH2DataWriter wr = new SSH2DataWriter(); wr.WritePacketType(PacketType.SSH_MSG_KEXDH_INIT); wr.Write(_e); _status = Status.WAIT_KEXDH_REPLY; TransmitPacket(wr.ToByteArray()); } private bool ProcessKEXDHREPLY(SSH2Packet packet) { //Round2 receives response SSH2DataReader re = new SSH2DataReader(packet.Data); PacketType h = re.ReadPacketType(); if(h!=PacketType.SSH_MSG_KEXDH_REPLY) throw new SSHException(String.Format("KeyExchange response is not KEXDH_REPLY but {0}", h)); byte[] key_and_cert = re.ReadString(); BigInteger f = re.ReadMPInt(); byte[] signature = re.ReadString(); Debug.Assert(re.Rest==0); //Round3 calc hash H SSH2DataWriter wr = new SSH2DataWriter(); _k = f.modPow(_x, DH_PRIME); wr = new SSH2DataWriter(); wr.Write(_cInfo._clientVersionString); wr.Write(_cInfo._serverVersionString); wr.WriteAsString(_clientKEXINITPayload); wr.WriteAsString(_serverKEXINITPayload); wr.WriteAsString(key_and_cert); wr.Write(_e); wr.Write(f); wr.Write(_k); _hash = new SHA1CryptoServiceProvider().ComputeHash(wr.ToByteArray()); if(!VerifyHostKey(key_and_cert, signature, _hash)) return false; //Debug.WriteLine("hash="+DebugUtil.DumpByteArray(hash)); if(_sessionID==null) _sessionID = _hash; return true; } private void SendNEWKEYS() { _status = Status.WAIT_NEWKEYS; _newKeyEvent = new ManualResetEvent(false); TransmitPacket(new byte[1] {(byte)PacketType.SSH_MSG_NEWKEYS}); //establish Ciphers _tc = CipherFactory.CreateCipher(SSHProtocol.SSH2, _cInfo._algorithmForTransmittion, DeriveKey(_k, _hash, 'C', CipherFactory.GetKeySize(_cInfo._algorithmForTransmittion)), DeriveKey(_k, _hash, 'A', CipherFactory.GetBlockSize(_cInfo._algorithmForTransmittion))); _rc = CipherFactory.CreateCipher(SSHProtocol.SSH2, _cInfo._algorithmForReception, DeriveKey(_k, _hash, 'D', CipherFactory.GetKeySize(_cInfo._algorithmForReception)), DeriveKey(_k, _hash, 'B', CipherFactory.GetBlockSize(_cInfo._algorithmForReception))); //establish MACs MACAlgorithm ma = MACAlgorithm.HMACSHA1; _tm = MACFactory.CreateMAC(MACAlgorithm.HMACSHA1, DeriveKey(_k, _hash, 'E', MACFactory.GetSize(ma))); _rm = MACFactory.CreateMAC(MACAlgorithm.HMACSHA1, DeriveKey(_k, _hash, 'F', MACFactory.GetSize(ma))); _newKeyEvent.Set(); } private void ProcessNEWKEYS(SSH2Packet packet) { //confirms new key try { byte[] response = packet.Data; if(response.Length!=1 || response[0]!=(byte)PacketType.SSH_MSG_NEWKEYS) throw new SSHException("SSH_MSG_NEWKEYS failed"); _newKeyEvent.WaitOne(); _newKeyEvent.Close(); _con.LockCommunication(); _con.RefreshKeys(_sessionID, _tc, _rc, _tm, _rm); _status = Status.FINISHED; } finally { _con.UnlockCommunication(); } } private bool VerifyHostKey(byte[] K_S, byte[] signature, byte[] hash) { SSH2DataReader re1 = new SSH2DataReader(K_S); string algorithm = Encoding.ASCII.GetString(re1.ReadString()); if(algorithm!=SSH2Util.PublicKeyAlgorithmName(_cInfo._algorithmForHostKeyVerification)) throw new SSHException("Protocol Error: Host Key Algorithm Mismatch"); SSH2DataReader re2 = new SSH2DataReader(signature); algorithm = Encoding.ASCII.GetString(re2.ReadString()); if(algorithm!=SSH2Util.PublicKeyAlgorithmName(_cInfo._algorithmForHostKeyVerification)) throw new SSHException("Protocol Error: Host Key Algorithm Mismatch"); byte[] sigbody = re2.ReadString(); Debug.Assert(re2.Rest==0); if(_cInfo._algorithmForHostKeyVerification==PublicKeyAlgorithm.RSA) VerifyHostKeyByRSA(re1, sigbody, hash); else if(_cInfo._algorithmForHostKeyVerification==PublicKeyAlgorithm.DSA) VerifyHostKeyByDSS(re1, sigbody, hash); else throw new SSHException("Bad host key algorithm "+_cInfo._algorithmForHostKeyVerification); //ask the client whether he accepts the host key if(!_startedByHost && _param.KeyCheck!=null && !_param.KeyCheck(_cInfo)) return false; else return true; } private void VerifyHostKeyByRSA(SSH2DataReader pubkey, byte[] sigbody, byte[] hash) { BigInteger exp = pubkey.ReadMPInt(); BigInteger mod = pubkey.ReadMPInt(); Debug.Assert(pubkey.Rest==0); //Debug.WriteLine(exp.ToHexString()); //Debug.WriteLine(mod.ToHexString()); RSAPublicKey pk = new RSAPublicKey(exp, mod); pk.VerifyWithSHA1(sigbody, new SHA1CryptoServiceProvider().ComputeHash(hash)); _cInfo._hostkey = pk; } private void VerifyHostKeyByDSS(SSH2DataReader pubkey, byte[] sigbody, byte[] hash) { BigInteger p = pubkey.ReadMPInt(); BigInteger q = pubkey.ReadMPInt(); BigInteger g = pubkey.ReadMPInt(); BigInteger y = pubkey.ReadMPInt(); Debug.Assert(pubkey.Rest==0); //Debug.WriteLine(p.ToHexString()); //Debug.WriteLine(q.ToHexString()); //Debug.WriteLine(g.ToHexString()); //Debug.WriteLine(y.ToHexString()); DSAPublicKey pk = new DSAPublicKey(p,g,q,y); pk.Verify(sigbody, new SHA1CryptoServiceProvider().ComputeHash(hash)); _cInfo._hostkey = pk; } private byte[] DeriveKey(BigInteger key, byte[] hash, char ch, int length) { byte[] result = new byte[length]; SSH2DataWriter wr = new SSH2DataWriter(); wr.Write(key); wr.Write(hash); wr.Write((byte)ch); wr.Write(_sessionID); byte[] h1 = new SHA1CryptoServiceProvider().ComputeHash(wr.ToByteArray()); if(h1.Length >= length) { Array.Copy(h1, 0, result, 0, length); return result; } else { wr = new SSH2DataWriter(); wr.Write(key); wr.Write(_sessionID); wr.Write(h1); byte[] h2 = new SHA1CryptoServiceProvider().ComputeHash(wr.ToByteArray()); if(h1.Length+h2.Length >= length) { Array.Copy(h1, 0, result, 0, h1.Length); Array.Copy(h2, 0, result, h1.Length, length-h1.Length); return result; } else throw new SSHException("necessary key length is too big"); //long key is not supported } } private static void CheckAlgorithmSupport(string title, string data, string algorithm_name) { string[] t = data.Split(','); foreach(string s in t) { if(s==algorithm_name) return; //found! } throw new SSHException("Server does not support "+algorithm_name+" for "+title); } private PublicKeyAlgorithm DecideHostKeyAlgorithm(string data) { string[] t = data.Split(','); foreach(PublicKeyAlgorithm a in _param.PreferableHostKeyAlgorithms) { if(SSHUtil.ContainsString(t, SSH2Util.PublicKeyAlgorithmName(a))) { return a; } } throw new SSHException("The negotiation of host key verification algorithm is failed"); } private CipherAlgorithm DecideCipherAlgorithm(string data) { string[] t = data.Split(','); foreach(CipherAlgorithm a in _param.PreferableCipherAlgorithms) { if(SSHUtil.ContainsString(t, CipherFactory.AlgorithmToSSH2Name(a))) { return a; } } throw new SSHException("The negotiation of encryption algorithm is failed"); } private string FormatHostKeyAlgorithmDescription() { StringBuilder b = new StringBuilder(); if(_param.PreferableHostKeyAlgorithms.Length==0) throw new SSHException("HostKeyAlgorithm is not set"); b.Append(SSH2Util.PublicKeyAlgorithmName(_param.PreferableHostKeyAlgorithms[0])); for(int i=1; i<_param.PreferableHostKeyAlgorithms.Length; i++) { b.Append(','); b.Append(SSH2Util.PublicKeyAlgorithmName(_param.PreferableHostKeyAlgorithms[i])); } return b.ToString(); } private string FormatCipherAlgorithmDescription() { StringBuilder b = new StringBuilder(); if(_param.PreferableCipherAlgorithms.Length==0) throw new SSHException("CipherAlgorithm is not set"); b.Append(CipherFactory.AlgorithmToSSH2Name(_param.PreferableCipherAlgorithms[0])); for(int i=1; i<_param.PreferableCipherAlgorithms.Length; i++) { b.Append(','); b.Append(CipherFactory.AlgorithmToSSH2Name(_param.PreferableCipherAlgorithms[i])); } return b.ToString(); } /* * the seed of diffie-hellman KX defined in the spec of SSH2 */ private static BigInteger _dh_prime = null; private static BigInteger DH_PRIME { get { if(_dh_prime==null) { StringBuilder sb = new StringBuilder(); sb.Append("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"); sb.Append("29024E088A67CC74020BBEA63B139B22514A08798E3404DD"); sb.Append("EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"); sb.Append("E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"); sb.Append("EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381"); sb.Append("FFFFFFFFFFFFFFFF"); _dh_prime = new BigInteger(sb.ToString(), 16); } return _dh_prime; } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvc = Google.Ads.GoogleAds.V9.Common; using gagve = Google.Ads.GoogleAds.V9.Enums; using gagvr = Google.Ads.GoogleAds.V9.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V9.Services; namespace Google.Ads.GoogleAds.Tests.V9.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedExtensionFeedItemServiceClientTest { [Category("Autogenerated")][Test] public void GetExtensionFeedItemRequestObject() { moq::Mock<ExtensionFeedItemService.ExtensionFeedItemServiceClient> mockGrpcClient = new moq::Mock<ExtensionFeedItemService.ExtensionFeedItemServiceClient>(moq::MockBehavior.Strict); GetExtensionFeedItemRequest request = new GetExtensionFeedItemRequest { ResourceNameAsExtensionFeedItemName = gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }; gagvr::ExtensionFeedItem expectedResponse = new gagvr::ExtensionFeedItem { ResourceNameAsExtensionFeedItemName = gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), SitelinkFeedItem = new gagvc::SitelinkFeedItem(), StructuredSnippetFeedItem = new gagvc::StructuredSnippetFeedItem(), Status = gagve::FeedItemStatusEnum.Types.FeedItemStatus.Enabled, AppFeedItem = new gagvc::AppFeedItem(), CallFeedItem = new gagvc::CallFeedItem(), CalloutFeedItem = new gagvc::CalloutFeedItem(), TextMessageFeedItem = new gagvc::TextMessageFeedItem(), PriceFeedItem = new gagvc::PriceFeedItem(), PromotionFeedItem = new gagvc::PromotionFeedItem(), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, LocationFeedItem = new gagvc::LocationFeedItem(), AffiliateLocationFeedItem = new gagvc::AffiliateLocationFeedItem(), AdSchedules = { new gagvc::AdScheduleInfo(), }, Device = gagve::FeedItemTargetDeviceEnum.Types.FeedItemTargetDevice.Mobile, TargetedKeyword = new gagvc::KeywordInfo(), HotelCalloutFeedItem = new gagvc::HotelCalloutFeedItem(), Id = -6774108720365892680L, StartDateTime = "start_date_timeea924cb1", EndDateTime = "end_date_timea95363f3", TargetedCampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), TargetedAdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), TargetedGeoTargetConstantAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), ImageFeedItem = new gagvc::ImageFeedItem(), }; mockGrpcClient.Setup(x => x.GetExtensionFeedItem(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ExtensionFeedItemServiceClient client = new ExtensionFeedItemServiceClientImpl(mockGrpcClient.Object, null); gagvr::ExtensionFeedItem response = client.GetExtensionFeedItem(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetExtensionFeedItemRequestObjectAsync() { moq::Mock<ExtensionFeedItemService.ExtensionFeedItemServiceClient> mockGrpcClient = new moq::Mock<ExtensionFeedItemService.ExtensionFeedItemServiceClient>(moq::MockBehavior.Strict); GetExtensionFeedItemRequest request = new GetExtensionFeedItemRequest { ResourceNameAsExtensionFeedItemName = gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }; gagvr::ExtensionFeedItem expectedResponse = new gagvr::ExtensionFeedItem { ResourceNameAsExtensionFeedItemName = gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), SitelinkFeedItem = new gagvc::SitelinkFeedItem(), StructuredSnippetFeedItem = new gagvc::StructuredSnippetFeedItem(), Status = gagve::FeedItemStatusEnum.Types.FeedItemStatus.Enabled, AppFeedItem = new gagvc::AppFeedItem(), CallFeedItem = new gagvc::CallFeedItem(), CalloutFeedItem = new gagvc::CalloutFeedItem(), TextMessageFeedItem = new gagvc::TextMessageFeedItem(), PriceFeedItem = new gagvc::PriceFeedItem(), PromotionFeedItem = new gagvc::PromotionFeedItem(), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, LocationFeedItem = new gagvc::LocationFeedItem(), AffiliateLocationFeedItem = new gagvc::AffiliateLocationFeedItem(), AdSchedules = { new gagvc::AdScheduleInfo(), }, Device = gagve::FeedItemTargetDeviceEnum.Types.FeedItemTargetDevice.Mobile, TargetedKeyword = new gagvc::KeywordInfo(), HotelCalloutFeedItem = new gagvc::HotelCalloutFeedItem(), Id = -6774108720365892680L, StartDateTime = "start_date_timeea924cb1", EndDateTime = "end_date_timea95363f3", TargetedCampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), TargetedAdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), TargetedGeoTargetConstantAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), ImageFeedItem = new gagvc::ImageFeedItem(), }; mockGrpcClient.Setup(x => x.GetExtensionFeedItemAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::ExtensionFeedItem>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ExtensionFeedItemServiceClient client = new ExtensionFeedItemServiceClientImpl(mockGrpcClient.Object, null); gagvr::ExtensionFeedItem responseCallSettings = await client.GetExtensionFeedItemAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::ExtensionFeedItem responseCancellationToken = await client.GetExtensionFeedItemAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetExtensionFeedItem() { moq::Mock<ExtensionFeedItemService.ExtensionFeedItemServiceClient> mockGrpcClient = new moq::Mock<ExtensionFeedItemService.ExtensionFeedItemServiceClient>(moq::MockBehavior.Strict); GetExtensionFeedItemRequest request = new GetExtensionFeedItemRequest { ResourceNameAsExtensionFeedItemName = gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }; gagvr::ExtensionFeedItem expectedResponse = new gagvr::ExtensionFeedItem { ResourceNameAsExtensionFeedItemName = gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), SitelinkFeedItem = new gagvc::SitelinkFeedItem(), StructuredSnippetFeedItem = new gagvc::StructuredSnippetFeedItem(), Status = gagve::FeedItemStatusEnum.Types.FeedItemStatus.Enabled, AppFeedItem = new gagvc::AppFeedItem(), CallFeedItem = new gagvc::CallFeedItem(), CalloutFeedItem = new gagvc::CalloutFeedItem(), TextMessageFeedItem = new gagvc::TextMessageFeedItem(), PriceFeedItem = new gagvc::PriceFeedItem(), PromotionFeedItem = new gagvc::PromotionFeedItem(), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, LocationFeedItem = new gagvc::LocationFeedItem(), AffiliateLocationFeedItem = new gagvc::AffiliateLocationFeedItem(), AdSchedules = { new gagvc::AdScheduleInfo(), }, Device = gagve::FeedItemTargetDeviceEnum.Types.FeedItemTargetDevice.Mobile, TargetedKeyword = new gagvc::KeywordInfo(), HotelCalloutFeedItem = new gagvc::HotelCalloutFeedItem(), Id = -6774108720365892680L, StartDateTime = "start_date_timeea924cb1", EndDateTime = "end_date_timea95363f3", TargetedCampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), TargetedAdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), TargetedGeoTargetConstantAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), ImageFeedItem = new gagvc::ImageFeedItem(), }; mockGrpcClient.Setup(x => x.GetExtensionFeedItem(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ExtensionFeedItemServiceClient client = new ExtensionFeedItemServiceClientImpl(mockGrpcClient.Object, null); gagvr::ExtensionFeedItem response = client.GetExtensionFeedItem(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetExtensionFeedItemAsync() { moq::Mock<ExtensionFeedItemService.ExtensionFeedItemServiceClient> mockGrpcClient = new moq::Mock<ExtensionFeedItemService.ExtensionFeedItemServiceClient>(moq::MockBehavior.Strict); GetExtensionFeedItemRequest request = new GetExtensionFeedItemRequest { ResourceNameAsExtensionFeedItemName = gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }; gagvr::ExtensionFeedItem expectedResponse = new gagvr::ExtensionFeedItem { ResourceNameAsExtensionFeedItemName = gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), SitelinkFeedItem = new gagvc::SitelinkFeedItem(), StructuredSnippetFeedItem = new gagvc::StructuredSnippetFeedItem(), Status = gagve::FeedItemStatusEnum.Types.FeedItemStatus.Enabled, AppFeedItem = new gagvc::AppFeedItem(), CallFeedItem = new gagvc::CallFeedItem(), CalloutFeedItem = new gagvc::CalloutFeedItem(), TextMessageFeedItem = new gagvc::TextMessageFeedItem(), PriceFeedItem = new gagvc::PriceFeedItem(), PromotionFeedItem = new gagvc::PromotionFeedItem(), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, LocationFeedItem = new gagvc::LocationFeedItem(), AffiliateLocationFeedItem = new gagvc::AffiliateLocationFeedItem(), AdSchedules = { new gagvc::AdScheduleInfo(), }, Device = gagve::FeedItemTargetDeviceEnum.Types.FeedItemTargetDevice.Mobile, TargetedKeyword = new gagvc::KeywordInfo(), HotelCalloutFeedItem = new gagvc::HotelCalloutFeedItem(), Id = -6774108720365892680L, StartDateTime = "start_date_timeea924cb1", EndDateTime = "end_date_timea95363f3", TargetedCampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), TargetedAdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), TargetedGeoTargetConstantAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), ImageFeedItem = new gagvc::ImageFeedItem(), }; mockGrpcClient.Setup(x => x.GetExtensionFeedItemAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::ExtensionFeedItem>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ExtensionFeedItemServiceClient client = new ExtensionFeedItemServiceClientImpl(mockGrpcClient.Object, null); gagvr::ExtensionFeedItem responseCallSettings = await client.GetExtensionFeedItemAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::ExtensionFeedItem responseCancellationToken = await client.GetExtensionFeedItemAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetExtensionFeedItemResourceNames() { moq::Mock<ExtensionFeedItemService.ExtensionFeedItemServiceClient> mockGrpcClient = new moq::Mock<ExtensionFeedItemService.ExtensionFeedItemServiceClient>(moq::MockBehavior.Strict); GetExtensionFeedItemRequest request = new GetExtensionFeedItemRequest { ResourceNameAsExtensionFeedItemName = gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }; gagvr::ExtensionFeedItem expectedResponse = new gagvr::ExtensionFeedItem { ResourceNameAsExtensionFeedItemName = gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), SitelinkFeedItem = new gagvc::SitelinkFeedItem(), StructuredSnippetFeedItem = new gagvc::StructuredSnippetFeedItem(), Status = gagve::FeedItemStatusEnum.Types.FeedItemStatus.Enabled, AppFeedItem = new gagvc::AppFeedItem(), CallFeedItem = new gagvc::CallFeedItem(), CalloutFeedItem = new gagvc::CalloutFeedItem(), TextMessageFeedItem = new gagvc::TextMessageFeedItem(), PriceFeedItem = new gagvc::PriceFeedItem(), PromotionFeedItem = new gagvc::PromotionFeedItem(), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, LocationFeedItem = new gagvc::LocationFeedItem(), AffiliateLocationFeedItem = new gagvc::AffiliateLocationFeedItem(), AdSchedules = { new gagvc::AdScheduleInfo(), }, Device = gagve::FeedItemTargetDeviceEnum.Types.FeedItemTargetDevice.Mobile, TargetedKeyword = new gagvc::KeywordInfo(), HotelCalloutFeedItem = new gagvc::HotelCalloutFeedItem(), Id = -6774108720365892680L, StartDateTime = "start_date_timeea924cb1", EndDateTime = "end_date_timea95363f3", TargetedCampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), TargetedAdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), TargetedGeoTargetConstantAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), ImageFeedItem = new gagvc::ImageFeedItem(), }; mockGrpcClient.Setup(x => x.GetExtensionFeedItem(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ExtensionFeedItemServiceClient client = new ExtensionFeedItemServiceClientImpl(mockGrpcClient.Object, null); gagvr::ExtensionFeedItem response = client.GetExtensionFeedItem(request.ResourceNameAsExtensionFeedItemName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetExtensionFeedItemResourceNamesAsync() { moq::Mock<ExtensionFeedItemService.ExtensionFeedItemServiceClient> mockGrpcClient = new moq::Mock<ExtensionFeedItemService.ExtensionFeedItemServiceClient>(moq::MockBehavior.Strict); GetExtensionFeedItemRequest request = new GetExtensionFeedItemRequest { ResourceNameAsExtensionFeedItemName = gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }; gagvr::ExtensionFeedItem expectedResponse = new gagvr::ExtensionFeedItem { ResourceNameAsExtensionFeedItemName = gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), SitelinkFeedItem = new gagvc::SitelinkFeedItem(), StructuredSnippetFeedItem = new gagvc::StructuredSnippetFeedItem(), Status = gagve::FeedItemStatusEnum.Types.FeedItemStatus.Enabled, AppFeedItem = new gagvc::AppFeedItem(), CallFeedItem = new gagvc::CallFeedItem(), CalloutFeedItem = new gagvc::CalloutFeedItem(), TextMessageFeedItem = new gagvc::TextMessageFeedItem(), PriceFeedItem = new gagvc::PriceFeedItem(), PromotionFeedItem = new gagvc::PromotionFeedItem(), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, LocationFeedItem = new gagvc::LocationFeedItem(), AffiliateLocationFeedItem = new gagvc::AffiliateLocationFeedItem(), AdSchedules = { new gagvc::AdScheduleInfo(), }, Device = gagve::FeedItemTargetDeviceEnum.Types.FeedItemTargetDevice.Mobile, TargetedKeyword = new gagvc::KeywordInfo(), HotelCalloutFeedItem = new gagvc::HotelCalloutFeedItem(), Id = -6774108720365892680L, StartDateTime = "start_date_timeea924cb1", EndDateTime = "end_date_timea95363f3", TargetedCampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), TargetedAdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), TargetedGeoTargetConstantAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), ImageFeedItem = new gagvc::ImageFeedItem(), }; mockGrpcClient.Setup(x => x.GetExtensionFeedItemAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::ExtensionFeedItem>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ExtensionFeedItemServiceClient client = new ExtensionFeedItemServiceClientImpl(mockGrpcClient.Object, null); gagvr::ExtensionFeedItem responseCallSettings = await client.GetExtensionFeedItemAsync(request.ResourceNameAsExtensionFeedItemName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::ExtensionFeedItem responseCancellationToken = await client.GetExtensionFeedItemAsync(request.ResourceNameAsExtensionFeedItemName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateExtensionFeedItemsRequestObject() { moq::Mock<ExtensionFeedItemService.ExtensionFeedItemServiceClient> mockGrpcClient = new moq::Mock<ExtensionFeedItemService.ExtensionFeedItemServiceClient>(moq::MockBehavior.Strict); MutateExtensionFeedItemsRequest request = new MutateExtensionFeedItemsRequest { CustomerId = "customer_id3b3724cb", Operations = { new ExtensionFeedItemOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateExtensionFeedItemsResponse expectedResponse = new MutateExtensionFeedItemsResponse { Results = { new MutateExtensionFeedItemResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateExtensionFeedItems(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ExtensionFeedItemServiceClient client = new ExtensionFeedItemServiceClientImpl(mockGrpcClient.Object, null); MutateExtensionFeedItemsResponse response = client.MutateExtensionFeedItems(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateExtensionFeedItemsRequestObjectAsync() { moq::Mock<ExtensionFeedItemService.ExtensionFeedItemServiceClient> mockGrpcClient = new moq::Mock<ExtensionFeedItemService.ExtensionFeedItemServiceClient>(moq::MockBehavior.Strict); MutateExtensionFeedItemsRequest request = new MutateExtensionFeedItemsRequest { CustomerId = "customer_id3b3724cb", Operations = { new ExtensionFeedItemOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateExtensionFeedItemsResponse expectedResponse = new MutateExtensionFeedItemsResponse { Results = { new MutateExtensionFeedItemResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateExtensionFeedItemsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateExtensionFeedItemsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ExtensionFeedItemServiceClient client = new ExtensionFeedItemServiceClientImpl(mockGrpcClient.Object, null); MutateExtensionFeedItemsResponse responseCallSettings = await client.MutateExtensionFeedItemsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateExtensionFeedItemsResponse responseCancellationToken = await client.MutateExtensionFeedItemsAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateExtensionFeedItems() { moq::Mock<ExtensionFeedItemService.ExtensionFeedItemServiceClient> mockGrpcClient = new moq::Mock<ExtensionFeedItemService.ExtensionFeedItemServiceClient>(moq::MockBehavior.Strict); MutateExtensionFeedItemsRequest request = new MutateExtensionFeedItemsRequest { CustomerId = "customer_id3b3724cb", Operations = { new ExtensionFeedItemOperation(), }, }; MutateExtensionFeedItemsResponse expectedResponse = new MutateExtensionFeedItemsResponse { Results = { new MutateExtensionFeedItemResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateExtensionFeedItems(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ExtensionFeedItemServiceClient client = new ExtensionFeedItemServiceClientImpl(mockGrpcClient.Object, null); MutateExtensionFeedItemsResponse response = client.MutateExtensionFeedItems(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateExtensionFeedItemsAsync() { moq::Mock<ExtensionFeedItemService.ExtensionFeedItemServiceClient> mockGrpcClient = new moq::Mock<ExtensionFeedItemService.ExtensionFeedItemServiceClient>(moq::MockBehavior.Strict); MutateExtensionFeedItemsRequest request = new MutateExtensionFeedItemsRequest { CustomerId = "customer_id3b3724cb", Operations = { new ExtensionFeedItemOperation(), }, }; MutateExtensionFeedItemsResponse expectedResponse = new MutateExtensionFeedItemsResponse { Results = { new MutateExtensionFeedItemResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateExtensionFeedItemsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateExtensionFeedItemsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ExtensionFeedItemServiceClient client = new ExtensionFeedItemServiceClientImpl(mockGrpcClient.Object, null); MutateExtensionFeedItemsResponse responseCallSettings = await client.MutateExtensionFeedItemsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateExtensionFeedItemsResponse responseCancellationToken = await client.MutateExtensionFeedItemsAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using JetBrains.Annotations; using osu.Framework.Bindables; using osu.Framework.Extensions.TypeExtensions; using osu.Framework.Graphics; using osu.Framework.Localisation; using osu.Game.Graphics.UserInterface; using osu.Game.Overlays.Settings; namespace osu.Game.Configuration { /// <summary> /// An attribute to mark a bindable as being exposed to the user via settings controls. /// Can be used in conjunction with <see cref="SettingSourceExtensions.CreateSettingsControls"/> to automatically create UI controls. /// </summary> /// <remarks> /// All controls with <see cref="OrderPosition"/> set will be placed first in ascending order. /// All controls with no <see cref="OrderPosition"/> will come afterward in default order. /// </remarks> [MeansImplicitUse] [AttributeUsage(AttributeTargets.Property)] public class SettingSourceAttribute : Attribute, IComparable<SettingSourceAttribute> { public LocalisableString Label { get; } public LocalisableString Description { get; } public int? OrderPosition { get; } /// <summary> /// The type of the settings control which handles this setting source. /// </summary> /// <remarks> /// Must be a type deriving <see cref="SettingsItem{T}"/> with a public parameterless constructor. /// </remarks> public Type? SettingControlType { get; set; } public SettingSourceAttribute(string? label, string? description = null) { Label = label ?? string.Empty; Description = description ?? string.Empty; } public SettingSourceAttribute(string label, string description, int orderPosition) : this(label, description) { OrderPosition = orderPosition; } public int CompareTo(SettingSourceAttribute other) { if (OrderPosition == other.OrderPosition) return 0; // unordered items come last (are greater than any ordered items). if (OrderPosition == null) return 1; if (other.OrderPosition == null) return -1; // ordered items are sorted by the order value. return OrderPosition.Value.CompareTo(other.OrderPosition); } } public static class SettingSourceExtensions { public static IEnumerable<Drawable> CreateSettingsControls(this object obj) { foreach (var (attr, property) in obj.GetOrderedSettingsSourceProperties()) { object value = property.GetValue(obj); if (attr.SettingControlType != null) { var controlType = attr.SettingControlType; if (controlType.EnumerateBaseTypes().All(t => !t.IsGenericType || t.GetGenericTypeDefinition() != typeof(SettingsItem<>))) throw new InvalidOperationException($"{nameof(SettingSourceAttribute)} had an unsupported custom control type ({controlType.ReadableName()})"); var control = (Drawable)Activator.CreateInstance(controlType); controlType.GetProperty(nameof(SettingsItem<object>.LabelText))?.SetValue(control, attr.Label); controlType.GetProperty(nameof(SettingsItem<object>.TooltipText))?.SetValue(control, attr.Description); controlType.GetProperty(nameof(SettingsItem<object>.Current))?.SetValue(control, value); yield return control; continue; } switch (value) { case BindableNumber<float> bNumber: yield return new SettingsSlider<float> { LabelText = attr.Label, TooltipText = attr.Description, Current = bNumber, KeyboardStep = 0.1f, }; break; case BindableNumber<double> bNumber: yield return new SettingsSlider<double> { LabelText = attr.Label, TooltipText = attr.Description, Current = bNumber, KeyboardStep = 0.1f, }; break; case BindableNumber<int> bNumber: yield return new SettingsSlider<int> { LabelText = attr.Label, TooltipText = attr.Description, Current = bNumber }; break; case Bindable<bool> bBool: yield return new SettingsCheckbox { LabelText = attr.Label, TooltipText = attr.Description, Current = bBool }; break; case Bindable<string> bString: yield return new SettingsTextBox { LabelText = attr.Label, TooltipText = attr.Description, Current = bString }; break; case IBindable bindable: var dropdownType = typeof(ModSettingsEnumDropdown<>).MakeGenericType(bindable.GetType().GetGenericArguments()[0]); var dropdown = (Drawable)Activator.CreateInstance(dropdownType); dropdownType.GetProperty(nameof(SettingsDropdown<object>.LabelText))?.SetValue(dropdown, attr.Label); dropdownType.GetProperty(nameof(SettingsDropdown<object>.TooltipText))?.SetValue(dropdown, attr.Description); dropdownType.GetProperty(nameof(SettingsDropdown<object>.Current))?.SetValue(dropdown, bindable); yield return dropdown; break; default: throw new InvalidOperationException($"{nameof(SettingSourceAttribute)} was attached to an unsupported type ({value})"); } } } private static readonly ConcurrentDictionary<Type, (SettingSourceAttribute, PropertyInfo)[]> property_info_cache = new ConcurrentDictionary<Type, (SettingSourceAttribute, PropertyInfo)[]>(); public static IEnumerable<(SettingSourceAttribute, PropertyInfo)> GetSettingsSourceProperties(this object obj) { var type = obj.GetType(); if (!property_info_cache.TryGetValue(type, out var properties)) property_info_cache[type] = properties = getSettingsSourceProperties(type).ToArray(); return properties; } private static IEnumerable<(SettingSourceAttribute, PropertyInfo)> getSettingsSourceProperties(Type type) { foreach (var property in type.GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance)) { var attr = property.GetCustomAttribute<SettingSourceAttribute>(true); if (attr == null) continue; yield return (attr, property); } } public static ICollection<(SettingSourceAttribute, PropertyInfo)> GetOrderedSettingsSourceProperties(this object obj) => obj.GetSettingsSourceProperties() .OrderBy(attr => attr.Item1) .ToArray(); private class ModSettingsEnumDropdown<T> : SettingsEnumDropdown<T> where T : struct, Enum { protected override OsuDropdown<T> CreateDropdown() => new ModDropdownControl(); private class ModDropdownControl : DropdownControl { // Set menu's max height low enough to workaround nested scroll issues (see https://github.com/ppy/osu-framework/issues/4536). protected override DropdownMenu CreateMenu() => base.CreateMenu().With(m => m.MaxHeight = 100); } } } }
using System; using System.Diagnostics; using HANDLE = System.IntPtr; using System.Text; namespace Core { public partial class Main { #if !APICORE const int APICORE = 1; // Disable the API redefinition in sqlite3ext.h #endif #region OMIT_LOAD_EXTENSION #if !OMIT_LOAD_EXTENSION #if !ENABLE_COLUMN_METADATA #endif #if OMIT_AUTHORIZATION #endif #if OMIT_UTF16 static string sqlite3_errmsg16( sqlite3 db ) { return ""; } static void sqlite3_result_text16( sqlite3_context pCtx, string z, int n, dxDel xDel ) { } #endif #if OMIT_COMPLETE #endif #if OMIT_DECLTYPE #endif #if OMIT_PROGRESS_CALLBACK static void sqlite3_progress_handler(sqlite3 db, int nOps, dxProgress xProgress, object pArg){} #endif #if OMIT_VIRTUALTABLE #endif #if OMIT_SHARED_CACHE #endif #if OMIT_TRACE #endif #if OMIT_GET_TABLE public static int sqlite3_get_table(sqlite3 db, string zSql, ref string[] pazResult, ref int pnRow, ref int pnColumn, ref string pzErrmsg) { return 0; } #endif #if OMIT_INCRBLOB #endif public class core_api_routines { public Context context_db_handle; } static core_api_routines g_apis = new core_api_routines(); public static RC LoadExtension_(Context ctx, string fileName, string procName, ref string errMsgOut) { if (errMsgOut != null) errMsgOut = null; // Ticket #1863. To avoid a creating security problems for older applications that relink against newer versions of SQLite, the // ability to run load_extension is turned off by default. One must call core_enable_load_extension() to turn on extension // loading. Otherwise you get the following error. if ((ctx.Flags & Context.FLAG.LoadExtension) == 0) { errMsgOut = C._mprintf("not authorized"); return RC.ERROR; } if (procName == null) procName = "sqlite3_extension_init"; VSystem vfs = ctx.Vfs; HANDLE handle = (HANDLE)vfs.DlOpen(fileName); StringBuilder errmsg = new StringBuilder(100); int msgLength = 300; if (handle == IntPtr.Zero) { errMsgOut = string.Empty; C.__snprintf(errmsg, msgLength, "unable to open shared library [%s]", fileName); vfs.DlError(msgLength - 1, errmsg.ToString()); return RC.ERROR; } Func<Context, StringBuilder, core_api_routines, RC> init = (Func<Context, StringBuilder, core_api_routines, RC>)vfs.DlSym(handle, procName); Debugger.Break(); if (init == null) { msgLength += procName.Length; C.__snprintf(errmsg, msgLength, "no entry point [%s] in shared library [%s]", procName, fileName); vfs.DlError(msgLength - 1, errMsgOut = errmsg.ToString()); vfs.DlClose(handle); return RC.ERROR; } else if (init(ctx, errmsg, g_apis) != 0) { errMsgOut = C._mprintf("error during initialization: %s", errmsg.ToString()); C._tagfree(ctx, ref errmsg); vfs.DlClose(handle); return RC.ERROR; } // Append the new shared library handle to the db.aExtension array. object[] handles = new object[ctx.Extensions.length + 1]; if (handles == null) return RC.NOMEM; if (ctx.Extensions.length > 0) Array.Copy(ctx.Extensions.data, handles, ctx.Extensions.length); C._tagfree(ctx, ref ctx.Extensions.data); ctx.Extensions.data = handles; ctx.Extensions[ctx.Extensions.length++] = handle; return RC.OK; } public static RC LoadExtension(Context ctx, string fileName, string procName, ref string errMsg) { MutexEx.Enter(ctx.Mutex); RC rc = LoadExtension_(ctx, fileName, procName, ref errMsg); rc = ApiExit(ctx, rc); MutexEx.Leave(ctx.Mutex); return rc; } public static void CloseExtensions(Context ctx) { Debug.Assert(MutexEx.Held(ctx.Mutex)); for (int i = 0; i < ctx.Extensions.length; i++) ctx.Vfs.DlClose((HANDLE)ctx.Extensions[i]); C._tagfree(ctx, ref ctx.Extensions.data); } public static RC EnableLoadExtension(Context ctx, bool onoff) { MutexEx.Enter(ctx.Mutex); if (onoff) ctx.Flags |= Context.FLAG.LoadExtension; else ctx.Flags &= ~Context.FLAG.LoadExtension; MutexEx.Leave(ctx.Mutex); return RC.OK; } #else const core_api_routines g_apis = null; #endif #endregion public class AutoExtList_t { public int ExtsLength = 0; // Number of entries in aExt[] public Func<Context, string, core_api_routines, RC>[] Exts = null; // Pointers to the extension init functions public AutoExtList_t(int extsLength, Func<Context, string, core_api_routines, RC>[] exts) { ExtsLength = extsLength; Exts = exts; } } static AutoExtList_t g_autoext = new AutoExtList_t(0, null); static RC AutoExtension(Func<Context, string, core_api_routines, RC> init) { RC rc = RC.OK; #if !OMIT_AUTOINIT rc = Initialize(); if (rc != 0) return rc; else #endif { #if THREADSAFE MutexEx mutex = MutexEx.Alloc(MutexEx.MUTEX.STATIC_MASTER); #endif MutexEx.Enter(mutex); int i; for (i = 0; i < g_autoext.ExtsLength; i++) if (g_autoext.Exts[i] == init) break; if (i == g_autoext.ExtsLength) { Array.Resize(ref g_autoext.Exts, g_autoext.ExtsLength + 1); g_autoext.Exts[g_autoext.ExtsLength] = init; g_autoext.ExtsLength++; } MutexEx.Leave(mutex); Debug.Assert((rc & (RC)0xff) == rc); return rc; } } public static void ResetAutoExtension() { #if !OMIT_AUTOINIT if (Initialize() == RC.OK) #endif { #if THREADSAFE MutexEx mutex = MutexEx.Alloc(MutexEx.MUTEX.STATIC_MASTER); #endif MutexEx.Enter(mutex); g_autoext.Exts = null; g_autoext.ExtsLength = 0; MutexEx.Leave(mutex); } } public static void AutoLoadExtensions(Context ctx) { if (g_autoext.ExtsLength == 0) return; // Common case: early out without every having to acquire a mutex bool go = true; for (int i = 0; go; i++) { string errmsg = null; #if THREADSAFE MutexEx mutex = MutexEx.Alloc(MutexEx.MUTEX.STATIC_MASTER); #endif MutexEx.Enter(mutex); Func<Context, string, core_api_routines, RC> init; if (i >= g_autoext.ExtsLength) { init = null; go = false; } else init = g_autoext.Exts[i]; MutexEx.Leave(mutex); errmsg = null; RC rc; if (init != null && (rc = init(ctx, errmsg, g_apis)) != 0) { Error(ctx, rc, "automatic extension loading failed: %s", errmsg); go = false; } C._tagfree(ctx, ref errmsg); } } } }
using System; using System.ComponentModel; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Threading; using System.Threading.Tasks; using Avalonia.Data; using Avalonia.Logging; using Avalonia.Platform; using Avalonia.Threading; using Avalonia.UnitTests; using Microsoft.Reactive.Testing; using Moq; using Xunit; namespace Avalonia.Base.UnitTests { public class AvaloniaObjectTests_Binding { [Fact] public void Bind_Sets_Current_Value() { var target = new Class1(); var source = new Class1(); var property = Class1.FooProperty; source.SetValue(property, "initial"); target.Bind(property, source.GetObservable(property)); Assert.Equal("initial", target.GetValue(property)); } [Fact] public void Bind_Raises_PropertyChanged() { var target = new Class1(); var source = new Subject<BindingValue<string>>(); bool raised = false; target.PropertyChanged += (s, e) => raised = e.Property == Class1.FooProperty && (string)e.OldValue == "foodefault" && (string)e.NewValue == "newvalue" && e.Priority == BindingPriority.LocalValue; target.Bind(Class1.FooProperty, source); source.OnNext("newvalue"); Assert.True(raised); } [Fact] public void PropertyChanged_Not_Raised_When_Value_Unchanged() { var target = new Class1(); var source = new Subject<BindingValue<string>>(); var raised = 0; target.PropertyChanged += (s, e) => ++raised; target.Bind(Class1.FooProperty, source); source.OnNext("newvalue"); source.OnNext("newvalue"); Assert.Equal(1, raised); } [Fact] public void Setting_LocalValue_Overrides_Binding_Until_Binding_Produces_Next_Value() { var target = new Class1(); var source = new Subject<string>(); var property = Class1.FooProperty; target.Bind(property, source); source.OnNext("foo"); Assert.Equal("foo", target.GetValue(property)); target.SetValue(property, "bar"); Assert.Equal("bar", target.GetValue(property)); source.OnNext("baz"); Assert.Equal("baz", target.GetValue(property)); } [Fact] public void Completing_LocalValue_Binding_Reverts_To_Default_Value_Even_When_Local_Value_Set_Earlier() { var target = new Class1(); var source = new Subject<string>(); var property = Class1.FooProperty; target.Bind(property, source); source.OnNext("foo"); target.SetValue(property, "bar"); source.OnNext("baz"); source.OnCompleted(); Assert.Equal("foodefault", target.GetValue(property)); } [Fact] public void Completing_LocalValue_Binding_Should_Not_Revert_To_Set_LocalValue() { var target = new Class1(); var source = new BehaviorSubject<string>("bar"); target.SetValue(Class1.FooProperty, "foo"); var sub = target.Bind(Class1.FooProperty, source); Assert.Equal("bar", target.GetValue(Class1.FooProperty)); sub.Dispose(); Assert.Equal("foodefault", target.GetValue(Class1.FooProperty)); } [Fact] public void Completing_Animation_Binding_Reverts_To_Set_LocalValue() { var target = new Class1(); var source = new Subject<string>(); var property = Class1.FooProperty; target.SetValue(property, "foo"); target.Bind(property, source, BindingPriority.Animation); source.OnNext("bar"); source.OnCompleted(); Assert.Equal("foo", target.GetValue(property)); } [Fact] public void Completing_LocalValue_Binding_Raises_PropertyChanged() { var target = new Class1(); var source = new BehaviorSubject<BindingValue<string>>("foo"); var property = Class1.FooProperty; var raised = 0; target.Bind(property, source); Assert.Equal("foo", target.GetValue(property)); target.PropertyChanged += (s, e) => { Assert.Equal(BindingPriority.Unset, e.Priority); Assert.Equal(property, e.Property); Assert.Equal("foo", e.OldValue as string); Assert.Equal("foodefault", e.NewValue as string); ++raised; }; source.OnCompleted(); Assert.Equal("foodefault", target.GetValue(property)); Assert.Equal(1, raised); } [Fact] public void Completing_Style_Binding_Raises_PropertyChanged() { var target = new Class1(); var source = new BehaviorSubject<BindingValue<string>>("foo"); var property = Class1.FooProperty; var raised = 0; target.Bind(property, source, BindingPriority.Style); Assert.Equal("foo", target.GetValue(property)); target.PropertyChanged += (s, e) => { Assert.Equal(BindingPriority.Unset, e.Priority); Assert.Equal(property, e.Property); Assert.Equal("foo", e.OldValue as string); Assert.Equal("foodefault", e.NewValue as string); ++raised; }; source.OnCompleted(); Assert.Equal("foodefault", target.GetValue(property)); Assert.Equal(1, raised); } [Fact] public void Completing_LocalValue_Binding_With_Style_Binding_Raises_PropertyChanged() { var target = new Class1(); var source = new BehaviorSubject<BindingValue<string>>("foo"); var property = Class1.FooProperty; var raised = 0; target.Bind(property, new BehaviorSubject<string>("bar"), BindingPriority.Style); target.Bind(property, source); Assert.Equal("foo", target.GetValue(property)); target.PropertyChanged += (s, e) => { Assert.Equal(BindingPriority.Style, e.Priority); Assert.Equal(property, e.Property); Assert.Equal("foo", e.OldValue as string); Assert.Equal("bar", e.NewValue as string); ++raised; }; source.OnCompleted(); Assert.Equal("bar", target.GetValue(property)); Assert.Equal(1, raised); } [Fact] public void Disposing_LocalValue_Binding_Raises_PropertyChanged() { var target = new Class1(); var source = new BehaviorSubject<BindingValue<string>>("foo"); var property = Class1.FooProperty; var raised = 0; var sub = target.Bind(property, source); Assert.Equal("foo", target.GetValue(property)); target.PropertyChanged += (s, e) => { Assert.Equal(BindingPriority.Unset, e.Priority); Assert.Equal(property, e.Property); Assert.Equal("foo", e.OldValue as string); Assert.Equal("foodefault", e.NewValue as string); ++raised; }; sub.Dispose(); Assert.Equal("foodefault", target.GetValue(property)); Assert.Equal(1, raised); } [Fact] public void Setting_Style_Value_Overrides_Binding_Permanently() { var target = new Class1(); var source = new Subject<string>(); target.Bind(Class1.FooProperty, source, BindingPriority.Style); source.OnNext("foo"); Assert.Equal("foo", target.GetValue(Class1.FooProperty)); target.SetValue(Class1.FooProperty, "bar", BindingPriority.Style); Assert.Equal("bar", target.GetValue(Class1.FooProperty)); source.OnNext("baz"); Assert.Equal("bar", target.GetValue(Class1.FooProperty)); } [Fact] public void Second_LocalValue_Binding_Overrides_First() { var property = Class1.FooProperty; var target = new Class1(); var source1 = new Subject<string>(); var source2 = new Subject<string>(); target.Bind(property, source1, BindingPriority.LocalValue); target.Bind(property, source2, BindingPriority.LocalValue); source1.OnNext("foo"); Assert.Equal("foo", target.GetValue(property)); source2.OnNext("bar"); Assert.Equal("bar", target.GetValue(property)); source1.OnNext("baz"); Assert.Equal("bar", target.GetValue(property)); } [Fact] public void Completing_Second_LocalValue_Binding_Reverts_To_First() { var property = Class1.FooProperty; var target = new Class1(); var source1 = new Subject<string>(); var source2 = new Subject<string>(); target.Bind(property, source1, BindingPriority.LocalValue); target.Bind(property, source2, BindingPriority.LocalValue); source1.OnNext("foo"); source2.OnNext("bar"); source1.OnNext("baz"); source2.OnCompleted(); Assert.Equal("baz", target.GetValue(property)); } [Fact] public void Completing_StyleTrigger_Binding_Reverts_To_StyleBinding() { var property = Class1.FooProperty; var target = new Class1(); var source1 = new Subject<string>(); var source2 = new Subject<string>(); target.Bind(property, source1, BindingPriority.Style); target.Bind(property, source2, BindingPriority.StyleTrigger); source1.OnNext("foo"); source2.OnNext("bar"); source2.OnCompleted(); source1.OnNext("baz"); Assert.Equal("baz", target.GetValue(property)); } [Fact] public void Bind_NonGeneric_Sets_Current_Value() { Class1 target = new Class1(); Class1 source = new Class1(); source.SetValue(Class1.FooProperty, "initial"); target.Bind((AvaloniaProperty)Class1.FooProperty, source.GetObservable(Class1.FooProperty)); Assert.Equal("initial", target.GetValue(Class1.FooProperty)); } [Fact] public void Bind_To_ValueType_Accepts_UnsetValue() { var target = new Class1(); var source = new Subject<object>(); target.Bind(Class1.QuxProperty, source); source.OnNext(6.7); source.OnNext(AvaloniaProperty.UnsetValue); Assert.Equal(5.6, target.GetValue(Class1.QuxProperty)); Assert.False(target.IsSet(Class1.QuxProperty)); } [Fact] public void OneTime_Binding_Ignores_UnsetValue() { var target = new Class1(); var source = new Subject<object>(); target.Bind(Class1.QuxProperty, new TestOneTimeBinding(source)); source.OnNext(AvaloniaProperty.UnsetValue); Assert.Equal(5.6, target.GetValue(Class1.QuxProperty)); source.OnNext(6.7); Assert.Equal(6.7, target.GetValue(Class1.QuxProperty)); } [Fact] public void OneTime_Binding_Ignores_Binding_Errors() { var target = new Class1(); var source = new Subject<object>(); target.Bind(Class1.QuxProperty, new TestOneTimeBinding(source)); source.OnNext(new BindingNotification(new Exception(), BindingErrorType.Error)); Assert.Equal(5.6, target.GetValue(Class1.QuxProperty)); source.OnNext(6.7); Assert.Equal(6.7, target.GetValue(Class1.QuxProperty)); } [Fact] public void Bind_Does_Not_Throw_Exception_For_Unregistered_Property() { Class1 target = new Class1(); target.Bind(Class2.BarProperty, Observable.Never<string>().StartWith("foo")); Assert.Equal("foo", target.GetValue(Class2.BarProperty)); } [Fact] public void Bind_Sets_Subsequent_Value() { Class1 target = new Class1(); Class1 source = new Class1(); source.SetValue(Class1.FooProperty, "initial"); target.Bind(Class1.FooProperty, source.GetObservable(Class1.FooProperty)); source.SetValue(Class1.FooProperty, "subsequent"); Assert.Equal("subsequent", target.GetValue(Class1.FooProperty)); } [Fact] public void Bind_Ignores_Invalid_Value_Type() { Class1 target = new Class1(); target.Bind((AvaloniaProperty)Class1.FooProperty, Observable.Return((object)123)); Assert.Equal("foodefault", target.GetValue(Class1.FooProperty)); } [Fact] public void Observable_Is_Unsubscribed_When_Subscription_Disposed() { var scheduler = new TestScheduler(); var source = scheduler.CreateColdObservable<string>(); var target = new Class1(); var subscription = target.Bind(Class1.FooProperty, source); Assert.Equal(1, source.Subscriptions.Count); Assert.Equal(Subscription.Infinite, source.Subscriptions[0].Unsubscribe); subscription.Dispose(); Assert.Equal(1, source.Subscriptions.Count); Assert.Equal(0, source.Subscriptions[0].Unsubscribe); } [Fact] public void Two_Way_Separate_Binding_Works() { Class1 obj1 = new Class1(); Class1 obj2 = new Class1(); obj1.SetValue(Class1.FooProperty, "initial1"); obj2.SetValue(Class1.FooProperty, "initial2"); obj1.Bind(Class1.FooProperty, obj2.GetObservable(Class1.FooProperty)); obj2.Bind(Class1.FooProperty, obj1.GetObservable(Class1.FooProperty)); Assert.Equal("initial2", obj1.GetValue(Class1.FooProperty)); Assert.Equal("initial2", obj2.GetValue(Class1.FooProperty)); obj1.SetValue(Class1.FooProperty, "first"); Assert.Equal("first", obj1.GetValue(Class1.FooProperty)); Assert.Equal("first", obj2.GetValue(Class1.FooProperty)); obj2.SetValue(Class1.FooProperty, "second"); Assert.Equal("second", obj1.GetValue(Class1.FooProperty)); Assert.Equal("second", obj2.GetValue(Class1.FooProperty)); obj1.SetValue(Class1.FooProperty, "third"); Assert.Equal("third", obj1.GetValue(Class1.FooProperty)); Assert.Equal("third", obj2.GetValue(Class1.FooProperty)); } [Fact] public void Two_Way_Binding_With_Priority_Works() { Class1 obj1 = new Class1(); Class1 obj2 = new Class1(); obj1.SetValue(Class1.FooProperty, "initial1", BindingPriority.Style); obj2.SetValue(Class1.FooProperty, "initial2", BindingPriority.Style); obj1.Bind(Class1.FooProperty, obj2.GetObservable(Class1.FooProperty), BindingPriority.Style); obj2.Bind(Class1.FooProperty, obj1.GetObservable(Class1.FooProperty), BindingPriority.Style); Assert.Equal("initial2", obj1.GetValue(Class1.FooProperty)); Assert.Equal("initial2", obj2.GetValue(Class1.FooProperty)); obj1.SetValue(Class1.FooProperty, "first", BindingPriority.Style); Assert.Equal("first", obj1.GetValue(Class1.FooProperty)); Assert.Equal("first", obj2.GetValue(Class1.FooProperty)); obj2.SetValue(Class1.FooProperty, "second", BindingPriority.Style); Assert.Equal("first", obj1.GetValue(Class1.FooProperty)); Assert.Equal("second", obj2.GetValue(Class1.FooProperty)); obj1.SetValue(Class1.FooProperty, "third", BindingPriority.Style); Assert.Equal("third", obj1.GetValue(Class1.FooProperty)); Assert.Equal("second", obj2.GetValue(Class1.FooProperty)); } [Fact] public void Local_Binding_Overwrites_Local_Value() { var target = new Class1(); var binding = new Subject<string>(); target.Bind(Class1.FooProperty, binding); binding.OnNext("first"); Assert.Equal("first", target.GetValue(Class1.FooProperty)); target.SetValue(Class1.FooProperty, "second"); Assert.Equal("second", target.GetValue(Class1.FooProperty)); binding.OnNext("third"); Assert.Equal("third", target.GetValue(Class1.FooProperty)); } [Fact] public void StyleBinding_Overrides_Default_Value() { Class1 target = new Class1(); target.Bind(Class1.FooProperty, Single("stylevalue"), BindingPriority.Style); Assert.Equal("stylevalue", target.GetValue(Class1.FooProperty)); } [Fact] public void this_Operator_Returns_Value_Property() { Class1 target = new Class1(); target.SetValue(Class1.FooProperty, "newvalue"); Assert.Equal("newvalue", target[Class1.FooProperty]); } [Fact] public void this_Operator_Sets_Value_Property() { Class1 target = new Class1(); target[Class1.FooProperty] = "newvalue"; Assert.Equal("newvalue", target.GetValue(Class1.FooProperty)); } [Fact] public void this_Operator_Doesnt_Accept_Observable() { Class1 target = new Class1(); Assert.Throws<ArgumentException>(() => { target[Class1.FooProperty] = Observable.Return("newvalue"); }); } [Fact] public void this_Operator_Binds_One_Way() { Class1 target1 = new Class1(); Class2 target2 = new Class2(); IndexerDescriptor binding = Class2.BarProperty.Bind().WithMode(BindingMode.OneWay); target1.SetValue(Class1.FooProperty, "first"); target2[binding] = target1[!Class1.FooProperty]; target1.SetValue(Class1.FooProperty, "second"); Assert.Equal("second", target2.GetValue(Class2.BarProperty)); } [Fact] public void this_Operator_Binds_Two_Way() { Class1 target1 = new Class1(); Class1 target2 = new Class1(); target1.SetValue(Class1.FooProperty, "first"); target2[!Class1.FooProperty] = target1[!!Class1.FooProperty]; Assert.Equal("first", target2.GetValue(Class1.FooProperty)); target1.SetValue(Class1.FooProperty, "second"); Assert.Equal("second", target2.GetValue(Class1.FooProperty)); target2.SetValue(Class1.FooProperty, "third"); Assert.Equal("third", target1.GetValue(Class1.FooProperty)); } [Fact] public void this_Operator_Binds_One_Time() { Class1 target1 = new Class1(); Class1 target2 = new Class1(); target1.SetValue(Class1.FooProperty, "first"); target2[!Class1.FooProperty] = target1[Class1.FooProperty.Bind().WithMode(BindingMode.OneTime)]; target1.SetValue(Class1.FooProperty, "second"); Assert.Equal("first", target2.GetValue(Class1.FooProperty)); } [Fact] public void Binding_Error_Reverts_To_Default_Value() { var target = new Class1(); var source = new Subject<BindingValue<string>>(); target.Bind(Class1.FooProperty, source); source.OnNext("initial"); source.OnNext(BindingValue<string>.BindingError(new InvalidOperationException("Foo"))); Assert.Equal("foodefault", target.GetValue(Class1.FooProperty)); } [Fact] public void Binding_Error_With_FallbackValue_Causes_Target_Update() { var target = new Class1(); var source = new Subject<BindingValue<string>>(); target.Bind(Class1.FooProperty, source); source.OnNext("initial"); source.OnNext(BindingValue<string>.BindingError(new InvalidOperationException("Foo"), "bar")); Assert.Equal("bar", target.GetValue(Class1.FooProperty)); } [Fact] public void DataValidationError_Does_Not_Cause_Target_Update() { var target = new Class1(); var source = new Subject<BindingValue<string>>(); target.Bind(Class1.FooProperty, source); source.OnNext("initial"); source.OnNext(BindingValue<string>.DataValidationError(new InvalidOperationException("Foo"))); Assert.Equal("initial", target.GetValue(Class1.FooProperty)); } [Fact] public void DataValidationError_With_FallbackValue_Causes_Target_Update() { var target = new Class1(); var source = new Subject<BindingValue<string>>(); target.Bind(Class1.FooProperty, source); source.OnNext("initial"); source.OnNext(BindingValue<string>.DataValidationError(new InvalidOperationException("Foo"), "bar")); Assert.Equal("bar", target.GetValue(Class1.FooProperty)); } [Fact] public void Bind_Logs_Binding_Error() { var target = new Class1(); var source = new Subject<BindingValue<double>>(); var called = false; var expectedMessageTemplate = "Error in binding to {Target}.{Property}: {Message}"; LogCallback checkLogMessage = (level, area, src, mt, pv) => { if (level == LogEventLevel.Warning && area == LogArea.Binding && mt == expectedMessageTemplate) { called = true; } }; using (TestLogSink.Start(checkLogMessage)) { target.Bind(Class1.QuxProperty, source); source.OnNext(6.7); source.OnNext(BindingValue<double>.BindingError(new InvalidOperationException("Foo"))); Assert.Equal(5.6, target.GetValue(Class1.QuxProperty)); Assert.True(called); } } [Fact] public async Task Bind_With_Scheduler_Executes_On_Scheduler() { var target = new Class1(); var source = new Subject<double>(); var currentThreadId = Thread.CurrentThread.ManagedThreadId; var threadingInterfaceMock = new Mock<IPlatformThreadingInterface>(); threadingInterfaceMock.SetupGet(mock => mock.CurrentThreadIsLoopThread) .Returns(() => Thread.CurrentThread.ManagedThreadId == currentThreadId); var services = new TestServices( scheduler: AvaloniaScheduler.Instance, threadingInterface: threadingInterfaceMock.Object); using (UnitTestApplication.Start(services)) { target.Bind(Class1.QuxProperty, source); await Task.Run(() => source.OnNext(6.7)); } } [Fact] public void SetValue_Should_Not_Cause_StackOverflow_And_Have_Correct_Values() { var viewModel = new TestStackOverflowViewModel() { Value = 50 }; var target = new Class1(); target.Bind(Class1.DoubleValueProperty, new Binding("Value") { Mode = BindingMode.TwoWay, Source = viewModel }); var child = new Class1(); child[!!Class1.DoubleValueProperty] = target[!!Class1.DoubleValueProperty]; Assert.Equal(1, viewModel.SetterInvokedCount); // Issues #855 and #824 were causing a StackOverflowException at this point. target.DoubleValue = 51.001; Assert.Equal(2, viewModel.SetterInvokedCount); double expected = 51; Assert.Equal(expected, viewModel.Value); Assert.Equal(expected, target.DoubleValue); Assert.Equal(expected, child.DoubleValue); } [Fact] public void IsAnimating_On_Property_With_No_Value_Returns_False() { var target = new Class1(); Assert.False(target.IsAnimating(Class1.FooProperty)); } [Fact] public void IsAnimating_On_Property_With_Animation_Value_Returns_True() { var target = new Class1(); target.SetValue(Class1.FooProperty, "foo", BindingPriority.Animation); Assert.True(target.IsAnimating(Class1.FooProperty)); } [Fact] public void IsAnimating_On_Property_With_Non_Animation_Binding_Returns_False() { var target = new Class1(); var source = new Subject<string>(); target.Bind(Class1.FooProperty, source, BindingPriority.LocalValue); Assert.False(target.IsAnimating(Class1.FooProperty)); } [Fact] public void IsAnimating_On_Property_With_Animation_Binding_Returns_True() { var target = new Class1(); var source = new BehaviorSubject<string>("foo"); target.Bind(Class1.FooProperty, source, BindingPriority.Animation); Assert.True(target.IsAnimating(Class1.FooProperty)); } [Fact] public void IsAnimating_On_Property_With_Local_Value_And_Animation_Binding_Returns_True() { var target = new Class1(); var source = new BehaviorSubject<string>("foo"); target.SetValue(Class1.FooProperty, "bar"); target.Bind(Class1.FooProperty, source, BindingPriority.Animation); Assert.True(target.IsAnimating(Class1.FooProperty)); } [Fact] public void IsAnimating_Returns_True_When_Animated_Value_Is_Same_As_Local_Value() { var target = new Class1(); var source = new BehaviorSubject<string>("foo"); target.SetValue(Class1.FooProperty, "foo"); target.Bind(Class1.FooProperty, source, BindingPriority.Animation); Assert.True(target.IsAnimating(Class1.FooProperty)); } [Fact] public void TwoWay_Binding_Should_Not_Call_Setter_On_Creation() { var target = new Class1(); var source = new TestTwoWayBindingViewModel(); target.Bind(Class1.DoubleValueProperty, new Binding(nameof(source.Value), BindingMode.TwoWay) { Source = source }); Assert.False(source.SetterCalled); } [Fact] public void TwoWay_Binding_Should_Not_Call_Setter_On_Creation_Indexer() { var target = new Class1(); var source = new TestTwoWayBindingViewModel(); target.Bind(Class1.DoubleValueProperty, new Binding("[0]", BindingMode.TwoWay) { Source = source }); Assert.False(source.SetterCalled); } [Fact] public void Disposing_Completed_Binding_Does_Not_Throw() { var target = new Class1(); var source = new Subject<string>(); var subscription = target.Bind(Class1.FooProperty, source); source.OnCompleted(); subscription.Dispose(); } /// <summary> /// Returns an observable that returns a single value but does not complete. /// </summary> /// <typeparam name="T">The type of the observable.</typeparam> /// <param name="value">The value.</param> /// <returns>The observable.</returns> private IObservable<T> Single<T>(T value) { return Observable.Never<T>().StartWith(value); } private class Class1 : AvaloniaObject { public static readonly StyledProperty<string> FooProperty = AvaloniaProperty.Register<Class1, string>("Foo", "foodefault"); public static readonly StyledProperty<double> QuxProperty = AvaloniaProperty.Register<Class1, double>("Qux", 5.6); public static readonly StyledProperty<double> DoubleValueProperty = AvaloniaProperty.Register<Class1, double>(nameof(DoubleValue)); public double DoubleValue { get { return GetValue(DoubleValueProperty); } set { SetValue(DoubleValueProperty, value); } } } private class Class2 : Class1 { public static readonly StyledProperty<string> BarProperty = AvaloniaProperty.Register<Class2, string>("Bar", "bardefault"); } private class TestOneTimeBinding : IBinding { private IObservable<object> _source; public TestOneTimeBinding(IObservable<object> source) { _source = source; } public InstancedBinding Initiate( IAvaloniaObject target, AvaloniaProperty targetProperty, object anchor = null, bool enableDataValidation = false) { return InstancedBinding.OneTime(_source); } } private class TestStackOverflowViewModel : INotifyPropertyChanged { public int SetterInvokedCount { get; private set; } public const int MaxInvokedCount = 1000; private double _value; public event PropertyChangedEventHandler PropertyChanged; public double Value { get { return _value; } set { if (_value != value) { SetterInvokedCount++; if (SetterInvokedCount < MaxInvokedCount) { _value = (int)value; if (_value > 75) _value = 75; if (_value < 25) _value = 25; } else { _value = value; } PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Value))); } } } } private class TestTwoWayBindingViewModel { private double _value; public double Value { get => _value; set { _value = value; SetterCalled = true; } } public double this[int index] { get => _value; set { _value = value; SetterCalled = true; } } public bool SetterCalled { get; private set; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using Xunit; namespace System.Linq.Expressions.Tests { public static class ArrayBoundsTests { private const int MaxArraySize = 0X7FEFFFFF; private class BogusCollection<T> : IList<T> { public T this[int index] { get { return default(T); } set { throw new NotSupportedException(); } } public int Count => -1; public bool IsReadOnly => true; public void Add(T item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(T item) => false; public void CopyTo(T[] array, int arrayIndex) { } public IEnumerator<T> GetEnumerator() => Enumerable.Empty<T>().GetEnumerator(); public int IndexOf(T item) => -1; public void Insert(int index, T item) { throw new NotSupportedException(); } public bool Remove(T item) { throw new NotSupportedException(); } public void RemoveAt(int index) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } private class BogusReadOnlyCollection<T> : ReadOnlyCollection<T> { public BogusReadOnlyCollection() : base(new BogusCollection<T>()) { } } public static IEnumerable<object> Bounds_TestData() { yield return new byte[] { 0, 1, byte.MaxValue }; yield return new int[] { 0, 1, -1, int.MinValue, int.MaxValue }; yield return new long[] { 0, 1, -1, long.MinValue, long.MaxValue }; yield return new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; yield return new short[] { 0, 1, -1, short.MinValue, short.MaxValue }; yield return new uint[] { 0, 1, uint.MaxValue }; yield return new ulong[] { 0, 1, ulong.MaxValue }; yield return new ushort[] { 0, 1, ushort.MaxValue }; yield return new byte?[] { null, 0, 1, byte.MaxValue }; yield return new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; yield return new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; yield return new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; yield return new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; yield return new uint?[] { null, 0, 1, uint.MaxValue }; yield return new ulong?[] { null, 0, 1, ulong.MaxValue }; yield return new ushort?[] { null, 0, 1, ushort.MaxValue }; } public static IEnumerable<object[]> TestData() { foreach (Array sizes in Bounds_TestData()) { Type sizeType = sizes.GetType().GetElementType(); foreach (object size in sizes) { // ValueType yield return new object[] { typeof(bool), size, sizeType, false }; yield return new object[] { typeof(byte), size, sizeType, (byte)0 }; yield return new object[] { typeof(char), size, sizeType, (char)0 }; yield return new object[] { typeof(decimal), size, sizeType, (decimal)0 }; yield return new object[] { typeof(double), size, sizeType, (double)0 }; yield return new object[] { typeof(float), size, sizeType, (float)0 }; yield return new object[] { typeof(int), size, sizeType, 0 }; yield return new object[] { typeof(long), size, sizeType, (long)0 }; yield return new object[] { typeof(S), size, sizeType, new S() }; yield return new object[] { typeof(sbyte), size, sizeType, (sbyte)0 }; yield return new object[] { typeof(Sc), size, sizeType, new Sc() }; yield return new object[] { typeof(Scs), size, sizeType, new Scs() }; yield return new object[] { typeof(short), size, sizeType, (short)0 }; yield return new object[] { typeof(Sp), size, sizeType, new Sp() }; yield return new object[] { typeof(Ss), size, sizeType, new Ss() }; yield return new object[] { typeof(uint), size, sizeType, (uint)0 }; yield return new object[] { typeof(ulong), size, sizeType, (ulong)0 }; yield return new object[] { typeof(ushort), size, sizeType, (ushort)0 }; // Object yield return new object[] { typeof(C), size, sizeType, null }; yield return new object[] { typeof(D), size, sizeType, null }; yield return new object[] { typeof(Delegate), size, sizeType, null }; yield return new object[] { typeof(E), size, sizeType, (E)0 }; yield return new object[] { typeof(El), size, sizeType, (El)0 }; yield return new object[] { typeof(Func<object>), size, sizeType, null }; yield return new object[] { typeof(I), size, sizeType, null }; yield return new object[] { typeof(IEquatable<C>), size, sizeType, null }; yield return new object[] { typeof(IEquatable<D>), size, sizeType, null }; yield return new object[] { typeof(object), size, sizeType, null }; yield return new object[] { typeof(string), size, sizeType, null }; } } } [Theory] [PerCompilationType(nameof(TestData))] public static void NewArrayBounds(Type arrayType, object size, Type sizeType, object defaultValue, bool useInterpreter) { Expression newArrayExpression = Expression.NewArrayBounds(arrayType, Expression.Constant(size, sizeType)); Expression <Func<Array>> e = Expression.Lambda<Func<Array>>(newArrayExpression); Func<Array> f = e.Compile(useInterpreter); if (sizeType == typeof(sbyte) || sizeType == typeof(short) || sizeType == typeof(int) || sizeType == typeof(long) || sizeType == typeof(sbyte?) || sizeType == typeof(short?) || sizeType == typeof(int?) || sizeType == typeof(long?)) { VerifyArrayGenerator(f, arrayType, size == null ? (long?)null : Convert.ToInt64(size), defaultValue); } else { VerifyArrayGenerator(f, arrayType, size == null ? (long?)null : unchecked((long)Convert.ToUInt64(size)), defaultValue); } } [Fact] public static void ThrowOnNegativeSizedCollection() { // This is an obscure case, and it doesn't much matter what is thrown, as long as is thrown before such // an edge case could cause more obscure damage. A class derived from ReadOnlyCollection is used to catch // assumptions that such a type is safe. Assert.ThrowsAny<Exception>(() => Expression.NewArrayBounds(typeof(int), new BogusReadOnlyCollection<Expression>())); } private static void VerifyArrayGenerator(Func<Array> func, Type arrayType, long? size, object defaultValue) { if (!size.HasValue) { Assert.Throws<InvalidOperationException>(() => func()); } else if (unchecked((ulong)size) > int.MaxValue) { Assert.Throws<OverflowException>(() => func()); } else if (size > MaxArraySize) { Assert.Throws<OutOfMemoryException>(() => func()); } else { Array array = func(); Assert.Equal(arrayType, array.GetType().GetElementType()); Assert.Equal(0, array.GetLowerBound(0)); Assert.Equal(size, array.Length); foreach (object value in array) { Assert.Equal(defaultValue, value); } } } [Fact] public static void NullType_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.NewArrayBounds(null, Expression.Constant(2))); } [Fact] public static void VoidType_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>("type", () => Expression.NewArrayBounds(typeof(void), Expression.Constant(2))); } [Fact] public static void NullBounds_ThrowsArgumentnNullException() { AssertExtensions.Throws<ArgumentNullException>("bounds", () => Expression.NewArrayBounds(typeof(int), default(Expression[]))); AssertExtensions.Throws<ArgumentNullException>("bounds", () => Expression.NewArrayBounds(typeof(int), default(IEnumerable<Expression>))); } [Fact] public static void EmptyBounds_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>("bounds", () => Expression.NewArrayBounds(typeof(int))); } [Fact] public static void NullBoundInBounds_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("bounds[0]", () => Expression.NewArrayBounds(typeof(int), new Expression[] { null, null })); AssertExtensions.Throws<ArgumentNullException>("bounds[0]", () => Expression.NewArrayBounds(typeof(int), new List<Expression> { null, null })); } [Fact] public static void NonIntegralBoundInBounds_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>("bounds[0]", () => Expression.NewArrayBounds(typeof(int), Expression.Constant(2.0))); } [Fact] public static void ByRefType_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>("type", () => Expression.NewArrayBounds(typeof(int).MakeByRefType(), Expression.Constant(2))); } [Fact] public static void PointerType_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>("type", () => Expression.NewArrayBounds(typeof(int).MakePointerType(), Expression.Constant(2))); } [Fact] public static void OpenGenericType_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>("type", () => Expression.NewArrayBounds(typeof(List<>), Expression.Constant(2))); } [Fact] public static void TypeContainsGenericParameters_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>("type", () => Expression.NewArrayBounds(typeof(List<>.Enumerator), Expression.Constant(2))); AssertExtensions.Throws<ArgumentException>("type", () => Expression.NewArrayBounds(typeof(List<>).MakeGenericType(typeof(List<>)), Expression.Constant(2))); } [Fact] public static void UpdateSameReturnsSame() { Expression bound0 = Expression.Constant(2); Expression bound1 = Expression.Constant(3); NewArrayExpression newArrayExpression = Expression.NewArrayBounds(typeof(string), bound0, bound1); Assert.Same(newArrayExpression, newArrayExpression.Update(new [] {bound0, bound1})); } [Fact] public static void UpdateDifferentReturnsDifferent() { Expression bound0 = Expression.Constant(2); Expression bound1 = Expression.Constant(3); NewArrayExpression newArrayExpression = Expression.NewArrayBounds(typeof(string), bound0, bound1); Assert.NotSame(newArrayExpression, newArrayExpression.Update(new[] { bound0 })); Assert.NotSame(newArrayExpression, newArrayExpression.Update(new[] { bound0, bound1, bound0, bound1 })); Assert.NotSame(newArrayExpression, newArrayExpression.Update(newArrayExpression.Expressions.Reverse())); } [Fact] public static void UpdateDoesntRepeatEnumeration() { Expression bound0 = Expression.Constant(2); Expression bound1 = Expression.Constant(3); NewArrayExpression newArrayExpression = Expression.NewArrayBounds(typeof(string), bound0, bound1); Assert.NotSame(newArrayExpression, newArrayExpression.Update(new RunOnceEnumerable<Expression>(new[] { bound0 }))); } [Fact] public static void UpdateNullThrows() { Expression bound0 = Expression.Constant(2); Expression bound1 = Expression.Constant(3); NewArrayExpression newArrayExpression = Expression.NewArrayBounds(typeof(string), bound0, bound1); AssertExtensions.Throws<ArgumentNullException>("expressions", () => newArrayExpression.Update(null)); } [Theory, ClassData(typeof(CompilationTypes))] public static void SingleNegativeBoundErrorMessage(bool useInterpreter) { string localizedMessage = null; try { int[] dummy = new int["".Length - 2]; } catch (OverflowException oe) { localizedMessage = oe.Message; } Expression<Func<int[]>> lambda = Expression.Lambda<Func<int[]>>(Expression.NewArrayBounds(typeof(int), Expression.Constant(-2))); var func = lambda.Compile(useInterpreter); OverflowException ex = Assert.Throws<OverflowException>(() => func()); Assert.Equal(localizedMessage, ex.Message); } [Theory, ClassData(typeof(CompilationTypes))] public static void MultipleNegativeBoundErrorMessage(bool useInterpreter) { string localizedMessage = null; try { int[,,] dummy = new int[1, 1, "".Length - 2]; } catch (OverflowException oe) { localizedMessage = oe.Message; } Expression<Func<int[,,]>> lambda = Expression.Lambda<Func<int[,,]>>( Expression.NewArrayBounds( typeof(int), Expression.Constant(0), Expression.Constant(0), Expression.Constant(-2))); var func = lambda.Compile(useInterpreter); OverflowException ex = Assert.Throws<OverflowException>(() => func()); Assert.Equal(localizedMessage, ex.Message); } } }
// 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.Linq; using System.Security; using System.Threading; using System.Windows.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Moq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Completion { public abstract class AbstractCompletionProviderTests<TWorkspaceFixture> : TestBase, IUseFixture<TWorkspaceFixture> where TWorkspaceFixture : TestWorkspaceFixture, new() { protected readonly Mock<ICompletionSession> MockCompletionSession; internal ICompletionProvider CompletionProvider; protected TWorkspaceFixture workspaceFixture; public AbstractCompletionProviderTests() { SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext()); MockCompletionSession = new Mock<ICompletionSession>(MockBehavior.Strict); } public void SetFixture(TWorkspaceFixture workspaceFixture) { this.workspaceFixture = workspaceFixture; this.CompletionProvider = CreateCompletionProvider(); } protected static bool CanUseSpeculativeSemanticModel(Document document, int position) { var service = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); var node = document.GetSyntaxRootAsync().Result.FindToken(position).Parent; return !service.GetMemberBodySpanForSpeculativeBinding(node).IsEmpty; } private void CheckResults(Document document, int position, string expectedItemOrNull, string expectedDescriptionOrNull, bool usePreviousCharAsTrigger, bool checkForAbsence, Glyph? glyph) { var code = document.GetTextAsync().Result.ToString(); CompletionTriggerInfo completionTriggerInfo = new CompletionTriggerInfo(); if (usePreviousCharAsTrigger) { completionTriggerInfo = CompletionTriggerInfo.CreateTypeCharTriggerInfo(triggerCharacter: code.ElementAt(position - 1)); } var group = CompletionProvider.GetGroupAsync(document, position, completionTriggerInfo).Result; var completions = group == null ? null : group.Items; if (checkForAbsence) { if (completions == null) { return; } if (expectedItemOrNull == null) { Assert.Empty(completions); } else { AssertEx.None( completions, c => CompareItems(c.DisplayText, expectedItemOrNull) && (expectedDescriptionOrNull != null ? c.GetDescriptionAsync().Result.GetFullText() == expectedDescriptionOrNull : true)); } } else { if (expectedItemOrNull == null) { Assert.NotEmpty(completions); } else { AssertEx.Any(completions, c => CompareItems(c.DisplayText, expectedItemOrNull) && (expectedDescriptionOrNull != null ? c.GetDescriptionAsync().Result.GetFullText() == expectedDescriptionOrNull : true) && (glyph.HasValue ? c.Glyph == glyph.Value : true)); } } } private void Verify(string markup, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, bool experimental, int? glyph) { string code; int position; MarkupTestFile.GetPosition(markup.NormalizeLineEndings(), out code, out position); VerifyWorker(code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, experimental, glyph); } protected void VerifyCustomCommitProvider(string markupBeforeCommit, string itemToCommit, string expectedCodeAfterCommit, SourceCodeKind? sourceCodeKind = null, char? commitChar = null) { string code; int position; MarkupTestFile.GetPosition(markupBeforeCommit.NormalizeLineEndings(), out code, out position); if (sourceCodeKind.HasValue) { VerifyCustomCommitProviderWorker(code, position, itemToCommit, expectedCodeAfterCommit, sourceCodeKind.Value, commitChar); } else { VerifyCustomCommitProviderWorker(code, position, itemToCommit, expectedCodeAfterCommit, SourceCodeKind.Regular, commitChar); VerifyCustomCommitProviderWorker(code, position, itemToCommit, expectedCodeAfterCommit, SourceCodeKind.Script, commitChar); } } protected void VerifyProviderCommit(string markupBeforeCommit, string itemToCommit, string expectedCodeAfterCommit, char? commitChar, string textTypedSoFar, SourceCodeKind? sourceCodeKind = null) { string code; int position; MarkupTestFile.GetPosition(markupBeforeCommit.NormalizeLineEndings(), out code, out position); expectedCodeAfterCommit = expectedCodeAfterCommit.NormalizeLineEndings(); if (sourceCodeKind.HasValue) { VerifyProviderCommitWorker(code, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar, sourceCodeKind.Value); } else { VerifyProviderCommitWorker(code, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar, SourceCodeKind.Regular); VerifyProviderCommitWorker(code, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar, SourceCodeKind.Script); } } protected virtual bool CompareItems(string actualItem, string expectedItem) { return actualItem.Equals(expectedItem); } protected void VerifyItemExists(string markup, string expectedItem, string expectedDescriptionOrNull = null, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false, bool experimental = false, int? glyph = null) { if (sourceCodeKind.HasValue) { Verify(markup, expectedItem, expectedDescriptionOrNull, sourceCodeKind.Value, usePreviousCharAsTrigger, checkForAbsence: false, experimental: experimental, glyph: glyph); } else { Verify(markup, expectedItem, expectedDescriptionOrNull, SourceCodeKind.Regular, usePreviousCharAsTrigger, checkForAbsence: false, experimental: experimental, glyph: glyph); Verify(markup, expectedItem, expectedDescriptionOrNull, SourceCodeKind.Script, usePreviousCharAsTrigger, checkForAbsence: false, experimental: experimental, glyph: glyph); } } protected void VerifyItemIsAbsent(string markup, string expectedItem, string expectedDescriptionOrNull = null, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false, bool experimental = false) { if (sourceCodeKind.HasValue) { Verify(markup, expectedItem, expectedDescriptionOrNull, sourceCodeKind.Value, usePreviousCharAsTrigger, checkForAbsence: true, experimental: experimental, glyph: null); } else { Verify(markup, expectedItem, expectedDescriptionOrNull, SourceCodeKind.Regular, usePreviousCharAsTrigger, checkForAbsence: true, experimental: experimental, glyph: null); Verify(markup, expectedItem, expectedDescriptionOrNull, SourceCodeKind.Script, usePreviousCharAsTrigger, checkForAbsence: true, experimental: experimental, glyph: null); } } protected void VerifyAnyItemExists(string markup, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false, bool experimental = false) { if (sourceCodeKind.HasValue) { Verify(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind.Value, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: false, experimental: experimental, glyph: null); } else { Verify(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: false, experimental: experimental, glyph: null); Verify(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: false, experimental: experimental, glyph: null); } } protected void VerifyNoItemsExist(string markup, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false, bool experimental = false) { if (sourceCodeKind.HasValue) { Verify(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind.Value, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: true, experimental: experimental, glyph: null); } else { Verify(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: true, experimental: experimental, glyph: null); Verify(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: true, experimental: experimental, glyph: null); } } internal abstract ICompletionProvider CreateCompletionProvider(); /// <summary> /// Override this to change parameters or return without verifying anything, e.g. for script sources. Or to test in other code contexts. /// </summary> /// <param name="code">The source code (not markup).</param> /// <param name="expectedItemOrNull">The expected item. If this is null, verifies that *any* item shows up for this CompletionProvider (or no items show up if checkForAbsence is true).</param> /// <param name="expectedDescriptionOrNull">If this is null, the Description for the item is ignored.</param> /// <param name="usePreviousCharAsTrigger">Whether or not the previous character in markup should be used to trigger IntelliSense for this provider. If false, invokes it through the invoke IntelliSense command.</param> /// <param name="checkForAbsence">If true, checks for absence of a specific item (or that no items are returned from this CompletionProvider)</param> protected virtual void VerifyWorker(string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, bool experimental, int? glyph) { if (experimental) { foreach (var project in workspaceFixture.Workspace.Projects) { workspaceFixture.Workspace.OnParseOptionsChanged(project.Id, CreateExperimentalParseOptions(project.ParseOptions)); } } Glyph? expectedGlyph = null; if (glyph.HasValue) { expectedGlyph = (Glyph)glyph.Value; } var document1 = workspaceFixture.UpdateDocument(code, sourceCodeKind); CheckResults(document1, position, expectedItemOrNull, expectedDescriptionOrNull, usePreviousCharAsTrigger, checkForAbsence, expectedGlyph); if (CanUseSpeculativeSemanticModel(document1, position)) { var document2 = workspaceFixture.UpdateDocument(code, sourceCodeKind, cleanBeforeUpdate: false); CheckResults(document2, position, expectedItemOrNull, expectedDescriptionOrNull, usePreviousCharAsTrigger, checkForAbsence, expectedGlyph); } } protected virtual ParseOptions CreateExperimentalParseOptions(ParseOptions parseOptions) { return parseOptions; } /// <summary> /// Override this to change parameters or return without verifying anything, e.g. for script sources. Or to test in other code contexts. /// </summary> /// <param name="codeBeforeCommit">The source code (not markup).</param> /// <param name="position">Position where intellisense is invoked.</param> /// <param name="itemToCommit">The item to commit from the completion provider.</param> /// <param name="expectedCodeAfterCommit">The expected code after commit.</param> protected virtual void VerifyCustomCommitProviderWorker(string codeBeforeCommit, int position, string itemToCommit, string expectedCodeAfterCommit, SourceCodeKind sourceCodeKind, char? commitChar = null) { var document1 = workspaceFixture.UpdateDocument(codeBeforeCommit, sourceCodeKind); VerifyCustomCommitProviderCheckResults(document1, codeBeforeCommit, position, itemToCommit, expectedCodeAfterCommit, commitChar); if (CanUseSpeculativeSemanticModel(document1, position)) { var document2 = workspaceFixture.UpdateDocument(codeBeforeCommit, sourceCodeKind, cleanBeforeUpdate: false); VerifyCustomCommitProviderCheckResults(document2, codeBeforeCommit, position, itemToCommit, expectedCodeAfterCommit, commitChar); } } private void VerifyCustomCommitProviderCheckResults(Document document, string codeBeforeCommit, int position, string itemToCommit, string expectedCodeAfterCommit, char? commitChar) { var textBuffer = workspaceFixture.Workspace.Documents.Single().TextBuffer; var completions = CompletionProvider.GetGroupAsync(document, position, CompletionTriggerInfo.CreateInvokeCompletionTriggerInfo()).Result.Items; var completionItem = completions.First(i => CompareItems(i.DisplayText, itemToCommit)); var customCommitCompletionProvider = CompletionProvider as ICustomCommitCompletionProvider; if (customCommitCompletionProvider != null) { var textView = workspaceFixture.Workspace.Documents.Single().GetTextView(); VerifyCustomCommitWorker(customCommitCompletionProvider, completionItem, textView, textBuffer, codeBeforeCommit, expectedCodeAfterCommit, commitChar); } else { throw new Exception(); } } internal virtual void VerifyCustomCommitWorker(ICustomCommitCompletionProvider customCommitCompletionProvider, CompletionItem completionItem, ITextView textView, ITextBuffer textBuffer, string codeBeforeCommit, string expectedCodeAfterCommit, char? commitChar = null) { int expectedCaretPosition; string actualExpectedCode = null; MarkupTestFile.GetPosition(expectedCodeAfterCommit, out actualExpectedCode, out expectedCaretPosition); if (commitChar.HasValue && !customCommitCompletionProvider.IsCommitCharacter(completionItem, commitChar.Value, string.Empty)) { Assert.Equal(codeBeforeCommit, actualExpectedCode); return; } customCommitCompletionProvider.Commit(completionItem, textView, textBuffer, textView.TextSnapshot, commitChar); string actualCodeAfterCommit = textBuffer.CurrentSnapshot.AsText().ToString(); var caretPosition = textView.Caret.Position.BufferPosition.Position; Assert.Equal(actualExpectedCode, actualCodeAfterCommit); Assert.Equal(expectedCaretPosition, caretPosition); } /// <summary> /// Override this to change parameters or return without verifying anything, e.g. for script sources. Or to test in other code contexts. /// </summary> /// <param name="codeBeforeCommit">The source code (not markup).</param> /// <param name="position">Position where intellisense is invoked.</param> /// <param name="itemToCommit">The item to commit from the completion provider.</param> /// <param name="expectedCodeAfterCommit">The expected code after commit.</param> protected virtual void VerifyProviderCommitWorker(string codeBeforeCommit, int position, string itemToCommit, string expectedCodeAfterCommit, char? commitChar, string textTypedSoFar, SourceCodeKind sourceCodeKind) { var document1 = workspaceFixture.UpdateDocument(codeBeforeCommit, sourceCodeKind); VerifyProviderCommitCheckResults(document1, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar); if (CanUseSpeculativeSemanticModel(document1, position)) { var document2 = workspaceFixture.UpdateDocument(codeBeforeCommit, sourceCodeKind, cleanBeforeUpdate: false); VerifyProviderCommitCheckResults(document2, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar); } } private void VerifyProviderCommitCheckResults(Document document, int position, string itemToCommit, string expectedCodeAfterCommit, char? commitChar, string textTypedSoFar) { var textBuffer = workspaceFixture.Workspace.Documents.Single().TextBuffer; var textSnapshot = textBuffer.CurrentSnapshot.AsText(); var completions = CompletionProvider.GetGroupAsync(document, position, CompletionTriggerInfo.CreateInvokeCompletionTriggerInfo()).Result.Items; var completionItem = completions.First(i => CompareItems(i.DisplayText, itemToCommit)); var textChange = CompletionProvider.IsCommitCharacter(completionItem, commitChar.HasValue ? commitChar.Value : ' ', textTypedSoFar) ? CompletionProvider.GetTextChange(completionItem, commitChar, textTypedSoFar) : new TextChange(); var oldText = document.GetTextAsync().Result; var newText = oldText.WithChanges(textChange); Assert.Equal(expectedCodeAfterCommit, newText.ToString()); } protected void VerifyItemInEditorBrowsableContexts(string markup, string referencedCode, string item, int expectedSymbolsSameSolution, int expectedSymbolsMetadataReference, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers = false) { CompletionProvider = CreateCompletionProvider(); VerifyItemWithMetadataReference(markup, referencedCode, item, expectedSymbolsMetadataReference, sourceLanguage, referencedLanguage, hideAdvancedMembers); VerifyItemWithProjectReference(markup, referencedCode, item, expectedSymbolsSameSolution, sourceLanguage, referencedLanguage, hideAdvancedMembers); // If the source and referenced languages are different, then they cannot be in the same project if (sourceLanguage == referencedLanguage) { VerifyItemInSameProject(markup, referencedCode, item, expectedSymbolsSameSolution, sourceLanguage, hideAdvancedMembers); } } private void VerifyItemWithMetadataReference(string markup, string metadataReferenceCode, string expectedItem, int expectedSymbols, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument""> {1} </Document> <MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument""> {3} </Document> </MetadataReferenceFromSource> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(metadataReferenceCode)); VerifyItemWithReferenceWorker(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } protected void VerifyItemWithAliasedMetadataReferences(string markup, string metadataAlias, string expectedItem, int expectedSymbols, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument""> {1} </Document> <MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"" Aliases=""{3}, global"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument""> </Document> </MetadataReferenceFromSource> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(metadataAlias)); VerifyItemWithReferenceWorker(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } protected void VerifyItemWithProjectReference(string markup, string referencedCode, string expectedItem, int expectedSymbols, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <ProjectReference>ReferencedProject</ProjectReference> <Document FilePath=""SourceDocument""> {1} </Document> </Project> <Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument""> {3} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(referencedCode)); VerifyItemWithReferenceWorker(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } private void VerifyItemInSameProject(string markup, string referencedCode, string expectedItem, int expectedSymbols, string sourceLanguage, bool hideAdvancedMembers) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument""> {1} </Document> <Document FilePath=""ReferencedDocument""> {2} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), SecurityElement.Escape(referencedCode)); VerifyItemWithReferenceWorker(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } private void VerifyItemWithReferenceWorker(string xmlString, string expectedItem, int expectedSymbols, bool hideAdvancedMembers) { using (var testWorkspace = TestWorkspaceFactory.CreateWorkspace(xmlString)) { var optionsService = testWorkspace.Services.GetService<IOptionService>(); int cursorPosition = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value; var solution = testWorkspace.CurrentSolution; DocumentId docId = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").Id; Document doc = solution.GetDocument(docId); optionsService.SetOptions(optionsService.GetOptions().WithChangedOption(Microsoft.CodeAnalysis.Completion.CompletionOptions.HideAdvancedMembers, doc.Project.Language, hideAdvancedMembers)); CompletionTriggerInfo completionTriggerInfo = new CompletionTriggerInfo(); var completions = CompletionProvider.GetGroupAsync(doc, cursorPosition, completionTriggerInfo).Result; if (expectedSymbols >= 1) { AssertEx.Any(completions.Items, c => CompareItems(c.DisplayText, expectedItem)); // Throw if multiple to indicate a bad test case var description = completions.Items.Single(c => CompareItems(c.DisplayText, expectedItem)).GetDescriptionAsync().Result; if (expectedSymbols == 1) { Assert.DoesNotContain("+", description.GetFullText()); } else { Assert.Contains(GetExpectedOverloadSubstring(expectedSymbols), description.GetFullText()); } } else { if (completions != null) { AssertEx.None(completions.Items, c => CompareItems(c.DisplayText, expectedItem)); } } } } protected void VerifyItemWithMscorlib45(string markup, string expectedItem, string expectedDescription, string sourceLanguage) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferencesNet45=""true""> <Document FilePath=""SourceDocument""> {1} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup)); VerifyItemWithMscorlib45Worker(xmlString, expectedItem, expectedDescription); } private void VerifyItemWithMscorlib45Worker(string xmlString, string expectedItem, string expectedDescription) { using (var testWorkspace = TestWorkspaceFactory.CreateWorkspace(xmlString)) { int cursorPosition = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value; var solution = testWorkspace.CurrentSolution; DocumentId docId = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").Id; Document doc = solution.GetDocument(docId); CompletionTriggerInfo completionTriggerInfo = new CompletionTriggerInfo(); var completions = CompletionProvider.GetGroupAsync(doc, cursorPosition, completionTriggerInfo).Result; var item = completions.Items.FirstOrDefault(i => i.DisplayText == expectedItem); Assert.Equal(expectedDescription, item.GetDescriptionAsync().Result.GetFullText()); } } private const char NonBreakingSpace = (char)0x00A0; private string GetExpectedOverloadSubstring(int expectedSymbols) { if (expectedSymbols <= 1) { throw new ArgumentOutOfRangeException("expectedSymbols"); } return "+" + NonBreakingSpace + (expectedSymbols - 1) + NonBreakingSpace + FeaturesResources.Overload; } protected void VerifyItemInLinkedFiles(string xmlString, string expectedItem, string expectedDescription) { using (var testWorkspace = TestWorkspaceFactory.CreateWorkspace(xmlString)) { var optionsService = testWorkspace.Services.GetService<IOptionService>(); int cursorPosition = testWorkspace.Documents.First().CursorPosition.Value; var solution = testWorkspace.CurrentSolution; var textContainer = testWorkspace.Documents.First().TextBuffer.AsTextContainer(); var currentContextDocumentId = testWorkspace.GetDocumentIdInCurrentContext(textContainer); Document doc = solution.GetDocument(currentContextDocumentId); CompletionTriggerInfo completionTriggerInfo = new CompletionTriggerInfo(); var completions = CompletionProvider.GetGroupAsync(doc, cursorPosition, completionTriggerInfo).WaitAndGetResult(CancellationToken.None); var item = completions.Items.Single(c => c.DisplayText == expectedItem); Assert.NotNull(item); if (expectedDescription != null) { var actualDescription = item.GetDescriptionAsync().Result.GetFullText(); Assert.Equal(expectedDescription, actualDescription); } } } } }
// Copyright (c) Alium FX. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Alium.Features { using System; using Xunit; using Alium.Modules; /// <summary> /// Provides tests for the <see cref="FeatureId"/> type. /// </summary> public class FeatureIdTests { [Fact] public void Constructor_ValidatesArguments() { // Arrange string value = "submodule"; var moduleId = new ModuleId("module"); var featureId = new FeatureId(moduleId, "feature"); // Act // Assert Assert.Throws<ArgumentException>("sourceModuleId", () => new FeatureId(ModuleId.Empty, value)); Assert.Throws<ArgumentException>("sourceModuleId", () => new FeatureId(ModuleId.Empty, value)); Assert.Throws<ArgumentException>("value", () => new FeatureId(moduleId, null! /* value */)); Assert.Throws<ArgumentException>("value", () => new FeatureId(moduleId, string.Empty /* value */)); Assert.Throws<ArgumentException>("sourceModuleId", () => new FeatureId(ModuleId.Empty, FeatureId.Empty, value)); Assert.Throws<ArgumentException>("sourceModuleId", () => new FeatureId(ModuleId.Empty, FeatureId.Empty, value)); Assert.Throws<ArgumentException>("parentFeatureId", () => new FeatureId(moduleId, FeatureId.Empty, value)); Assert.Throws<ArgumentException>("parentFeatureId", () => new FeatureId(moduleId, FeatureId.Empty, value)); Assert.Throws<ArgumentException>("value", () => new FeatureId(moduleId, featureId, null! /* value */)); Assert.Throws<ArgumentException>("value", () => new FeatureId(moduleId, featureId, string.Empty /* value */)); } [Fact] public void InitialisedInstance_HasValue_WhenProvidingModuleId() { // Arrange var moduleId = new ModuleId("module"); // Act var value = new FeatureId(moduleId, "feature"); // Asset Assert.True(value.HasValue); Assert.True(value.ParentModuleId.HasValue); Assert.True(value.ParentModuleId.Equals(moduleId)); Assert.True(value.SourceModuleId.HasValue); Assert.True(value.SourceModuleId.Equals(moduleId)); Assert.Equal("feature", value.LocalValue); Assert.Equal("module.feature", value.Value); } [Fact] public void InitialisedInstance_HasValue_WhenProvidingFeatureId() { // Arrange var moduleId = new ModuleId("module"); var featureId = new FeatureId(moduleId, "parentFeature"); // Act var value = new FeatureId(moduleId, featureId, "feature"); // Asset Assert.True(value.HasValue); Assert.True(value.ParentModuleId.HasValue); Assert.True(value.ParentModuleId.Equals(moduleId)); Assert.True(value.ParentModuleId.HasValue); Assert.True(value.ParentModuleId.Equals(moduleId)); Assert.True(value.SourceModuleId.HasValue); Assert.True(value.SourceModuleId.Equals(moduleId)); Assert.Equal("feature", value.LocalValue); Assert.Equal("module.parentFeature.feature", value.Value); } [Fact] public void InitialisingFeatureId_CreatesNestedValue() { // Arrange var moduleId = new ModuleId("module"); // Act var featureAId = new FeatureId(moduleId, "featureA"); var featureBId = new FeatureId(moduleId, featureAId, "featureB"); // Assert Assert.Equal("module.featureA", featureAId.Value); Assert.Equal("module.featureA.featureB", featureBId.Value); Assert.Equal(featureAId, featureBId.ParentFeatureId); } [Fact] public void CanCompare_AgainstFeatureId() { // Arrange var moduleId = new ModuleId("module"); var id = new FeatureId(moduleId, "feature"); // Act int compare0 = id.CompareTo(FeatureId.Empty); int compare1 = id.CompareTo(new FeatureId(moduleId, "feature")); int compare2 = id.CompareTo(new FeatureId(moduleId, "zzzz")); int compare3 = id.CompareTo(new FeatureId(moduleId, "aaaa")); // Assert Assert.True(1 == compare0); Assert.True(0 == compare1); Assert.True(-1 == compare2); Assert.True(1 == compare3); } [Fact] public void CanCompare_AgainstString() { // Arrange var moduleId = new ModuleId("module"); var id = new FeatureId(moduleId, "feature"); // Act int compare0 = id.CompareTo((string?) null); int compare1 = id.CompareTo("module.feature"); int compare2 = id.CompareTo("module.zzzz"); int compare3 = id.CompareTo("module.aaaa"); // Assert Assert.True(1 == compare0); Assert.True(0 == compare1); Assert.True(-1 == compare2); Assert.True(1 == compare3); } [Fact] public void WhenComparing_UsesCaseInsensitiveCompare() { // Arrange var moduleId = new ModuleId("module"); string value = "feature"; var id = new FeatureId(moduleId, value); // Act int compare = id.CompareTo("MODULE.FEATURE"); // Assert Assert.Equal(0, compare); } [Fact] public void CanEquate_AgainstFeatureId() { // Arrange var moduleId = new ModuleId("module"); var id = new FeatureId(moduleId, "feature"); // Act bool equate0 = id.Equals(FeatureId.Empty); bool equate1 = id.Equals(new FeatureId(moduleId, "feature")); bool equate2 = id.Equals(new FeatureId(moduleId, "aaaa")); // Assert Assert.False(equate0); Assert.True(equate1); Assert.False(equate2); } [Fact] public void CanEquate_AgainstString() { // Arrange var moduleId = new ModuleId("module"); var id = new FeatureId(moduleId, "feature"); // Act bool equate0 = id.Equals((string?)null); bool equate1 = id.Equals("module.feature"); bool equate2 = id.Equals("module.aaaa"); // Assert Assert.False(equate0); Assert.True(equate1); Assert.False(equate2); } [Fact] public void WhenEquating_UsesCaseInsensitiveCompare() { // Arrange var moduleId = new ModuleId("module"); var id = new FeatureId(moduleId, "feature"); // Act bool equals = id.Equals(new FeatureId(moduleId, "FEATURE")); // Assert Assert.True(equals); } [Fact] public void CanExplicitlyCast_FromFeatureId_ToString() { // Arrange var moduleId = new ModuleId("module"); var id = new FeatureId(moduleId, "feature"); // Act string value = (string) id; // Assert Assert.Equal("module.feature", value); } [Fact] public void ParentMdoule_InheritedFromParentFeature() { // Arrange var moduleId = new ModuleId("module"); var otherModuleId = new ModuleId("otherModule"); var featureId = new FeatureId(moduleId, "feature"); var otherFeatureId = new FeatureId(otherModuleId, featureId, "feature"); // Act // Assert Assert.Equal(moduleId, otherFeatureId.ParentModuleId); Assert.Equal(otherModuleId, otherFeatureId.SourceModuleId); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace Northwind { /// <summary> /// Strongly-typed collection for the Category class. /// </summary> [Serializable] public partial class CategoryCollection : ActiveList<Category, CategoryCollection> { public CategoryCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>CategoryCollection</returns> public CategoryCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { Category o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Categories table. /// </summary> [Serializable] public partial class Category : ActiveRecord<Category>, IActiveRecord { #region .ctors and Default Settings public Category() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public Category(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public Category(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public Category(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Categories", TableType.Table, DataService.GetInstance("Northwind")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarCategoryID = new TableSchema.TableColumn(schema); colvarCategoryID.ColumnName = "CategoryID"; colvarCategoryID.DataType = DbType.Int32; colvarCategoryID.MaxLength = 0; colvarCategoryID.AutoIncrement = true; colvarCategoryID.IsNullable = false; colvarCategoryID.IsPrimaryKey = true; colvarCategoryID.IsForeignKey = false; colvarCategoryID.IsReadOnly = false; colvarCategoryID.DefaultSetting = @""; colvarCategoryID.ForeignKeyTableName = ""; schema.Columns.Add(colvarCategoryID); TableSchema.TableColumn colvarCategoryName = new TableSchema.TableColumn(schema); colvarCategoryName.ColumnName = "CategoryName"; colvarCategoryName.DataType = DbType.String; colvarCategoryName.MaxLength = 15; colvarCategoryName.AutoIncrement = false; colvarCategoryName.IsNullable = false; colvarCategoryName.IsPrimaryKey = false; colvarCategoryName.IsForeignKey = false; colvarCategoryName.IsReadOnly = false; colvarCategoryName.DefaultSetting = @""; colvarCategoryName.ForeignKeyTableName = ""; schema.Columns.Add(colvarCategoryName); TableSchema.TableColumn colvarDescription = new TableSchema.TableColumn(schema); colvarDescription.ColumnName = "Description"; colvarDescription.DataType = DbType.String; colvarDescription.MaxLength = 1073741823; colvarDescription.AutoIncrement = false; colvarDescription.IsNullable = true; colvarDescription.IsPrimaryKey = false; colvarDescription.IsForeignKey = false; colvarDescription.IsReadOnly = false; colvarDescription.DefaultSetting = @""; colvarDescription.ForeignKeyTableName = ""; schema.Columns.Add(colvarDescription); TableSchema.TableColumn colvarPicture = new TableSchema.TableColumn(schema); colvarPicture.ColumnName = "Picture"; colvarPicture.DataType = DbType.Binary; colvarPicture.MaxLength = 2147483647; colvarPicture.AutoIncrement = false; colvarPicture.IsNullable = true; colvarPicture.IsPrimaryKey = false; colvarPicture.IsForeignKey = false; colvarPicture.IsReadOnly = false; colvarPicture.DefaultSetting = @""; colvarPicture.ForeignKeyTableName = ""; schema.Columns.Add(colvarPicture); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["Northwind"].AddSchema("Categories",schema); } } #endregion #region Props [XmlAttribute("CategoryID")] [Bindable(true)] public int CategoryID { get { return GetColumnValue<int>(Columns.CategoryID); } set { SetColumnValue(Columns.CategoryID, value); } } [XmlAttribute("CategoryName")] [Bindable(true)] public string CategoryName { get { return GetColumnValue<string>(Columns.CategoryName); } set { SetColumnValue(Columns.CategoryName, value); } } [XmlAttribute("Description")] [Bindable(true)] public string Description { get { return GetColumnValue<string>(Columns.Description); } set { SetColumnValue(Columns.Description, value); } } [XmlAttribute("Picture")] [Bindable(true)] public byte[] Picture { get { return GetColumnValue<byte[]>(Columns.Picture); } set { SetColumnValue(Columns.Picture, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } public Northwind.ProductCategoryMapCollection ProductCategoryMapRecords() { return new Northwind.ProductCategoryMapCollection().Where(ProductCategoryMap.Columns.CategoryID, CategoryID).Load(); } public Northwind.ProductCollection Products() { return new Northwind.ProductCollection().Where(Product.Columns.CategoryID, CategoryID).Load(); } #endregion //no foreign key tables defined (0) #region Many To Many Helpers public Northwind.ProductCollection GetProductCollection() { return Category.GetProductCollection(this.CategoryID); } public static Northwind.ProductCollection GetProductCollection(int varCategoryID) { SubSonic.QueryCommand cmd = new SubSonic.QueryCommand("SELECT * FROM [dbo].[Products] INNER JOIN [Product_Category_Map] ON [Products].[ProductID] = [Product_Category_Map].[ProductID] WHERE [Product_Category_Map].[CategoryID] = @CategoryID", Category.Schema.Provider.Name); cmd.AddParameter("@CategoryID", varCategoryID, DbType.Int32); IDataReader rdr = SubSonic.DataService.GetReader(cmd); ProductCollection coll = new ProductCollection(); coll.LoadAndCloseReader(rdr); return coll; } public static void SaveProductMap(int varCategoryID, ProductCollection items) { QueryCommandCollection coll = new SubSonic.QueryCommandCollection(); //delete out the existing QueryCommand cmdDel = new QueryCommand("DELETE FROM [Product_Category_Map] WHERE [Product_Category_Map].[CategoryID] = @CategoryID", Category.Schema.Provider.Name); cmdDel.AddParameter("@CategoryID", varCategoryID, DbType.Int32); coll.Add(cmdDel); DataService.ExecuteTransaction(coll); foreach (Product item in items) { ProductCategoryMap varProductCategoryMap = new ProductCategoryMap(); varProductCategoryMap.SetColumnValue("CategoryID", varCategoryID); varProductCategoryMap.SetColumnValue("ProductID", item.GetPrimaryKeyValue()); varProductCategoryMap.Save(); } } public static void SaveProductMap(int varCategoryID, System.Web.UI.WebControls.ListItemCollection itemList) { QueryCommandCollection coll = new SubSonic.QueryCommandCollection(); //delete out the existing QueryCommand cmdDel = new QueryCommand("DELETE FROM [Product_Category_Map] WHERE [Product_Category_Map].[CategoryID] = @CategoryID", Category.Schema.Provider.Name); cmdDel.AddParameter("@CategoryID", varCategoryID, DbType.Int32); coll.Add(cmdDel); DataService.ExecuteTransaction(coll); foreach (System.Web.UI.WebControls.ListItem l in itemList) { if (l.Selected) { ProductCategoryMap varProductCategoryMap = new ProductCategoryMap(); varProductCategoryMap.SetColumnValue("CategoryID", varCategoryID); varProductCategoryMap.SetColumnValue("ProductID", l.Value); varProductCategoryMap.Save(); } } } public static void SaveProductMap(int varCategoryID , int[] itemList) { QueryCommandCollection coll = new SubSonic.QueryCommandCollection(); //delete out the existing QueryCommand cmdDel = new QueryCommand("DELETE FROM [Product_Category_Map] WHERE [Product_Category_Map].[CategoryID] = @CategoryID", Category.Schema.Provider.Name); cmdDel.AddParameter("@CategoryID", varCategoryID, DbType.Int32); coll.Add(cmdDel); DataService.ExecuteTransaction(coll); foreach (int item in itemList) { ProductCategoryMap varProductCategoryMap = new ProductCategoryMap(); varProductCategoryMap.SetColumnValue("CategoryID", varCategoryID); varProductCategoryMap.SetColumnValue("ProductID", item); varProductCategoryMap.Save(); } } public static void DeleteProductMap(int varCategoryID) { QueryCommand cmdDel = new QueryCommand("DELETE FROM [Product_Category_Map] WHERE [Product_Category_Map].[CategoryID] = @CategoryID", Category.Schema.Provider.Name); cmdDel.AddParameter("@CategoryID", varCategoryID, DbType.Int32); DataService.ExecuteQuery(cmdDel); } #endregion #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varCategoryName,string varDescription,byte[] varPicture) { Category item = new Category(); item.CategoryName = varCategoryName; item.Description = varDescription; item.Picture = varPicture; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varCategoryID,string varCategoryName,string varDescription,byte[] varPicture) { Category item = new Category(); item.CategoryID = varCategoryID; item.CategoryName = varCategoryName; item.Description = varDescription; item.Picture = varPicture; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn CategoryIDColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn CategoryNameColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn DescriptionColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn PictureColumn { get { return Schema.Columns[3]; } } #endregion #region Columns Struct public struct Columns { public static string CategoryID = @"CategoryID"; public static string CategoryName = @"CategoryName"; public static string Description = @"Description"; public static string Picture = @"Picture"; } #endregion #region Update PK Collections public void SetPKValues() { } #endregion #region Deep Save public void DeepSave() { Save(); } #endregion } }
namespace android.view { [global::MonoJavaBridge.JavaClass()] public partial class GestureDetector : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static GestureDetector() { InitJNI(); } protected GestureDetector(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaInterface(typeof(global::android.view.GestureDetector.OnDoubleTapListener_))] public interface OnDoubleTapListener : global::MonoJavaBridge.IJavaObject { bool onSingleTapConfirmed(android.view.MotionEvent arg0); bool onDoubleTap(android.view.MotionEvent arg0); bool onDoubleTapEvent(android.view.MotionEvent arg0); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.view.GestureDetector.OnDoubleTapListener))] public sealed partial class OnDoubleTapListener_ : java.lang.Object, OnDoubleTapListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static OnDoubleTapListener_() { InitJNI(); } internal OnDoubleTapListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _onSingleTapConfirmed8728; bool android.view.GestureDetector.OnDoubleTapListener.onSingleTapConfirmed(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnDoubleTapListener_._onSingleTapConfirmed8728, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnDoubleTapListener_.staticClass, global::android.view.GestureDetector.OnDoubleTapListener_._onSingleTapConfirmed8728, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onDoubleTap8729; bool android.view.GestureDetector.OnDoubleTapListener.onDoubleTap(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnDoubleTapListener_._onDoubleTap8729, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnDoubleTapListener_.staticClass, global::android.view.GestureDetector.OnDoubleTapListener_._onDoubleTap8729, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onDoubleTapEvent8730; bool android.view.GestureDetector.OnDoubleTapListener.onDoubleTapEvent(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnDoubleTapListener_._onDoubleTapEvent8730, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnDoubleTapListener_.staticClass, global::android.view.GestureDetector.OnDoubleTapListener_._onDoubleTapEvent8730, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.GestureDetector.OnDoubleTapListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/GestureDetector$OnDoubleTapListener")); global::android.view.GestureDetector.OnDoubleTapListener_._onSingleTapConfirmed8728 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.OnDoubleTapListener_.staticClass, "onSingleTapConfirmed", "(Landroid/view/MotionEvent;)Z"); global::android.view.GestureDetector.OnDoubleTapListener_._onDoubleTap8729 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.OnDoubleTapListener_.staticClass, "onDoubleTap", "(Landroid/view/MotionEvent;)Z"); global::android.view.GestureDetector.OnDoubleTapListener_._onDoubleTapEvent8730 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.OnDoubleTapListener_.staticClass, "onDoubleTapEvent", "(Landroid/view/MotionEvent;)Z"); } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.view.GestureDetector.OnGestureListener_))] public interface OnGestureListener : global::MonoJavaBridge.IJavaObject { void onLongPress(android.view.MotionEvent arg0); bool onSingleTapUp(android.view.MotionEvent arg0); bool onScroll(android.view.MotionEvent arg0, android.view.MotionEvent arg1, float arg2, float arg3); bool onFling(android.view.MotionEvent arg0, android.view.MotionEvent arg1, float arg2, float arg3); void onShowPress(android.view.MotionEvent arg0); bool onDown(android.view.MotionEvent arg0); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.view.GestureDetector.OnGestureListener))] public sealed partial class OnGestureListener_ : java.lang.Object, OnGestureListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static OnGestureListener_() { InitJNI(); } internal OnGestureListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _onLongPress8731; void android.view.GestureDetector.OnGestureListener.onLongPress(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_._onLongPress8731, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_.staticClass, global::android.view.GestureDetector.OnGestureListener_._onLongPress8731, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onSingleTapUp8732; bool android.view.GestureDetector.OnGestureListener.onSingleTapUp(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_._onSingleTapUp8732, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_.staticClass, global::android.view.GestureDetector.OnGestureListener_._onSingleTapUp8732, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onScroll8733; bool android.view.GestureDetector.OnGestureListener.onScroll(android.view.MotionEvent arg0, android.view.MotionEvent arg1, float arg2, float arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_._onScroll8733, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_.staticClass, global::android.view.GestureDetector.OnGestureListener_._onScroll8733, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _onFling8734; bool android.view.GestureDetector.OnGestureListener.onFling(android.view.MotionEvent arg0, android.view.MotionEvent arg1, float arg2, float arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_._onFling8734, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_.staticClass, global::android.view.GestureDetector.OnGestureListener_._onFling8734, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _onShowPress8735; void android.view.GestureDetector.OnGestureListener.onShowPress(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_._onShowPress8735, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_.staticClass, global::android.view.GestureDetector.OnGestureListener_._onShowPress8735, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onDown8736; bool android.view.GestureDetector.OnGestureListener.onDown(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_._onDown8736, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_.staticClass, global::android.view.GestureDetector.OnGestureListener_._onDown8736, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.GestureDetector.OnGestureListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/GestureDetector$OnGestureListener")); global::android.view.GestureDetector.OnGestureListener_._onLongPress8731 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.OnGestureListener_.staticClass, "onLongPress", "(Landroid/view/MotionEvent;)V"); global::android.view.GestureDetector.OnGestureListener_._onSingleTapUp8732 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.OnGestureListener_.staticClass, "onSingleTapUp", "(Landroid/view/MotionEvent;)Z"); global::android.view.GestureDetector.OnGestureListener_._onScroll8733 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.OnGestureListener_.staticClass, "onScroll", "(Landroid/view/MotionEvent;Landroid/view/MotionEvent;FF)Z"); global::android.view.GestureDetector.OnGestureListener_._onFling8734 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.OnGestureListener_.staticClass, "onFling", "(Landroid/view/MotionEvent;Landroid/view/MotionEvent;FF)Z"); global::android.view.GestureDetector.OnGestureListener_._onShowPress8735 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.OnGestureListener_.staticClass, "onShowPress", "(Landroid/view/MotionEvent;)V"); global::android.view.GestureDetector.OnGestureListener_._onDown8736 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.OnGestureListener_.staticClass, "onDown", "(Landroid/view/MotionEvent;)Z"); } } [global::MonoJavaBridge.JavaClass()] public partial class SimpleOnGestureListener : java.lang.Object, OnGestureListener, OnDoubleTapListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static SimpleOnGestureListener() { InitJNI(); } protected SimpleOnGestureListener(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _onLongPress8737; public virtual void onLongPress(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener._onLongPress8737, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, global::android.view.GestureDetector.SimpleOnGestureListener._onLongPress8737, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onSingleTapConfirmed8738; public virtual bool onSingleTapConfirmed(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener._onSingleTapConfirmed8738, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, global::android.view.GestureDetector.SimpleOnGestureListener._onSingleTapConfirmed8738, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onDoubleTap8739; public virtual bool onDoubleTap(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener._onDoubleTap8739, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, global::android.view.GestureDetector.SimpleOnGestureListener._onDoubleTap8739, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onDoubleTapEvent8740; public virtual bool onDoubleTapEvent(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener._onDoubleTapEvent8740, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, global::android.view.GestureDetector.SimpleOnGestureListener._onDoubleTapEvent8740, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onSingleTapUp8741; public virtual bool onSingleTapUp(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener._onSingleTapUp8741, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, global::android.view.GestureDetector.SimpleOnGestureListener._onSingleTapUp8741, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onScroll8742; public virtual bool onScroll(android.view.MotionEvent arg0, android.view.MotionEvent arg1, float arg2, float arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener._onScroll8742, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, global::android.view.GestureDetector.SimpleOnGestureListener._onScroll8742, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _onFling8743; public virtual bool onFling(android.view.MotionEvent arg0, android.view.MotionEvent arg1, float arg2, float arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener._onFling8743, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, global::android.view.GestureDetector.SimpleOnGestureListener._onFling8743, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _onShowPress8744; public virtual void onShowPress(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener._onShowPress8744, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, global::android.view.GestureDetector.SimpleOnGestureListener._onShowPress8744, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onDown8745; public virtual bool onDown(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener._onDown8745, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, global::android.view.GestureDetector.SimpleOnGestureListener._onDown8745, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _SimpleOnGestureListener8746; public SimpleOnGestureListener() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.GestureDetector.SimpleOnGestureListener.staticClass, global::android.view.GestureDetector.SimpleOnGestureListener._SimpleOnGestureListener8746); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.GestureDetector.SimpleOnGestureListener.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/GestureDetector$SimpleOnGestureListener")); global::android.view.GestureDetector.SimpleOnGestureListener._onLongPress8737 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onLongPress", "(Landroid/view/MotionEvent;)V"); global::android.view.GestureDetector.SimpleOnGestureListener._onSingleTapConfirmed8738 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onSingleTapConfirmed", "(Landroid/view/MotionEvent;)Z"); global::android.view.GestureDetector.SimpleOnGestureListener._onDoubleTap8739 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onDoubleTap", "(Landroid/view/MotionEvent;)Z"); global::android.view.GestureDetector.SimpleOnGestureListener._onDoubleTapEvent8740 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onDoubleTapEvent", "(Landroid/view/MotionEvent;)Z"); global::android.view.GestureDetector.SimpleOnGestureListener._onSingleTapUp8741 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onSingleTapUp", "(Landroid/view/MotionEvent;)Z"); global::android.view.GestureDetector.SimpleOnGestureListener._onScroll8742 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onScroll", "(Landroid/view/MotionEvent;Landroid/view/MotionEvent;FF)Z"); global::android.view.GestureDetector.SimpleOnGestureListener._onFling8743 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onFling", "(Landroid/view/MotionEvent;Landroid/view/MotionEvent;FF)Z"); global::android.view.GestureDetector.SimpleOnGestureListener._onShowPress8744 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onShowPress", "(Landroid/view/MotionEvent;)V"); global::android.view.GestureDetector.SimpleOnGestureListener._onDown8745 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onDown", "(Landroid/view/MotionEvent;)Z"); global::android.view.GestureDetector.SimpleOnGestureListener._SimpleOnGestureListener8746 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "<init>", "()V"); } } internal static global::MonoJavaBridge.MethodId _onTouchEvent8747; public virtual bool onTouchEvent(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector._onTouchEvent8747, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.staticClass, global::android.view.GestureDetector._onTouchEvent8747, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setOnDoubleTapListener8748; public virtual void setOnDoubleTapListener(android.view.GestureDetector.OnDoubleTapListener arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.view.GestureDetector._setOnDoubleTapListener8748, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.GestureDetector.staticClass, global::android.view.GestureDetector._setOnDoubleTapListener8748, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setIsLongpressEnabled8749; public virtual void setIsLongpressEnabled(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.view.GestureDetector._setIsLongpressEnabled8749, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.GestureDetector.staticClass, global::android.view.GestureDetector._setIsLongpressEnabled8749, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _isLongpressEnabled8750; public virtual bool isLongpressEnabled() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector._isLongpressEnabled8750); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.staticClass, global::android.view.GestureDetector._isLongpressEnabled8750); } internal static global::MonoJavaBridge.MethodId _GestureDetector8751; public GestureDetector(android.view.GestureDetector.OnGestureListener arg0, android.os.Handler arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.GestureDetector.staticClass, global::android.view.GestureDetector._GestureDetector8751, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _GestureDetector8752; public GestureDetector(android.view.GestureDetector.OnGestureListener arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.GestureDetector.staticClass, global::android.view.GestureDetector._GestureDetector8752, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _GestureDetector8753; public GestureDetector(android.content.Context arg0, android.view.GestureDetector.OnGestureListener arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.GestureDetector.staticClass, global::android.view.GestureDetector._GestureDetector8753, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _GestureDetector8754; public GestureDetector(android.content.Context arg0, android.view.GestureDetector.OnGestureListener arg1, android.os.Handler arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.GestureDetector.staticClass, global::android.view.GestureDetector._GestureDetector8754, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _GestureDetector8755; public GestureDetector(android.content.Context arg0, android.view.GestureDetector.OnGestureListener arg1, android.os.Handler arg2, bool arg3) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.GestureDetector.staticClass, global::android.view.GestureDetector._GestureDetector8755, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.GestureDetector.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/GestureDetector")); global::android.view.GestureDetector._onTouchEvent8747 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.staticClass, "onTouchEvent", "(Landroid/view/MotionEvent;)Z"); global::android.view.GestureDetector._setOnDoubleTapListener8748 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.staticClass, "setOnDoubleTapListener", "(Landroid/view/GestureDetector$OnDoubleTapListener;)V"); global::android.view.GestureDetector._setIsLongpressEnabled8749 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.staticClass, "setIsLongpressEnabled", "(Z)V"); global::android.view.GestureDetector._isLongpressEnabled8750 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.staticClass, "isLongpressEnabled", "()Z"); global::android.view.GestureDetector._GestureDetector8751 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.staticClass, "<init>", "(Landroid/view/GestureDetector$OnGestureListener;Landroid/os/Handler;)V"); global::android.view.GestureDetector._GestureDetector8752 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.staticClass, "<init>", "(Landroid/view/GestureDetector$OnGestureListener;)V"); global::android.view.GestureDetector._GestureDetector8753 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.staticClass, "<init>", "(Landroid/content/Context;Landroid/view/GestureDetector$OnGestureListener;)V"); global::android.view.GestureDetector._GestureDetector8754 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.staticClass, "<init>", "(Landroid/content/Context;Landroid/view/GestureDetector$OnGestureListener;Landroid/os/Handler;)V"); global::android.view.GestureDetector._GestureDetector8755 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.staticClass, "<init>", "(Landroid/content/Context;Landroid/view/GestureDetector$OnGestureListener;Landroid/os/Handler;Z)V"); } } }
using System; using System.Collections; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.CryptoPro; using Org.BouncyCastle.Asn1.Nist; using Org.BouncyCastle.Asn1.Oiw; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Asn1.TeleTrust; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities.Collections; using Org.BouncyCastle.X509; using Org.BouncyCastle.X509.Store; namespace Org.BouncyCastle.Cms { public class CmsSignedGenerator { /** * Default type for the signed data. */ public static readonly string Data = PkcsObjectIdentifiers.Data.Id; public static readonly string DigestSha1 = OiwObjectIdentifiers.IdSha1.Id; public static readonly string DigestSha224 = NistObjectIdentifiers.IdSha224.Id; public static readonly string DigestSha256 = NistObjectIdentifiers.IdSha256.Id; public static readonly string DigestSha384 = NistObjectIdentifiers.IdSha384.Id; public static readonly string DigestSha512 = NistObjectIdentifiers.IdSha512.Id; public static readonly string DigestMD5 = PkcsObjectIdentifiers.MD5.Id; public static readonly string DigestGost3411 = CryptoProObjectIdentifiers.GostR3411.Id; public static readonly string DigestRipeMD128 = TeleTrusTObjectIdentifiers.RipeMD128.Id; public static readonly string DigestRipeMD160 = TeleTrusTObjectIdentifiers.RipeMD160.Id; public static readonly string DigestRipeMD256 = TeleTrusTObjectIdentifiers.RipeMD256.Id; public static readonly string EncryptionRsa = PkcsObjectIdentifiers.RsaEncryption.Id; public static readonly string EncryptionDsa = X9ObjectIdentifiers.IdDsaWithSha1.Id; public static readonly string EncryptionECDsa = X9ObjectIdentifiers.ECDsaWithSha1.Id; public static readonly string EncryptionRsaPss = PkcsObjectIdentifiers.IdRsassaPss.Id; public static readonly string EncryptionGost3410 = CryptoProObjectIdentifiers.GostR3410x94.Id; public static readonly string EncryptionECGost3410 = CryptoProObjectIdentifiers.GostR3410x2001.Id; private static readonly string EncryptionECDsaWithSha1 = X9ObjectIdentifiers.ECDsaWithSha1.Id; private static readonly string EncryptionECDsaWithSha224 = X9ObjectIdentifiers.ECDsaWithSha224.Id; private static readonly string EncryptionECDsaWithSha256 = X9ObjectIdentifiers.ECDsaWithSha256.Id; private static readonly string EncryptionECDsaWithSha384 = X9ObjectIdentifiers.ECDsaWithSha384.Id; private static readonly string EncryptionECDsaWithSha512 = X9ObjectIdentifiers.ECDsaWithSha512.Id; private static readonly ISet noParams = new HashSet(); private static readonly Hashtable ecAlgorithms = new Hashtable(); static CmsSignedGenerator() { noParams.Add(EncryptionDsa); // noParams.Add(EncryptionECDsa); noParams.Add(EncryptionECDsaWithSha1); noParams.Add(EncryptionECDsaWithSha224); noParams.Add(EncryptionECDsaWithSha256); noParams.Add(EncryptionECDsaWithSha384); noParams.Add(EncryptionECDsaWithSha512); ecAlgorithms.Add(DigestSha1, EncryptionECDsaWithSha1); ecAlgorithms.Add(DigestSha224, EncryptionECDsaWithSha224); ecAlgorithms.Add(DigestSha256, EncryptionECDsaWithSha256); ecAlgorithms.Add(DigestSha384, EncryptionECDsaWithSha384); ecAlgorithms.Add(DigestSha512, EncryptionECDsaWithSha512); } internal ArrayList _certs = new ArrayList(); internal ArrayList _crls = new ArrayList(); internal ArrayList _signers = new ArrayList(); internal IDictionary _digests = new Hashtable(); protected readonly SecureRandom rand; protected CmsSignedGenerator() : this(new SecureRandom()) { } /// <summary>Constructor allowing specific source of randomness</summary> /// <param name="rand">Instance of <c>SecureRandom</c> to use.</param> protected CmsSignedGenerator( SecureRandom rand) { this.rand = rand; } protected string GetEncOid( AsymmetricKeyParameter key, string digestOID) { string encOID = null; if (key is RsaKeyParameters) { if (!((RsaKeyParameters) key).IsPrivate) throw new ArgumentException("Expected RSA private key"); encOID = EncryptionRsa; } else if (key is DsaPrivateKeyParameters) { if (!digestOID.Equals(DigestSha1)) throw new ArgumentException("can't mix DSA with anything but SHA1"); encOID = EncryptionDsa; } else if (key is ECPrivateKeyParameters) { ECPrivateKeyParameters ecPrivKey = (ECPrivateKeyParameters) key; string algName = ecPrivKey.AlgorithmName; if (algName == "ECGOST3410") { encOID = EncryptionECGost3410; } else { // TODO Should we insist on algName being one of "EC" or "ECDSA", as Java does? encOID = (string) ecAlgorithms[digestOID]; if (encOID == null) throw new ArgumentException("can't mix ECDSA with anything but SHA family digests"); } } else if (key is Gost3410PrivateKeyParameters) { encOID = EncryptionGost3410; } else { throw new ArgumentException("Unknown algorithm in CmsSignedGenerator.GetEncOid"); } return encOID; } internal static AlgorithmIdentifier GetEncAlgorithmIdentifier( string encOid) { if (noParams.Contains(encOid)) { return new AlgorithmIdentifier(new DerObjectIdentifier(encOid)); } return new AlgorithmIdentifier(new DerObjectIdentifier(encOid), DerNull.Instance); } internal protected virtual IDictionary GetBaseParameters( DerObjectIdentifier contentType, AlgorithmIdentifier digAlgId, byte[] hash) { IDictionary param = new Hashtable(); param[CmsAttributeTableParameter.ContentType] = contentType; param[CmsAttributeTableParameter.DigestAlgorithmIdentifier] = digAlgId; if (hash != null) { param[CmsAttributeTableParameter.Digest] = hash.Clone(); } return param; } internal protected virtual Asn1Set GetAttributeSet( Asn1.Cms.AttributeTable attr) { return attr == null ? null : new DerSet(attr.ToAsn1EncodableVector()); } public void AddCertificates( IX509Store certStore) { _certs.AddRange(CmsUtilities.GetCertificatesFromStore(certStore)); } public void AddCrls( IX509Store crlStore) { _crls.AddRange(CmsUtilities.GetCrlsFromStore(crlStore)); } /** * Add the attribute certificates contained in the passed in store to the * generator. * * @param store a store of Version 2 attribute certificates * @throws CmsException if an error occurse processing the store. */ public void AddAttributeCertificates( IX509Store store) { try { foreach (IX509AttributeCertificate attrCert in store.GetMatches(null)) { _certs.Add(new DerTaggedObject(false, 2, AttributeCertificate.GetInstance(Asn1Object.FromByteArray(attrCert.GetEncoded())))); } } catch (Exception e) { throw new CmsException("error processing attribute certs", e); } } /** * Add a store of precalculated signers to the generator. * * @param signerStore store of signers */ public void AddSigners( SignerInformationStore signerStore) { foreach (SignerInformation o in signerStore.GetSigners()) { _signers.Add(o); AddSignerCallback(o); } } /** * Return a map of oids and byte arrays representing the digests calculated on the content during * the last generate. * * @return a map of oids (as String objects) and byte[] representing digests. */ public IDictionary GetGeneratedDigests() { return new Hashtable(_digests); } internal virtual void AddSignerCallback( SignerInformation si) { } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Reflection; using System.Text.RegularExpressions; using System.Xml.Serialization; using log4net; using Nwc.XmlRpc; using OpenMetaverse; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Communications.Clients; namespace OpenSim.Region.Communications.OGS1 { public class OGS1UserDataPlugin : IUserDataPlugin { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected CommunicationsManager m_commsManager; public OGS1UserDataPlugin() { } public OGS1UserDataPlugin(CommunicationsManager commsManager) { m_log.DebugFormat("[OGS1 USER SERVICES]: {0} initialized", Name); m_commsManager = commsManager; } public string Version { get { return "0.1"; } } public string Name { get { return "Open Grid Services 1 (OGS1) User Data Plugin"; } } public void Initialise() {} public void Initialise(string connect) {} public void Dispose() {} // Arguably the presence of these means that IUserDataPlugin could be fissioned public UserAgentData GetUserAgent(string name) { return null; } public UserAgentData GetAgentByName(string name) { return null; } public UserAgentData GetAgentByName(string fname, string lname) { return null; } public void StoreWebLoginKey(UUID agentID, UUID webLoginKey) {} public void AddNewUserProfile(UserProfileData user) {} public void AddNewUserAgent(UserAgentData agent) {} public bool MoneyTransferRequest(UUID from, UUID to, uint amount) { return false; } public bool InventoryTransferRequest(UUID from, UUID to, UUID inventory) { return false; } public void ResetAttachments(UUID userID) {} public void LogoutUsers(UUID regionID) {} public virtual void AddTemporaryUserProfile(UserProfileData userProfile) { // Not interested } public UserProfileData GetUserByUri(Uri uri) { WebRequest request = WebRequest.Create(uri); WebResponse webResponse = request.GetResponse(); XmlSerializer deserializer = new XmlSerializer(typeof(XmlRpcResponse)); XmlRpcResponse xmlRpcResponse = (XmlRpcResponse)deserializer.Deserialize(webResponse.GetResponseStream()); Hashtable respData = (Hashtable)xmlRpcResponse.Value; return ConvertXMLRPCDataToUserProfile(respData); } // public Uri GetUserUri(UserProfileData userProfile) // { // throw new NotImplementedException(); // } public virtual UserAgentData GetAgentByUUID(UUID userId) { try { Hashtable param = new Hashtable(); param["avatar_uuid"] = userId.ToString(); IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("get_agent_by_uuid", parameters); XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 6000); Hashtable respData = (Hashtable)resp.Value; if (respData.Contains("error_type")) { //m_log.Warn("[GRID]: " + // "Error sent by user server when trying to get agent: (" + // (string) respData["error_type"] + // "): " + (string)respData["error_desc"]); return null; } UUID sessionid = UUID.Zero; UserAgentData userAgent = new UserAgentData(); userAgent.Handle = Convert.ToUInt64((string)respData["handle"]); UUID.TryParse((string)respData["sessionid"], out sessionid); userAgent.SessionID = sessionid; if ((string)respData["agent_online"] == "TRUE") { userAgent.AgentOnline = true; } else { userAgent.AgentOnline = false; } return userAgent; } catch (Exception e) { m_log.ErrorFormat( "[OGS1 USER SERVICES]: Error when trying to fetch agent data by uuid from remote user server: {0}", e); } return null; } public virtual UserProfileData GetUserByName(string firstName, string lastName) { return GetUserProfile(firstName + " " + lastName); } public virtual List<AvatarPickerAvatar> GeneratePickerResults(UUID queryID, string query) { List<AvatarPickerAvatar> pickerlist = new List<AvatarPickerAvatar>(); Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9 ]"); try { Hashtable param = new Hashtable(); param["queryid"] = (string)queryID.ToString(); param["avquery"] = objAlphaNumericPattern.Replace(query, String.Empty); IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("get_avatar_picker_avatar", parameters); XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 3000); Hashtable respData = (Hashtable)resp.Value; pickerlist = ConvertXMLRPCDataToAvatarPickerList(queryID, respData); } catch (WebException e) { m_log.Warn("[OGS1 USER SERVICES]: Error when trying to fetch Avatar Picker Response: " + e.Message); // Return Empty picker list (no results) } return pickerlist; } /// <summary> /// Get a user profile from the user server /// </summary> /// <param name="avatarID"></param> /// <returns>null if the request fails</returns> protected virtual UserProfileData GetUserProfile(string name) { try { Hashtable param = new Hashtable(); param["avatar_name"] = name; IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("get_user_by_name", parameters); XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 30000); Hashtable respData = (Hashtable)resp.Value; return ConvertXMLRPCDataToUserProfile(respData); } catch (WebException e) { m_log.ErrorFormat( "[OGS1 USER SERVICES]: Error when trying to fetch profile data by name from remote user server: {0}", e); } return null; } /// <summary> /// Get a user profile from the user server /// </summary> /// <param name="avatarID"></param> /// <returns>null if the request fails</returns> public virtual UserProfileData GetUserByUUID(UUID avatarID) { try { Hashtable param = new Hashtable(); param["avatar_uuid"] = avatarID.ToString(); IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("get_user_by_uuid", parameters); XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 30000); Hashtable respData = (Hashtable)resp.Value; return ConvertXMLRPCDataToUserProfile(respData); } catch (Exception e) { m_log.ErrorFormat( "[OGS1 USER SERVICES]: Error when trying to fetch profile data by uuid from remote user server: {0}", e); } return null; } public virtual bool UpdateUserProfile(UserProfileData userProfile) { m_log.Debug("[OGS1 USER SERVICES]: Asking UserServer to update profile."); Hashtable param = new Hashtable(); param["avatar_uuid"] = userProfile.ID.ToString(); //param["AllowPublish"] = userProfile.ToString(); param["FLImageID"] = userProfile.FirstLifeImage.ToString(); param["ImageID"] = userProfile.Image.ToString(); //param["MaturePublish"] = MaturePublish.ToString(); param["AboutText"] = userProfile.AboutText; param["FLAboutText"] = userProfile.FirstLifeAboutText; //param["ProfileURL"] = userProfile.ProfileURL.ToString(); param["home_region"] = userProfile.HomeRegion.ToString(); param["home_region_id"] = userProfile.HomeRegionID.ToString(); param["home_pos_x"] = userProfile.HomeLocationX.ToString(); param["home_pos_y"] = userProfile.HomeLocationY.ToString(); param["home_pos_z"] = userProfile.HomeLocationZ.ToString(); param["home_look_x"] = userProfile.HomeLookAtX.ToString(); param["home_look_y"] = userProfile.HomeLookAtY.ToString(); param["home_look_z"] = userProfile.HomeLookAtZ.ToString(); param["user_flags"] = userProfile.UserFlags.ToString(); param["god_level"] = userProfile.GodLevel.ToString(); param["custom_type"] = userProfile.CustomType.ToString(); param["partner"] = userProfile.Partner.ToString(); IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("update_user_profile", parameters); XmlRpcResponse resp = req.Send(GetUserServerURL(userProfile.ID), 3000); Hashtable respData = (Hashtable)resp.Value; if (respData != null) { if (respData.Contains("returnString")) { if (((string)respData["returnString"]).ToUpper() != "TRUE") { m_log.Warn("[GRID]: Unable to update user profile, User Server Reported an issue"); return false; } } else { m_log.Warn("[GRID]: Unable to update user profile, UserServer didn't understand me!"); return false; } } else { m_log.Warn("[GRID]: Unable to update user profile, UserServer didn't understand me!"); return false; } return true; } /// <summary> /// Adds a new friend to the database for XUser /// </summary> /// <param name="friendlistowner">The agent that who's friends list is being added to</param> /// <param name="friend">The agent that being added to the friends list of the friends list owner</param> /// <param name="perms">A uint bit vector for set perms that the friend being added has; 0 = none, 1=This friend can see when they sign on, 2 = map, 4 edit objects </param> public virtual void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms) { try { Hashtable param = new Hashtable(); param["ownerID"] = friendlistowner.Guid.ToString(); param["friendID"] = friend.Guid.ToString(); param["friendPerms"] = perms.ToString(); IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("add_new_user_friend", parameters); XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 3000); Hashtable respData = (Hashtable)resp.Value; if (respData != null) { if (respData.Contains("returnString")) { if ((string)respData["returnString"] == "TRUE") { } else { m_log.Warn("[GRID]: Unable to add new friend, User Server Reported an issue"); } } else { m_log.Warn("[GRID]: Unable to add new friend, UserServer didn't understand me!"); } } else { m_log.Warn("[GRID]: Unable to add new friend, UserServer didn't understand me!"); } } catch (WebException e) { m_log.Warn("[GRID]: Error when trying to AddNewUserFriend: " + e.Message); } } /// <summary> /// Delete friend on friendlistowner's friendlist. /// </summary> /// <param name="friendlistowner">The agent that who's friends list is being updated</param> /// <param name="friend">The Ex-friend agent</param> public virtual void RemoveUserFriend(UUID friendlistowner, UUID friend) { try { Hashtable param = new Hashtable(); param["ownerID"] = friendlistowner.Guid.ToString(); param["friendID"] = friend.Guid.ToString(); IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("remove_user_friend", parameters); XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 3000); Hashtable respData = (Hashtable)resp.Value; if (respData != null) { if (respData.Contains("returnString")) { if ((string)respData["returnString"] == "TRUE") { } else { m_log.Warn("[GRID]: Unable to remove friend, User Server Reported an issue"); } } else { m_log.Warn("[GRID]: Unable to remove friend, UserServer didn't understand me!"); } } else { m_log.Warn("[GRID]: Unable to remove friend, UserServer didn't understand me!"); } } catch (WebException e) { m_log.Warn("[GRID]: Error when trying to RemoveUserFriend: " + e.Message); } } /// <summary> /// Update permissions for friend on friendlistowner's friendlist. /// </summary> /// <param name="friendlistowner">The agent that who's friends list is being updated</param> /// <param name="friend">The agent that is getting or loosing permissions</param> /// <param name="perms">A uint bit vector for set perms that the friend being added has; 0 = none, 1=This friend can see when they sign on, 2 = map, 4 edit objects </param> public virtual void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms) { try { Hashtable param = new Hashtable(); param["ownerID"] = friendlistowner.Guid.ToString(); param["friendID"] = friend.Guid.ToString(); param["friendPerms"] = perms.ToString(); IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("update_user_friend_perms", parameters); XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 3000); Hashtable respData = (Hashtable)resp.Value; if (respData != null) { if (respData.Contains("returnString")) { if ((string)respData["returnString"] == "TRUE") { } else { m_log.Warn("[GRID]: Unable to update_user_friend_perms, User Server Reported an issue"); } } else { m_log.Warn("[GRID]: Unable to update_user_friend_perms, UserServer didn't understand me!"); } } else { m_log.Warn("[GRID]: Unable to update_user_friend_perms, UserServer didn't understand me!"); } } catch (WebException e) { m_log.Warn("[GRID]: Error when trying to update_user_friend_perms: " + e.Message); } } /// <summary> /// Returns a list of FriendsListItems that describe the friends and permissions in the friend relationship for UUID friendslistowner /// </summary> /// <param name="friendlistowner">The agent that we're retreiving the friends Data.</param> public virtual List<FriendListItem> GetUserFriendList(UUID friendlistowner) { List<FriendListItem> buddylist = new List<FriendListItem>(); try { Hashtable param = new Hashtable(); param["ownerID"] = friendlistowner.Guid.ToString(); IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("get_user_friend_list", parameters); XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 8000); Hashtable respData = (Hashtable)resp.Value; if (respData != null && respData.Contains("avcount")) { buddylist = ConvertXMLRPCDataToFriendListItemList(respData); } } catch (WebException e) { m_log.Warn("[OGS1 USER SERVICES]: Error when trying to fetch Avatar's friends list: " + e.Message); // Return Empty list (no friends) } return buddylist; } public virtual Dictionary<UUID, FriendRegionInfo> GetFriendRegionInfos(List<UUID> uuids) { Dictionary<UUID, FriendRegionInfo> result = new Dictionary<UUID, FriendRegionInfo>(); // ask MessageServer about the current on-/offline status and regions the friends are in ArrayList parameters = new ArrayList(); Hashtable map = new Hashtable(); ArrayList list = new ArrayList(); foreach (UUID uuid in uuids) { list.Add(uuid.ToString()); list.Add(uuid.ToString()); } map["uuids"] = list; map["recv_key"] = m_commsManager.NetworkServersInfo.UserRecvKey; map["send_key"] = m_commsManager.NetworkServersInfo.UserSendKey; parameters.Add(map); try { XmlRpcRequest req = new XmlRpcRequest("get_presence_info_bulk", parameters); XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.MessagingURL, 8000); Hashtable respData = resp != null ? (Hashtable)resp.Value : null; if (respData == null || respData.ContainsKey("faultMessage")) { m_log.WarnFormat("[OGS1 USER SERVICES]: Contacting MessagingServer about user-regions resulted in error: {0}", respData == null ? "<unknown error>" : respData["faultMessage"]); } else if (!respData.ContainsKey("count")) { m_log.WarnFormat("[OGS1 USER SERVICES]: Wrong format in response for MessagingServer request get_presence_info_bulk: missing 'count' field"); } else { int count = (int)respData["count"]; m_log.DebugFormat("[OGS1 USER SERVICES]: Request returned {0} results.", count); for (int i = 0; i < count; ++i) { if (respData.ContainsKey("uuid_" + i) && respData.ContainsKey("isOnline_" + i) && respData.ContainsKey("regionHandle_" + i)) { UUID uuid; if (UUID.TryParse((string)respData["uuid_" + i], out uuid)) { FriendRegionInfo info = new FriendRegionInfo(); info.isOnline = (bool)respData["isOnline_" + i]; if (info.isOnline) { // TODO remove this after the next protocol update (say, r7800?) info.regionHandle = Convert.ToUInt64(respData["regionHandle_" + i]); // accept missing id if (respData.ContainsKey("regionID_" + i)) UUID.TryParse((string)respData["regionID_" + i], out info.regionID); } result.Add(uuid, info); } } else { m_log.WarnFormat("[OGS1 USER SERVICES]: Response to get_presence_info_bulk contained an error in entry {0}", i); } } } } catch (WebException e) { m_log.ErrorFormat("[OGS1 USER SERVICES]: Network problems when trying to fetch friend infos: {0}", e.Message); } m_log.DebugFormat("[OGS1 USER SERVICES]: Returning {0} entries", result.Count); return result; } public virtual AvatarAppearance GetUserAppearance(UUID user) { AvatarAppearance appearance = null; try { Hashtable param = new Hashtable(); param["owner"] = user.ToString(); IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("get_avatar_appearance", parameters); XmlRpcResponse resp = req.Send(GetUserServerURL(user), 8000); Hashtable respData = (Hashtable)resp.Value; return ConvertXMLRPCDataToAvatarAppearance(respData); } catch (WebException e) { m_log.ErrorFormat("[OGS1 USER SERVICES]: Network problems when trying to fetch appearance for avatar {0}, {1}", user, e.Message); } return appearance; } public virtual void UpdateUserAppearance(UUID user, AvatarAppearance appearance) { try { Hashtable param = appearance.ToHashTable(); param["owner"] = user.ToString(); IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("update_avatar_appearance", parameters); XmlRpcResponse resp = req.Send(GetUserServerURL(user), 8000); Hashtable respData = (Hashtable)resp.Value; if (respData != null) { if (respData.Contains("returnString")) { if ((string)respData["returnString"] == "TRUE") { m_log.DebugFormat("[OGS1 USER SERVICES]: Updated user appearance in {0}", GetUserServerURL(user)); } else { m_log.Warn("[GRID]: Unable to update_user_appearance, User Server Reported an issue"); } } else { m_log.Warn("[GRID]: Unable to update_user_appearance, UserServer didn't understand me!"); } } else { m_log.Warn("[GRID]: Unable to update_user_appearance, UserServer didn't understand me!"); } } catch (WebException e) { m_log.WarnFormat("[OGS1 USER SERVICES]: Error when trying to update Avatar's appearance in {0}: {1}", GetUserServerURL(user), e.Message); // Return Empty list (no friends) } } protected virtual string GetUserServerURL(UUID userID) { return m_commsManager.NetworkServersInfo.UserURL; } protected UserProfileData ConvertXMLRPCDataToUserProfile(Hashtable data) { if (data.Contains("error_type")) { //m_log.Warn("[GRID]: " + // "Error sent by user server when trying to get user profile: (" + // data["error_type"] + // "): " + data["error_desc"]); return null; } UserProfileData userData = new UserProfileData(); userData.FirstName = (string)data["firstname"]; userData.SurName = (string)data["lastname"]; if (data["email"] != null) userData.Email = (string)data["email"]; userData.ID = new UUID((string)data["uuid"]); userData.Created = Convert.ToInt32(data["profile_created"]); if (data.Contains("server_inventory") && data["server_inventory"] != null) userData.UserInventoryURI = (string)data["server_inventory"]; if (data.Contains("server_asset") && data["server_asset"] != null) userData.UserAssetURI = (string)data["server_asset"]; if (data.Contains("profile_firstlife_about") && data["profile_firstlife_about"] != null) userData.FirstLifeAboutText = (string)data["profile_firstlife_about"]; userData.FirstLifeImage = new UUID((string)data["profile_firstlife_image"]); userData.CanDoMask = Convert.ToUInt32((string)data["profile_can_do"]); userData.WantDoMask = Convert.ToUInt32(data["profile_want_do"]); userData.AboutText = (string)data["profile_about"]; userData.Image = new UUID((string)data["profile_image"]); userData.LastLogin = Convert.ToInt32((string)data["profile_lastlogin"]); userData.HomeRegion = Convert.ToUInt64((string)data["home_region"]); if (data.Contains("home_region_id")) userData.HomeRegionID = new UUID((string)data["home_region_id"]); else userData.HomeRegionID = UUID.Zero; userData.HomeLocation = new Vector3((float)Convert.ToDecimal((string)data["home_coordinates_x"], Culture.NumberFormatInfo), (float)Convert.ToDecimal((string)data["home_coordinates_y"], Culture.NumberFormatInfo), (float)Convert.ToDecimal((string)data["home_coordinates_z"], Culture.NumberFormatInfo)); userData.HomeLookAt = new Vector3((float)Convert.ToDecimal((string)data["home_look_x"], Culture.NumberFormatInfo), (float)Convert.ToDecimal((string)data["home_look_y"], Culture.NumberFormatInfo), (float)Convert.ToDecimal((string)data["home_look_z"], Culture.NumberFormatInfo)); if (data.Contains("user_flags")) userData.UserFlags = Convert.ToInt32((string)data["user_flags"]); if (data.Contains("god_level")) userData.GodLevel = Convert.ToInt32((string)data["god_level"]); if (data.Contains("custom_type")) userData.CustomType = (string)data["custom_type"]; else userData.CustomType = ""; if (userData.CustomType == null) userData.CustomType = ""; if (data.Contains("partner")) userData.Partner = new UUID((string)data["partner"]); else userData.Partner = UUID.Zero; return userData; } protected AvatarAppearance ConvertXMLRPCDataToAvatarAppearance(Hashtable data) { if (data != null) { if (data.Contains("error_type")) { m_log.Warn("[GRID]: " + "Error sent by user server when trying to get user appearance: (" + data["error_type"] + "): " + data["error_desc"]); return null; } else { return new AvatarAppearance(data); } } else { m_log.Error("[GRID]: The avatar appearance is null, something bad happenend"); return null; } } protected List<AvatarPickerAvatar> ConvertXMLRPCDataToAvatarPickerList(UUID queryID, Hashtable data) { List<AvatarPickerAvatar> pickerlist = new List<AvatarPickerAvatar>(); int pickercount = Convert.ToInt32((string)data["avcount"]); UUID respqueryID = new UUID((string)data["queryid"]); if (queryID == respqueryID) { for (int i = 0; i < pickercount; i++) { AvatarPickerAvatar apicker = new AvatarPickerAvatar(); UUID avatarID = new UUID((string)data["avatarid" + i.ToString()]); string firstname = (string)data["firstname" + i.ToString()]; string lastname = (string)data["lastname" + i.ToString()]; apicker.AvatarID = avatarID; apicker.firstName = firstname; apicker.lastName = lastname; pickerlist.Add(apicker); } } else { m_log.Warn("[OGS1 USER SERVICES]: Got invalid queryID from userServer"); } return pickerlist; } protected List<FriendListItem> ConvertXMLRPCDataToFriendListItemList(Hashtable data) { List<FriendListItem> buddylist = new List<FriendListItem>(); int buddycount = Convert.ToInt32((string)data["avcount"]); for (int i = 0; i < buddycount; i++) { FriendListItem buddylistitem = new FriendListItem(); buddylistitem.FriendListOwner = new UUID((string)data["ownerID" + i.ToString()]); buddylistitem.Friend = new UUID((string)data["friendID" + i.ToString()]); buddylistitem.FriendListOwnerPerms = (uint)Convert.ToInt32((string)data["ownerPerms" + i.ToString()]); buddylistitem.FriendPerms = (uint)Convert.ToInt32((string)data["friendPerms" + i.ToString()]); buddylist.Add(buddylistitem); } return buddylist; } } }
using System; using UnityEngine; using System.Collections.Generic; using MeshSplitting.SplitterMath; namespace MeshSplitting.MeshTools { public class MeshSplitterConvex : IMeshSplitter { public bool UseCapUV = false; public bool CustomUV = false; public Vector2 CapUVMin = Vector2.zero; public Vector2 CapUVMax = Vector2.one; protected MeshContainer _mesh; protected PlaneMath _splitPlane; protected Quaternion _splitRotation; private Quaternion _ownRotation; public List<int> capInds; public MeshSplitterConvex(MeshContainer meshContainer, PlaneMath splitPlane, Quaternion splitRotation) { _mesh = meshContainer; _splitPlane = splitPlane; _splitRotation = splitRotation; _ownRotation = meshContainer.transform.rotation; capInds = new List<int>(meshContainer.vertexCount / 10); } #if UNITY_EDITOR [NonSerialized] public bool ShowDebug = false; public void DebugDraw(bool debug) { ShowDebug = debug; } #endif public void SetCapUV(bool useCapUV, bool customUV, Vector2 uvMin, Vector2 uvMax) { UseCapUV = useCapUV; CustomUV = customUV; CapUVMin = uvMin; CapUVMax = uvMax; } #region Mesh Split private int[] triIndicies = new int[3]; private float[] lineLerp = new float[3]; private bool[] lineHit = new bool[3]; private Vector3[] triVertices = new Vector3[3]; public void MeshSplit() { int triCount = _mesh.triangles.Length - 2; for (int triOffset = 0; triOffset < triCount; triOffset += 3) { triIndicies[0] = _mesh.triangles[triOffset]; triIndicies[1] = _mesh.triangles[1 + triOffset]; triIndicies[2] = _mesh.triangles[2 + triOffset]; lineLerp[0] = _splitPlane.LineIntersect(_mesh.wsVerts[triIndicies[0]], _mesh.wsVerts[triIndicies[1]]); lineLerp[1] = _splitPlane.LineIntersect(_mesh.wsVerts[triIndicies[1]], _mesh.wsVerts[triIndicies[2]]); lineLerp[2] = _splitPlane.LineIntersect(_mesh.wsVerts[triIndicies[2]], _mesh.wsVerts[triIndicies[0]]); lineHit[0] = lineLerp[0] > 0f && lineLerp[0] < 1f; lineHit[1] = lineLerp[1] > 0f && lineLerp[1] < 1f; lineHit[2] = lineLerp[2] > 0f && lineLerp[2] < 1f; if (lineHit[0] || lineHit[1] || lineHit[2]) { if (lineHit[0] && lineHit[1]) { // tri cut at 0 & 1 SplitTriangle(0); } else if (lineHit[1] && lineHit[2]) { // tri cut at 1 & 2 SplitTriangle(1); } else if (lineHit[0] && lineHit[2]) { // tri cut at 2 & 0 SplitTriangle(2); } else if (lineHit[1]) { // try split between side 1 and vertex 0 SplitTriangleAlternative(0); } else if (lineHit[2]) { // try split between side 2 and vertex 1 SplitTriangleAlternative(1); } else { // try split between side 0 and vertex 2 SplitTriangleAlternative(2); } } else { // tri uncut triVertices[0] = _mesh.wsVerts[triIndicies[0]]; triVertices[1] = _mesh.wsVerts[triIndicies[1]]; triVertices[2] = _mesh.wsVerts[triIndicies[2]]; if (SplitterHelper.GetPlaneSide(_splitPlane, triVertices) > 0f) { _mesh.trisUp.Add(triIndicies[0]); _mesh.trisUp.Add(triIndicies[1]); _mesh.trisUp.Add(triIndicies[2]); #if UNITY_EDITOR if (ShowDebug) DrawDebugTri(triIndicies, Color.cyan); #endif } else { _mesh.trisDown.Add(triIndicies[0]); _mesh.trisDown.Add(triIndicies[1]); _mesh.trisDown.Add(triIndicies[2]); #if UNITY_EDITOR if (ShowDebug) DrawDebugTri(triIndicies, Color.magenta); #endif } } } } private int[] smallTri = new int[3]; private int[] bigTri = new int[6]; private void SplitTriangle(int offset) { int i0 = offset % 3; int i1 = (1 + offset) % 3; int i2 = (2 + offset) % 3; int indexHit0 = _mesh.AddLerpVertex(triIndicies[i0], triIndicies[i1], lineLerp[i0]); int indexHit1 = _mesh.AddLerpVertex(triIndicies[i1], triIndicies[i2], lineLerp[i1]); AddCapIndex(indexHit0); AddCapIndex(indexHit1); smallTri[0] = indexHit0; smallTri[1] = triIndicies[i1]; smallTri[2] = indexHit1; bigTri[0] = triIndicies[i0]; bigTri[1] = indexHit0; bigTri[2] = indexHit1; bigTri[3] = triIndicies[i0]; bigTri[4] = indexHit1; bigTri[5] = triIndicies[i2]; if (_splitPlane.PointSide(_mesh.wsVerts[triIndicies[i1]]) > 0f) { _mesh.trisUp.Add(smallTri[0]); _mesh.trisUp.Add(smallTri[1]); _mesh.trisUp.Add(smallTri[2]); _mesh.trisDown.Add(bigTri[0]); _mesh.trisDown.Add(bigTri[1]); _mesh.trisDown.Add(bigTri[2]); _mesh.trisDown.Add(bigTri[3]); _mesh.trisDown.Add(bigTri[4]); _mesh.trisDown.Add(bigTri[5]); #if UNITY_EDITOR if (ShowDebug) { DrawDebugTri(smallTri, Color.cyan); DrawDebugTriDouble(bigTri, Color.magenta); } #endif } else { _mesh.trisDown.Add(smallTri[0]); _mesh.trisDown.Add(smallTri[1]); _mesh.trisDown.Add(smallTri[2]); _mesh.trisUp.Add(bigTri[0]); _mesh.trisUp.Add(bigTri[1]); _mesh.trisUp.Add(bigTri[2]); _mesh.trisUp.Add(bigTri[3]); _mesh.trisUp.Add(bigTri[4]); _mesh.trisUp.Add(bigTri[5]); #if UNITY_EDITOR if (ShowDebug) { DrawDebugTri(smallTri, Color.magenta); DrawDebugTriDouble(bigTri, Color.cyan); } #endif } } private void SplitTriangleAlternative(int offset) { Debug.Log("alt tri split"); int i0 = offset % 3; int i1 = (1 + offset) % 3; int i2 = (2 + offset) % 3; int indexHit = _mesh.AddLerpVertex(triIndicies[i0], triIndicies[i1], lineLerp[i0]); AddCapIndex(indexHit); smallTri[0] = triIndicies[i0]; smallTri[1] = indexHit; smallTri[2] = triIndicies[i2]; bigTri[0] = indexHit; bigTri[1] = triIndicies[i1]; bigTri[2] = triIndicies[i2]; if (_splitPlane.PointSide(_mesh.wsVerts[triIndicies[i0]]) > 0f) { _mesh.trisUp.Add(smallTri[0]); _mesh.trisUp.Add(smallTri[1]); _mesh.trisUp.Add(smallTri[2]); _mesh.trisDown.Add(bigTri[0]); _mesh.trisDown.Add(bigTri[1]); _mesh.trisDown.Add(bigTri[2]); #if UNITY_EDITOR //if (ShowDebug) { DrawDebugTri(smallTri, Color.cyan); DrawDebugTri(bigTri, Color.magenta); } #endif } else { _mesh.trisDown.Add(smallTri[0]); _mesh.trisDown.Add(smallTri[1]); _mesh.trisDown.Add(smallTri[2]); _mesh.trisUp.Add(bigTri[0]); _mesh.trisUp.Add(bigTri[1]); _mesh.trisUp.Add(bigTri[2]); #if UNITY_EDITOR //if (ShowDebug) { DrawDebugTri(smallTri, Color.magenta); DrawDebugTri(bigTri, Color.cyan); } #endif } } private void AddCapIndex(int index) { int newIndex = index - _mesh.vertexCount; Vector3 compVec = _mesh.verticesNew[newIndex]; int capCount = capInds.Count; for (int k = 0; k < capCount; k++) { int i = capInds[k]; int j = i; if (i >= _mesh.vertexCount) j -= _mesh.vertexCount; if (SplitterHelper.CompareVector3(_mesh.verticesNew[j], compVec)) return; } capInds.Add(index); } #if UNITY_EDITOR private void DrawDebugTri(int[] tri, Color color) { Debug.DrawLine(GetWSPos(tri[0]), GetWSPos(tri[1]), color, 2f); Debug.DrawLine(GetWSPos(tri[1]), GetWSPos(tri[2]), color, 2f); Debug.DrawLine(GetWSPos(tri[2]), GetWSPos(tri[0]), color, 2f); } private void DrawDebugTriDouble(int[] tri, Color color) { Debug.DrawLine(GetWSPos(tri[0]), GetWSPos(tri[1]), color, 2f); Debug.DrawLine(GetWSPos(tri[1]), GetWSPos(tri[2]), color, 2f); Debug.DrawLine(GetWSPos(tri[2]), GetWSPos(tri[0]), color, 2f); Debug.DrawLine(GetWSPos(tri[3]), GetWSPos(tri[4]), color, 2f); Debug.DrawLine(GetWSPos(tri[4]), GetWSPos(tri[5]), color, 2f); Debug.DrawLine(GetWSPos(tri[5]), GetWSPos(tri[3]), color, 2f); } public Vector3 GetWSPos(int index) { if (index >= _mesh.vertexCount) { index -= _mesh.vertexCount; return _mesh.wsVertsNew[index]; } return _mesh.wsVerts[index]; } #endif #endregion #region Mesh Caps private static Vector2 Vector2Up = Vector2.up; protected int[] capsSorted; protected Vector2[] capsUV; public void MeshCreateCaps() { if (capInds.Count == 0) return; CreateCap(); int newCapCount = capsSorted.Length; if (CustomUV) { float offX = CapUVMin.x, offY = CapUVMin.y; float dX = CapUVMax.x - CapUVMin.x, dY = CapUVMax.y - CapUVMin.y; for (int i = 0; i < newCapCount; i++) { capsUV[i].x = (capsUV[i].x * dX) + offX; capsUV[i].y = (capsUV[i].y * dY) + offY; } } //create cap verticies Vector3 normal = Quaternion.Inverse(_ownRotation) * _splitPlane.Normal; Vector3 invNormal = -normal; int[] capUpperOrder = new int[capsSorted.Length]; int[] capLowerOrder = new int[capsSorted.Length]; if (UseCapUV) { for (int i = 0; i < newCapCount; i++) { capUpperOrder[i] = _mesh.AddCapVertex(capsSorted[i], invNormal, capsUV[i]); capLowerOrder[i] = _mesh.AddCapVertex(capsSorted[i], normal, capsUV[i]); } } else { for (int i = 0; i < newCapCount; i++) { capUpperOrder[i] = _mesh.AddCapVertex(capsSorted[i], invNormal); capLowerOrder[i] = _mesh.AddCapVertex(capsSorted[i], normal); } } int capOderCount = capUpperOrder.Length; for (int i = 2; i < capOderCount; i++) { _mesh.trisUp.Add(capUpperOrder[0]); _mesh.trisUp.Add(capUpperOrder[i - 1]); _mesh.trisUp.Add(capUpperOrder[i]); _mesh.trisDown.Add(capLowerOrder[0]); _mesh.trisDown.Add(capLowerOrder[i]); _mesh.trisDown.Add(capLowerOrder[i - 1]); } #if UNITY_EDITOR // debug draw if (ShowDebug) { for (int i = 2; i < capUpperOrder.Length; i++) { Debug.DrawLine(GetVertPos(capUpperOrder[0]), GetVertPos(capUpperOrder[i - 1]), Color.yellow, 2f); Debug.DrawLine(GetVertPos(capUpperOrder[i - 1]), GetVertPos(capUpperOrder[i]), Color.yellow, 2f); Debug.DrawLine(GetVertPos(capUpperOrder[i]), GetVertPos(capUpperOrder[0]), Color.yellow, 2f); } } #endif } #if UNITY_EDITOR public Vector3 GetVertPos(int index) { if (index >= _mesh.vertexCount) { index -= _mesh.vertexCount; return _mesh.verticesNew[index]; } return _mesh.vertices[index]; } #endif private void CreateCap() { Quaternion invRotation = Quaternion.Inverse(_splitRotation); int capCount = capInds.Count; Vector3 pos = _mesh.transform.position; Vector2[] rotVerts = new Vector2[capCount]; for (int i = 0; i < capCount; i++) { Vector3 vec = capInds[i] < _mesh.vertexCount ? _mesh.wsVerts[capInds[i]] : _mesh.wsVertsNew[capInds[i] - _mesh.vertexCount]; vec = invRotation * (vec - pos); rotVerts[i] = new Vector2(vec.x, vec.z); } // init sorting int[] sorted = new int[capCount]; for (int i = 0; i < capCount; i++) { sorted[i] = i; } // find start point int lowestIndex = 0; Vector2 lowestVec = rotVerts[sorted[lowestIndex]]; for (int i = 1; i < capCount; i++) { if (SortLowY(rotVerts[sorted[i]], lowestVec)) { lowestIndex = i; lowestVec = rotVerts[sorted[lowestIndex]]; } } if (lowestIndex != 0) Swap(sorted, 0, lowestIndex); // calc angles float angleSensitivity = 90f * 10f; int[] angles = new int[capCount]; Vector2 sVec = rotVerts[sorted[0]]; for (int i = 1; i < capCount; i++) { Vector2 vec = rotVerts[sorted[i]]; float dot = Vector2.Dot(Vector2Up, (vec - sVec).normalized); if (sVec.x <= vec.x) { angles[sorted[i]] = (int)(dot * angleSensitivity); } else { angles[sorted[i]] = (int)((2f - dot) * angleSensitivity); } if (angles[sorted[i]] < 0) angles[sorted[i]] = 0; } angles[sorted[0]] = -1; // sorting GnomeSort(sorted, angles); SortEvenStart(sorted, angles, rotVerts); SortEvenEnd(sorted, angles, rotVerts); // Remove redundant verts float invThreshold = 1f - SplitterHelper.Threshold; int sortCount = sorted.Length; int sortSize = sortCount; int sort0 = 0, sort1 = 1 % sortCount, sort2 = 2 % sortCount; while (true) { Vector2 vec01 = rotVerts[sorted[sort1]] - rotVerts[sorted[sort0]]; Vector2 vec12 = rotVerts[sorted[sort2]] - rotVerts[sorted[sort1]]; if (Vector2.Dot(vec01.normalized, vec12.normalized) > invThreshold) { sorted[sort1] = -1; sortSize--; } else { sort0 = sort1; } if (sort2 == 0) break; sort1 = sort2; sort2 = (sort2 + 1) % sortCount; } capsSorted = new int[sortSize]; int capsIndex = 0; for (int i = 0; i < sortCount && capsIndex < sortSize; i++) { int sortIndex = sorted[i]; if (sortIndex >= 0) { capsSorted[capsIndex++] = capInds[sortIndex]; } } if (UseCapUV) { capsUV = new Vector2[sortSize]; Vector2 minBounds = new Vector2(float.MaxValue, float.MaxValue); Vector2 maxBounds = new Vector2(float.MinValue, float.MinValue); for (int i = 0; i < sortCount; i++) { int sortIndex = sorted[i]; if (sortIndex >= 0) { Vector2 vert = rotVerts[sortIndex]; if (minBounds.x > vert.x) minBounds.x = vert.x; else if (maxBounds.x < vert.x) maxBounds.x = vert.x; if (minBounds.y > vert.y) minBounds.y = vert.y; else if (maxBounds.y < vert.y) maxBounds.y = vert.y; } } float dX = maxBounds.x - minBounds.x, dY = maxBounds.y - minBounds.y; capsIndex = 0; for (int i = 0; i < sortCount && capsIndex < sortSize; i++) { int sortIndex = sorted[i]; if (sortIndex >= 0) { Vector2 vert = rotVerts[sortIndex]; capsUV[capsIndex++] = new Vector2((vert.x - minBounds.x) / dX, (vert.y - minBounds.y) / dY); } } } } private void Swap(int[] array, int a, int b) { int tmp = array[a]; array[a] = array[b]; array[b] = tmp; } private bool SortLowY(Vector2 a, Vector2 b) { if (a.y > b.y) return false; else if (a.y < b.y) return true; else if (a.x < b.x) return true; return false; } private void GnomeSort(int[] index, int[] value) { int pos = 1; int count = index.Length; while (pos < count) { if (value[index[pos]] >= value[index[pos - 1]]) pos++; else { Swap(index, pos, pos - 1); if (pos > 1) pos--; else pos++; } } } private void SortEvenStart(int[] index, int[] value, Vector2[] localVerts) { int pos = 2; int count = index.Length; while (pos < count) { if (value[index[pos]] == value[index[pos - 1]]) { Vector2 vecPos1 = localVerts[index[pos - 1]]; Vector2 vecPos2 = localVerts[index[pos]]; if (vecPos1.y > vecPos2.y || (vecPos1.x > vecPos2.x && vecPos1.y == vecPos2.y)) { Swap(index, pos, pos - 1); if (pos > 2) pos--; else pos++; } else pos++; } else break; } } private void SortEvenEnd(int[] index, int[] value, Vector2[] localVerts) { int count = index.Length; int pos = count - 2; while (pos > 0) { if (value[index[pos]] == value[index[pos + 1]]) { Vector2 vecPos1 = localVerts[index[pos]]; Vector2 vecPos2 = localVerts[index[pos + 1]]; if (vecPos1.y < vecPos2.y) { Swap(index, pos, pos + 1); if (pos < count - 2) pos++; else pos--; } else pos--; } else break; } } #endregion } }
// Copyright (c) Andrew Karpov. 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Text; using System.Composition; using System; namespace RefactoringTools { /// <summary> /// Provides refactoring for using extension method IsNullOrEmpty instead of String.IsNullOrEmpty. /// </summary> [ExportCodeRefactoringProvider(RefactoringId, LanguageNames.CSharp), Shared] internal class StringExtensionRefactoringProvider : CodeRefactoringProvider { public const string RefactoringId = nameof(StringExtensionRefactoringProvider); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var document = context.Document; var cancellationToken = context.CancellationToken; var textSpan = context.Span; var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var node = root.FindNode(textSpan); var invocation = node as InvocationExpressionSyntax; if (invocation == null && node.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && node.Parent.Parent.IsKind(SyntaxKind.InvocationExpression)) { if (node.IsKind(SyntaxKind.PredefinedType)) { var predefinedTypeSyntax = node as PredefinedTypeSyntax; if (predefinedTypeSyntax == null) return; if (!predefinedTypeSyntax.Keyword.IsKind(SyntaxKind.StringKeyword)) return; } else if (node.IsKind(SyntaxKind.IdentifierName)) { var identifier = node as IdentifierNameSyntax; if (identifier.ToString() != "IsNullOrEmpty") return; } invocation = node.Parent.Parent as InvocationExpressionSyntax; } if (invocation == null || !IsRefactorable(invocation)) { return; } var action = CodeAction.Create( "Replace with extension method", c => ReplaceWithExtensionMethod(document, invocation, c)); context.RegisterRefactoring(action); } private bool IsRefactorable(InvocationExpressionSyntax invocation) { var memberAccess = invocation.Expression as MemberAccessExpressionSyntax; if (!memberAccess.IsKind(SyntaxKind.SimpleMemberAccessExpression)) return false; if (memberAccess.Name.ToString() != "IsNullOrEmpty") return false; var predefinedTypeSyntax = memberAccess.Expression as PredefinedTypeSyntax; if (predefinedTypeSyntax == null) return false; if (!predefinedTypeSyntax.Keyword.IsKind(SyntaxKind.StringKeyword)) return false; var argumentList = invocation.ArgumentList; if (argumentList.Arguments.Count != 1) return false; return true; } private async Task<Solution> ReplaceWithExtensionMethod( Document document, InvocationExpressionSyntax invocation, CancellationToken cancellationToken) { var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var invocationArgument = invocation.ArgumentList.Arguments[0].Expression; var typeSymbol = semanticModel.GetTypeInfo(invocationArgument).Type; var hasExtensionMethodIsNullOrEmpty = semanticModel .LookupSymbols(invocationArgument.Span.End, typeSymbol, null, true) .OfType<IMethodSymbol>() .Any(s => s.IsExtensionMethod && s.Name.EndsWith("IsNullOrEmpty") && s.Parameters.Length == 0 && s.ReturnType.SpecialType == SpecialType.System_Boolean); var argumentList = invocation.ArgumentList; var argument = argumentList.Arguments[0].Expression; ExpressionSyntax target; if (argument is BinaryExpressionSyntax || argument is ConditionalExpressionSyntax) { target = SyntaxFactory.ParenthesizedExpression(argument); } else { target = argument; } var newMemberAccess = SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, target, SyntaxFactory.IdentifierName("IsNullOrEmpty")); var newInvocation = SyntaxFactory.InvocationExpression(newMemberAccess); syntaxRoot = syntaxRoot.ReplaceNode(invocation, newInvocation); if (!hasExtensionMethodIsNullOrEmpty) { var extensionClass = CreateStringExtensionsClass(); var namespaceDeclaration = syntaxRoot.DescendantNodes().OfType<NamespaceDeclarationSyntax>().First(); var newNamespaceDeclaration = namespaceDeclaration.AddMembers(extensionClass); var dump = newNamespaceDeclaration.ToString(); syntaxRoot = syntaxRoot.ReplaceNode(namespaceDeclaration, newNamespaceDeclaration); } syntaxRoot = syntaxRoot.Format();; document = document.WithSyntaxRoot(syntaxRoot); return document.Project.Solution; } private static ClassDeclarationSyntax CreateStringExtensionsClass() { var result = SyntaxFactory.ClassDeclaration("StringExtensions") .WithModifiers(new SyntaxTokenList().AddRange( new SyntaxToken[] { SyntaxFactory.Token(SyntaxKind.InternalKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword) } )) .WithMembers(new SyntaxList<MemberDeclarationSyntax>().Add( CreateIsNullOrEmptyMethod() )); return result; } private static MethodDeclarationSyntax CreateIsNullOrEmptyMethod() { var argumentList = SyntaxFactory.ArgumentList(new SeparatedSyntaxList<ArgumentSyntax>().Add( SyntaxFactory.Argument(SyntaxFactory.IdentifierName("input")) )); var argsToString = argumentList.ToString(); var returnStatement = SyntaxFactory.ReturnStatement( SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword)), SyntaxFactory.IdentifierName("IsNullOrEmpty") ), argumentList ) ); var returnDump = returnStatement.ToString(); var method = SyntaxFactory.MethodDeclaration( SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BoolKeyword)), "IsNullOrEmpty") .WithParameterList(SyntaxFactory.ParameterList(new SeparatedSyntaxList<ParameterSyntax>().Add( SyntaxFactory.Parameter(SyntaxFactory.Identifier("input")) .WithModifiers(new SyntaxTokenList().Add( SyntaxFactory.Token(SyntaxKind.ThisKeyword) )) .WithType( SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword)) )))) .WithBody(SyntaxFactory.Block(new SyntaxList<StatementSyntax>().Add( returnStatement ))) .WithModifiers(new SyntaxTokenList().AddRange( new SyntaxToken[] { SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword) } )); var dump = method.ToString(); return method; } } }
// Stubs for the namespace Microsoft.SqlServer.Management.Smo. Used for mocking in tests. using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Security; using System.Runtime.InteropServices; namespace Microsoft.SqlServer.Management.Smo { #region Public Enums // TypeName: Microsoft.SqlServer.Management.Smo.LoginCreateOptions // Used by: // MSFT_xSQLServerLogin.Tests.ps1 public enum LoginCreateOptions { None = 0, IsHashed = 1, MustChange = 2 } // TypeName: Microsoft.SqlServer.Management.Smo.LoginType // BaseType: Microsoft.SqlServer.Management.Smo.ScriptNameObjectBase // Used by: // MSFT_xSQLServerLogin public enum LoginType { AsymmetricKey = 4, Certificate = 3, ExternalGroup = 6, ExternalUser = 5, SqlLogin = 2, WindowsGroup = 1, WindowsUser = 0, Unknown = -1 // Added for verification (mock) purposes, to verify that a login type is passed } // TypeName: Microsoft.SqlServer.Management.Smo.AvailabilityReplicaFailoverMode // Used by: // MSFT_xSQLAOGroupEnsure.Tests public enum AvailabilityReplicaFailoverMode { Automatic, Manual, Unknown } // TypeName: Microsoft.SqlServer.Management.Smo.AvailabilityReplicaAvailabilityMode // Used by: // MSFT_xSQLAOGroupEnsure.Tests public enum AvailabilityReplicaAvailabilityMode { AsynchronousCommit, SynchronousCommit, Unknown } // TypeName: Microsoft.SqlServer.Management.Smo.EndpointType // Used by: // xSQLServerEndpoint public enum EndpointType { DatabaseMirroring, ServiceBroker, Soap, TSql } // TypeName: Microsoft.SqlServer.Management.Smo.ProtocolType // Used by: // xSQLServerEndpoint public enum ProtocolType { Http, NamedPipes, SharedMemory, Tcp, Via } // TypeName: Microsoft.SqlServer.Management.Smo.ServerMirroringRole // Used by: // xSQLServerEndpoint public enum ServerMirroringRole { All, None, Partner, Witness } // TypeName: Microsoft.SqlServer.Management.Smo.EndpointEncryption // Used by: // xSQLServerEndpoint public enum EndpointEncryption { Disabled, Required, Supported } // TypeName: Microsoft.SqlServer.Management.Smo.EndpointEncryptionAlgorithm // Used by: // xSQLServerEndpoint public enum EndpointEncryptionAlgorithm { Aes, AesRC4, None, RC4, RC4Aes } #endregion Public Enums #region Public Classes public class Globals { // Static property that is switched on or off by tests if data should be mocked (true) or not (false). public static bool GenerateMockData = false; } // Typename: Microsoft.SqlServer.Management.Smo.ObjectPermissionSet // BaseType: Microsoft.SqlServer.Management.Smo.PermissionSetBase // Used by: // xSQLServerEndpointPermission.Tests.ps1 public class ObjectPermissionSet { public ObjectPermissionSet(){} public ObjectPermissionSet( bool connect ) { this.Connect = connect; } public bool Connect = false; } // TypeName: Microsoft.SqlServer.Management.Smo.ServerPermissionSet // BaseType: Microsoft.SqlServer.Management.Smo.PermissionSetBase // Used by: // xSQLServerPermission.Tests.ps1 public class ServerPermissionSet { public ServerPermissionSet(){} public ServerPermissionSet( bool alterAnyAvailabilityGroup, bool alterAnyEndpoint, bool connectSql, bool viewServerState ) { this.AlterAnyAvailabilityGroup = alterAnyAvailabilityGroup; this.AlterAnyEndpoint = alterAnyEndpoint; this.ConnectSql = connectSql; this.ViewServerState = viewServerState; } public bool AlterAnyAvailabilityGroup = false; public bool AlterAnyEndpoint = false; public bool ConnectSql = false; public bool ViewServerState = false; } // TypeName: Microsoft.SqlServer.Management.Smo.ServerPermissionInfo // BaseType: Microsoft.SqlServer.Management.Smo.PermissionInfo // Used by: // xSQLServerPermission.Tests.ps1 public class ServerPermissionInfo { public ServerPermissionInfo() { Microsoft.SqlServer.Management.Smo.ServerPermissionSet[] permissionSet = { new Microsoft.SqlServer.Management.Smo.ServerPermissionSet() }; this.PermissionType = permissionSet; } public ServerPermissionInfo( Microsoft.SqlServer.Management.Smo.ServerPermissionSet[] permissionSet ) { this.PermissionType = permissionSet; } public Microsoft.SqlServer.Management.Smo.ServerPermissionSet[] PermissionType; public string PermissionState = "Grant"; } // TypeName: Microsoft.SqlServer.Management.Smo.DatabasePermissionSet // BaseType: Microsoft.SqlServer.Management.Smo.PermissionSetBase // Used by: // xSQLServerDatabasePermission.Tests.ps1 public class DatabasePermissionSet { public DatabasePermissionSet(){} public DatabasePermissionSet( bool connect, bool update ) { this.Connect = connect; this.Update = update; } public bool Connect = false; public bool Update = false; } // TypeName: Microsoft.SqlServer.Management.Smo.DatabasePermissionInfo // BaseType: Microsoft.SqlServer.Management.Smo.PermissionInfo // Used by: // xSQLServerDatabasePermission.Tests.ps1 public class DatabasePermissionInfo { public DatabasePermissionInfo() { Microsoft.SqlServer.Management.Smo.DatabasePermissionSet[] permissionSet = { new Microsoft.SqlServer.Management.Smo.DatabasePermissionSet() }; this.PermissionType = permissionSet; } public DatabasePermissionInfo( Microsoft.SqlServer.Management.Smo.DatabasePermissionSet[] permissionSet ) { this.PermissionType = permissionSet; } public Microsoft.SqlServer.Management.Smo.DatabasePermissionSet[] PermissionType; public string PermissionState = "Grant"; } // TypeName: Microsoft.SqlServer.Management.Smo.Server // BaseType: Microsoft.SqlServer.Management.Smo.SqlSmoObject // Used by: // xSQLServerPermission // MSFT_xSQLServerLogin public class Server { public string MockGranteeName; public AvailabilityGroupCollection AvailabilityGroups = new AvailabilityGroupCollection(); public ConnectionContext ConnectionContext; public string ComputerNamePhysicalNetBIOS; public DatabaseCollection Databases = new DatabaseCollection(); public string DisplayName; public string DomainInstanceName; public EndpointCollection Endpoints = new EndpointCollection(); public string FilestreamLevel = "Disabled"; public string InstanceName; public bool IsClustered = false; public bool IsHadrEnabled = false; public Hashtable Logins = new Hashtable(); public string Name; public string NetName; public Hashtable Roles = new Hashtable(); public string ServiceName; public Hashtable Version = new Hashtable(); public Server(){} public Server(string name) { this.Name = name; } public Server Clone() { return new Server() { MockGranteeName = this.MockGranteeName, AvailabilityGroups = this.AvailabilityGroups, ConnectionContext = this.ConnectionContext, ComputerNamePhysicalNetBIOS = this.ComputerNamePhysicalNetBIOS, Databases = this.Databases, DisplayName = this.DisplayName, DomainInstanceName = this.DomainInstanceName, Endpoints = this.Endpoints, FilestreamLevel = this.FilestreamLevel, InstanceName = this.InstanceName, IsClustered = this.IsClustered, IsHadrEnabled = this.IsHadrEnabled, Logins = this.Logins, Name = this.Name, NetName = this.NetName, Roles = this.Roles, ServiceName = this.ServiceName, Version = this.Version }; } public Microsoft.SqlServer.Management.Smo.ServerPermissionInfo[] EnumServerPermissions( string principal, Microsoft.SqlServer.Management.Smo.ServerPermissionSet permissionSetQuery ) { Microsoft.SqlServer.Management.Smo.ServerPermissionInfo[] permissionInfo = null; List<Microsoft.SqlServer.Management.Smo.ServerPermissionInfo> listOfServerPermissionInfo = null; if( Globals.GenerateMockData ) { listOfServerPermissionInfo = new List<Microsoft.SqlServer.Management.Smo.ServerPermissionInfo>(); Microsoft.SqlServer.Management.Smo.ServerPermissionSet[] permissionSet = { // AlterAnyEndpoint is set to false to test when permissions are missing. // AlterAnyAvailabilityGroup is set to true. new Microsoft.SqlServer.Management.Smo.ServerPermissionSet( true, false, false, false ), // ConnectSql is set to true. new Microsoft.SqlServer.Management.Smo.ServerPermissionSet( false, false, true, false ), // ViewServerState is set to true. new Microsoft.SqlServer.Management.Smo.ServerPermissionSet( false, false, false, true ) }; listOfServerPermissionInfo.Add( new Microsoft.SqlServer.Management.Smo.ServerPermissionInfo( permissionSet ) ); } if( listOfServerPermissionInfo != null ) { permissionInfo = listOfServerPermissionInfo.ToArray(); } return permissionInfo; } public void Grant( Microsoft.SqlServer.Management.Smo.ServerPermissionSet permission, string granteeName ) { if( granteeName != this.MockGranteeName ) { string errorMessage = "Expected to get granteeName == '" + this.MockGranteeName + "'. But got '" + granteeName + "'"; throw new System.ArgumentException(errorMessage, "granteeName"); } } public void Revoke( Microsoft.SqlServer.Management.Smo.ServerPermissionSet permission, string granteeName ) { if( granteeName != this.MockGranteeName ) { string errorMessage = "Expected to get granteeName == '" + this.MockGranteeName + "'. But got '" + granteeName + "'"; throw new System.ArgumentException(errorMessage, "granteeName"); } } } // TypeName: Microsoft.SqlServer.Management.Smo.Login // BaseType: Microsoft.SqlServer.Management.Smo.ScriptNameObjectBase // Used by: // MSFT_xSQLServerLogin public class Login { private bool _mockPasswordPassed = false; public string Name; public LoginType LoginType = LoginType.Unknown; public bool MustChangePassword = false; public bool PasswordPolicyEnforced = false; public bool PasswordExpirationEnabled = false; public bool IsDisabled = false; public string MockName; public LoginType MockLoginType; public Login( string name ) { this.Name = name; } public Login( Server server, string name ) { this.Name = name; } public Login( Object server, string name ) { this.Name = name; } public void Alter() { if( !( String.IsNullOrEmpty(this.MockName) ) ) { if(this.MockName != this.Name) { throw new Exception(); } } if( !( String.IsNullOrEmpty(this.MockLoginType.ToString()) ) ) { if( this.MockLoginType != this.LoginType ) { throw new Exception(this.MockLoginType.ToString()); } } } public void ChangePassword( SecureString secureString ) { IntPtr valuePtr = IntPtr.Zero; try { valuePtr = Marshal.SecureStringToGlobalAllocUnicode(secureString); if ( Marshal.PtrToStringUni(valuePtr) == "pw" ) { throw new FailedOperationException ( "FailedOperationException", new SmoException ( "SmoException", new SqlServerManagementException ( "SqlServerManagementException", new Exception ( "Password validation failed. The password does not meet Windows policy requirements because it is too short." ) ) ) ); } else if ( Marshal.PtrToStringUni(valuePtr) == "reused" ) { throw new FailedOperationException (); } else if ( Marshal.PtrToStringUni(valuePtr) == "other" ) { throw new Exception (); } } finally { Marshal.ZeroFreeGlobalAllocUnicode(valuePtr); } } public void Create() { if( this.LoginType == LoginType.Unknown ) { throw new System.Exception( "Called Create() method without a value for LoginType." ); } if( this.LoginType == LoginType.SqlLogin && _mockPasswordPassed != true ) { throw new System.Exception( "Called Create() method for the LoginType 'SqlLogin' but called with the wrong overloaded method. Did not pass the password with the Create() method." ); } if( !( String.IsNullOrEmpty(this.MockName) ) ) { if(this.MockName != this.Name) { throw new Exception(); } } if( !( String.IsNullOrEmpty(this.MockLoginType.ToString()) ) ) { if( this.MockLoginType != this.LoginType ) { throw new Exception(this.MockLoginType.ToString()); } } } public void Create( SecureString secureString ) { _mockPasswordPassed = true; this.Create(); } public void Create( SecureString password, LoginCreateOptions options ) { IntPtr valuePtr = IntPtr.Zero; try { valuePtr = Marshal.SecureStringToGlobalAllocUnicode(password); if ( Marshal.PtrToStringUni(valuePtr) == "pw" ) { throw new FailedOperationException ( "FailedOperationException", new SmoException ( "SmoException", new SqlServerManagementException ( "SqlServerManagementException", new Exception ( "Password validation failed. The password does not meet Windows policy requirements because it is too short." ) ) ) ); } else if ( this.Name == "Existing" ) { throw new FailedOperationException ( "The login already exists" ); } else if ( this.Name == "Unknown" ) { throw new Exception (); } else { _mockPasswordPassed = true; this.Create(); } } finally { Marshal.ZeroFreeGlobalAllocUnicode(valuePtr); } } public void Drop() { if( !( String.IsNullOrEmpty(this.MockName) ) ) { if(this.MockName != this.Name) { throw new Exception(); } } if( !( String.IsNullOrEmpty(this.MockLoginType.ToString()) ) ) { if( this.MockLoginType != this.LoginType ) { throw new Exception(this.MockLoginType.ToString()); } } } } // TypeName: Microsoft.SqlServer.Management.Smo.ServerRole // BaseType: Microsoft.SqlServer.Management.Smo.ScriptNameObjectBase // Used by: // MSFT_xSQLServerRole public class ServerRole { public ServerRole( Server server, string name ) { this.Name = name; } public ServerRole( Object server, string name ) { this.Name = name; } public string Name; } // TypeName: Microsoft.SqlServer.Management.Smo.Database // BaseType: Microsoft.SqlServer.Management.Smo.ScriptNameObjectBase // Used by: // MSFT_xSQLServerAlwaysOnAvailabilityGroupDatabaseMembership // MSFT_xSQLServerDatabase // MSFT_xSQLServerDatabasePermission public class Database { public bool AutoClose = false; public string AvailabilityGroupName = ""; public Certificate[] Certificates; public string ContainmentType = "None"; public DatabaseEncryptionKey DatabaseEncryptionKey; public string DefaultFileStreamFileGroup; public bool EncryptionEnabled = false; public Hashtable FileGroups; public string FilestreamDirectoryName; public string FilestreamNonTransactedAccess = "Off"; public int ID = 6; public bool IsMirroringEnabled = false; public DateTime LastBackupDate = DateTime.Now; public Hashtable LogFiles; public string MockGranteeName; public string Owner = "sa"; public bool ReadOnly = false; public string RecoveryModel = "Full"; public string UserAccess = "Multiple"; public Database( Server server, string name ) { this.Name = name; } public Database( Object server, string name ) { this.Name = name; } public Database() {} public string Name; public void Create() { } public void Drop() { } public Microsoft.SqlServer.Management.Smo.DatabasePermissionInfo[] EnumDatabasePermissions( string granteeName ) { List<Microsoft.SqlServer.Management.Smo.DatabasePermissionInfo> listOfDatabasePermissionInfo = new List<Microsoft.SqlServer.Management.Smo.DatabasePermissionInfo>(); if( Globals.GenerateMockData ) { Microsoft.SqlServer.Management.Smo.DatabasePermissionSet[] permissionSet = { new Microsoft.SqlServer.Management.Smo.DatabasePermissionSet( true, false ), new Microsoft.SqlServer.Management.Smo.DatabasePermissionSet( false, true ) }; listOfDatabasePermissionInfo.Add( new Microsoft.SqlServer.Management.Smo.DatabasePermissionInfo( permissionSet ) ); } else { listOfDatabasePermissionInfo.Add( new Microsoft.SqlServer.Management.Smo.DatabasePermissionInfo() ); } Microsoft.SqlServer.Management.Smo.DatabasePermissionInfo[] permissionInfo = listOfDatabasePermissionInfo.ToArray(); return permissionInfo; } public void Grant( Microsoft.SqlServer.Management.Smo.DatabasePermissionSet permission, string granteeName ) { if( granteeName != this.MockGranteeName ) { string errorMessage = "Expected to get granteeName == '" + this.MockGranteeName + "'. But got '" + granteeName + "'"; throw new System.ArgumentException(errorMessage, "granteeName"); } } public void Deny( Microsoft.SqlServer.Management.Smo.DatabasePermissionSet permission, string granteeName ) { if( granteeName != this.MockGranteeName ) { string errorMessage = "Expected to get granteeName == '" + this.MockGranteeName + "'. But got '" + granteeName + "'"; throw new System.ArgumentException(errorMessage, "granteeName"); } } } // TypeName: Microsoft.SqlServer.Management.Smo.User // BaseType: Microsoft.SqlServer.Management.Smo.ScriptNameObjectBase // Used by: // xSQLServerDatabaseRole.Tests.ps1 public class User { public User( Server server, string name ) { this.Name = name; } public User( Object server, string name ) { this.Name = name; } public string Name; public string Login; public void Create() { } public void Drop() { } } // TypeName: Microsoft.SqlServer.Management.Smo.SqlServerManagementException // BaseType: System.Exception // Used by: // xSqlServerLogin.Tests.ps1 public class SqlServerManagementException : Exception { public SqlServerManagementException () : base () {} public SqlServerManagementException (string message) : base (message) {} public SqlServerManagementException (string message, Exception inner) : base (message, inner) {} } // TypeName: Microsoft.SqlServer.Management.Smo.SmoException // BaseType: Microsoft.SqlServer.Management.Smo.SqlServerManagementException // Used by: // xSqlServerLogin.Tests.ps1 public class SmoException : SqlServerManagementException { public SmoException () : base () {} public SmoException (string message) : base (message) {} public SmoException (string message, SqlServerManagementException inner) : base (message, inner) {} } // TypeName: Microsoft.SqlServer.Management.Smo.FailedOperationException // BaseType: Microsoft.SqlServer.Management.Smo.SmoException // Used by: // xSqlServerLogin.Tests.ps1 public class FailedOperationException : SmoException { public FailedOperationException () : base () {} public FailedOperationException (string message) : base (message) {} public FailedOperationException (string message, SmoException inner) : base (message, inner) {} } // TypeName: Microsoft.SqlServer.Management.Smo.AvailabilityGroup // BaseType: Microsoft.SqlServer.Management.Smo.NamedSmoObject // Used by: // xSQLServerAlwaysOnAvailabilityGroup public class AvailabilityGroup { public AvailabilityGroup() {} public AvailabilityGroup( Server server, string name ) {} public string AutomatedBackupPreference; public AvailabilityDatabaseCollection AvailabilityDatabases = new AvailabilityDatabaseCollection(); public AvailabilityReplicaCollection AvailabilityReplicas = new AvailabilityReplicaCollection(); public bool BasicAvailabilityGroup; public bool DatabaseHealthTrigger; public bool DtcSupportEnabled; public string FailureConditionLevel; public string HealthCheckTimeout; public string Name; public string PrimaryReplicaServerName; public string LocalReplicaRole = "Secondary"; public void Alter() { if ( this.Name == "AlterFailed" ) { throw new System.Exception( "Alter Availability Group failed" ); } } public AvailabilityGroup Clone() { return new AvailabilityGroup() { AutomatedBackupPreference = this.AutomatedBackupPreference, AvailabilityDatabases = this.AvailabilityDatabases, AvailabilityReplicas = this.AvailabilityReplicas, BasicAvailabilityGroup = this.BasicAvailabilityGroup, DatabaseHealthTrigger = this.DatabaseHealthTrigger, DtcSupportEnabled = this.DtcSupportEnabled, FailureConditionLevel = this.FailureConditionLevel, HealthCheckTimeout = this.HealthCheckTimeout, Name = this.Name, PrimaryReplicaServerName = this.PrimaryReplicaServerName, LocalReplicaRole = this.LocalReplicaRole }; } } // TypeName: Microsoft.SqlServer.Management.Smo.AvailabilityReplica // BaseType: Microsoft.SqlServer.Management.Smo.NamedSmoObject // Used by: // xSQLServerAlwaysOnAvailabilityGroup public class AvailabilityReplica { public AvailabilityReplica() {} public AvailabilityReplica( AvailabilityGroup availabilityGroup, string name ) {} public string AvailabilityMode; public string BackupPriority; public string ConnectionModeInPrimaryRole; public string ConnectionModeInSecondaryRole; public string EndpointUrl; public string FailoverMode; public string Name; public string ReadOnlyRoutingConnectionUrl; public string[] ReadOnlyRoutingList; public string Role = "Secondary"; public void Alter() { if ( this.Name == "AlterFailed" ) { throw new System.Exception( "Alter Availability Group Replica failed" ); } } public void Create() {} } // TypeName: Microsoft.SqlServer.Management.Common.ServerConnection // Used by: // xSQLServerAlwaysOnAvailabilityGroupDatabaseMembership public class ConnectionContext { public string TrueLogin; public void Create() {} } // TypeName: Microsoft.SqlServer.Management.Smo.AvailabilityDatabase // Used by: // xSQLServerAlwaysOnAvailabilityGroupDatabaseMembership public class AvailabilityDatabase { public string Name; public void Create() {} } // TypeName: Microsoft.SqlServer.Management.Smo.DatabaseCollection // Used by: // xSQLServerAlwaysOnAvailabilityGroupDatabaseMembership public class DatabaseCollection : Collection<Database> { public Database this[string name] { get { foreach ( Database database in this ) { if ( name == database.Name ) { return database; } } return null; } } } // TypeName: Microsoft.SqlServer.Management.Smo.AvailabilityReplicaCollection // Used by: // xSQLServerAlwaysOnAvailabilityGroupDatabaseMembership public class AvailabilityReplicaCollection : Collection<AvailabilityReplica> { public AvailabilityReplica this[string name] { get { foreach ( AvailabilityReplica availabilityReplica in this ) { if ( name == availabilityReplica.Name ) { return availabilityReplica; } } return null; } } } // TypeName: Microsoft.SqlServer.Management.Smo.DatabaseEncryptionKey // Used by: // xSQLServerAlwaysOnAvailabilityGroupDatabaseMembership public class DatabaseEncryptionKey { public string EncryptorName; public byte[] Thumbprint; } // TypeName: Microsoft.SqlServer.Management.Smo.Certificate // Used by: // xSQLServerAlwaysOnAvailabilityGroupDatabaseMembership public class Certificate { public byte[] Thumbprint; } // TypeName: Microsoft.SqlServer.Management.Smo.AvailabilityDatabaseCollection // Used by: // xSQLServerAlwaysOnAvailabilityGroupDatabaseMembership public class AvailabilityDatabaseCollection : Collection<AvailabilityDatabase> { public AvailabilityDatabase this[string name] { get { foreach ( AvailabilityDatabase availabilityDatabase in this ) { if ( name == availabilityDatabase.Name ) { return availabilityDatabase; } } return null; } } } // TypeName: Microsoft.SqlServer.Management.Smo.AvailabilityGroupCollection // Used by: // xSQLServerAlwaysOnAvailabilityGroup public class AvailabilityGroupCollection : Collection<AvailabilityGroup> { public AvailabilityGroup this[string name] { get { foreach ( AvailabilityGroup availabilityGroup in this ) { if ( name == availabilityGroup.Name ) { return availabilityGroup; } } return null; } } } // TypeName: Microsoft.SqlServer.Management.Smo.Endpoint // Used by: // xSQLServerAlwaysOnAvailabilityGroup public class Endpoint { public string Name; public string EndpointType; public Hashtable Protocol; } // TypeName: Microsoft.SqlServer.Management.Smo.EndpointCollection // Used by: // xSQLServerAlwaysOnAvailabilityGroup public class EndpointCollection : Collection<Endpoint> { public Endpoint this[string name] { get { foreach ( Endpoint endpoint in this ) { if ( name == endpoint.Name ) { return endpoint; } } return null; } } } #endregion Public Classes } namespace Microsoft.SqlServer.Management.Smo.Wmi { #region Public Enums // TypeName: Microsoft.SqlServer.Management.Smo.Wmi.ManagedServiceType // Used by: // MSFT_xSQLServerServiceAccount.Tests.ps1 public enum ManagedServiceType { SqlServer = 1, SqlAgent = 2, Search = 3, SqlServerIntegrationService = 4, AnalysisServer = 5, ReportServer = 6, SqlBrowser = 7, NotificationServer = 8 } #endregion }
using UnityEngine; using System.Collections; using System.Collections.Generic; using UMA; namespace UMA.Examples { public class UMACrowdRandomSet : ScriptableObject { public CrowdRaceData data; [System.Serializable] public class CrowdRaceData { public string raceID; public CrowdSlotElement[] slotElements; } [System.Serializable] public class CrowdSlotElement { public string Info; public CrowdSlotData[] possibleSlots; public string requirement; public string condition; } [System.Serializable] public class CrowdSlotData { public string slotID; public bool useSharedOverlayList; public int overlayListSource; public CrowdOverlayElement[] overlayElements; } [System.Serializable] public class CrowdOverlayElement { public CrowdOverlayData[] possibleOverlays; } public enum OverlayType { Unknown, Random, Texture, Color, Skin, Hair, } public enum ChannelUse { None, Color, InverseColor } [System.Serializable] public class CrowdOverlayData { public string overlayID; public Color maxRGB; public Color minRGB; public bool useSkinColor; public bool useHairColor; public float hairColorMultiplier; public ChannelUse colorChannelUse; public int colorChannel; public OverlayType overlayType; public void UpdateVersion() { if (overlayType == UMACrowdRandomSet.OverlayType.Unknown) { if (useSkinColor) { overlayType = UMACrowdRandomSet.OverlayType.Skin; } else if (useHairColor) { overlayType = UMACrowdRandomSet.OverlayType.Hair; } else { if (minRGB == maxRGB) { if (minRGB == Color.white) { overlayType = UMACrowdRandomSet.OverlayType.Texture; } else { overlayType = UMACrowdRandomSet.OverlayType.Color; } } else { overlayType = UMACrowdRandomSet.OverlayType.Random; } } } } } public static void Apply(UMA.UMAData umaData, CrowdRaceData race, Color skinColor, Color HairColor, Color Shine, HashSet<string> Keywords, UMAContextBase context) { var slotParts = new HashSet<string>(); umaData.umaRecipe.slotDataList = new SlotData[race.slotElements.Length]; for (int i = 0; i < race.slotElements.Length; i++) { var currentElement = race.slotElements[i]; if (!string.IsNullOrEmpty(currentElement.requirement) && !slotParts.Contains(currentElement.requirement)) continue; if (!string.IsNullOrEmpty(currentElement.condition)) { if (currentElement.condition.StartsWith("!")) { if (Keywords.Contains(currentElement.condition.Substring(1))) continue; } else { if (!Keywords.Contains(currentElement.condition)) continue; } } if (currentElement.possibleSlots.Length == 0) continue; int randomResult = Random.Range(0, currentElement.possibleSlots.Length); var slot = currentElement.possibleSlots[randomResult]; if (string.IsNullOrEmpty(slot.slotID)) continue; slotParts.Add(slot.slotID); SlotData slotData; if (slot.useSharedOverlayList && slot.overlayListSource >= 0 && slot.overlayListSource < i) { slotData = context.InstantiateSlot(slot.slotID, umaData.umaRecipe.slotDataList[slot.overlayListSource].GetOverlayList()); } else { if (slot.useSharedOverlayList) { Debug.LogError("UMA Crowd: Invalid overlayListSource for " + slot.slotID); } slotData = context.InstantiateSlot(slot.slotID); } umaData.umaRecipe.slotDataList[i] = slotData; for (int overlayIdx = 0; overlayIdx < slot.overlayElements.Length; overlayIdx++) { var currentOverlayElement = slot.overlayElements[overlayIdx]; randomResult = Random.Range(0, currentOverlayElement.possibleOverlays.Length); var overlay = currentOverlayElement.possibleOverlays[randomResult]; if (string.IsNullOrEmpty(overlay.overlayID)) continue; overlay.UpdateVersion(); slotParts.Add(overlay.overlayID); Color overlayColor = Color.black; var overlayData = context.InstantiateOverlay(overlay.overlayID, overlayColor); switch (overlay.overlayType) { case UMACrowdRandomSet.OverlayType.Color: overlayColor = overlay.minRGB; overlayData.colorData.color = overlayColor; break; case UMACrowdRandomSet.OverlayType.Texture: overlayColor = Color.white; overlayData.colorData.color = overlayColor; break; case UMACrowdRandomSet.OverlayType.Hair: overlayColor = HairColor * overlay.hairColorMultiplier; overlayColor.a = 1.0f; overlayData.colorData.color = overlayColor; break; case UMACrowdRandomSet.OverlayType.Skin: overlayColor = skinColor;// + new Color(Random.Range(overlay.minRGB.r, overlay.maxRGB.r), Random.Range(overlay.minRGB.g, overlay.maxRGB.g), Random.Range(overlay.minRGB.b, overlay.maxRGB.b), 1); overlayData.colorData.color = overlayColor; if (overlayData.colorData.channelAdditiveMask.Length > 2) { overlayData.colorData.channelAdditiveMask[2] = Shine; } else { break; } break; case UMACrowdRandomSet.OverlayType.Random: { float randomShine = Random.Range(0.05f, 0.25f); float randomMetal = Random.Range(0.1f, 0.3f); overlayColor = new Color(Random.Range(overlay.minRGB.r, overlay.maxRGB.r), Random.Range(overlay.minRGB.g, overlay.maxRGB.g), Random.Range(overlay.minRGB.b, overlay.maxRGB.b), Random.Range(overlay.minRGB.a, overlay.maxRGB.a)); overlayData.colorData.color = overlayColor; if (overlayData.colorData.channelAdditiveMask.Length > 2) { overlayData.colorData.channelAdditiveMask[2] = new Color(randomMetal, randomMetal, randomMetal, randomShine); } } break; default: Debug.LogError("Unknown RandomSet overlayType: "+((int)overlay.overlayType)); overlayColor = overlay.minRGB; overlayData.colorData.color = overlayColor; break; } slotData.AddOverlay(overlayData); if (overlay.colorChannelUse != ChannelUse.None) { overlayColor.a *= overlay.minRGB.a; if (overlay.colorChannelUse == ChannelUse.InverseColor) { Vector3 color = new Vector3(overlayColor.r, overlayColor.g, overlayColor.b); var len = color.magnitude; if (len < 1f) len = 1f; color = new Vector3(1.001f, 1.001f, 1.001f) - color; color = color.normalized* len; overlayColor = new Color(color.x, color.y, color.z, overlayColor.a); } overlayData.SetColor(overlay.colorChannel, overlayColor); } } } } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace Provisioning.Framework.Cloud.AsyncWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
// 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 Cake.Common.Tests.Fixtures.Tools.Chocolatey.Export; using Cake.Testing; using Cake.Testing.Xunit; using Xunit; namespace Cake.Common.Tests.Unit.Tools.Chocolatey.Export { public sealed class ChocolateyExporterTests { public sealed class TheExportMethod { [Fact] public void Should_Throw_If_Settings_Are_Null() { // Given var fixture = new ChocolateyExportFixture(); fixture.Settings = null; // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsArgumentNullException(result, "settings"); } [Fact] public void Should_Throw_If_Chocolatey_Executable_Was_Not_Found() { // Given var fixture = new ChocolateyExportFixture(); fixture.GivenDefaultToolDoNotExist(); // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsCakeException(result, "Chocolatey: Could not locate executable."); } [Theory] [InlineData("/bin/chocolatey/choco.exe", "/bin/chocolatey/choco.exe")] [InlineData("./chocolatey/choco.exe", "/Working/chocolatey/choco.exe")] public void Should_Use_Chocolatey_Executable_From_Tool_Path_If_Provided(string toolPath, string expected) { // Given var fixture = new ChocolateyExportFixture(); fixture.Settings.ToolPath = toolPath; fixture.GivenSettingsToolPathExist(); // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Path.FullPath); } [WindowsTheory] [InlineData("C:/ProgramData/chocolatey/choco.exe", "C:/ProgramData/chocolatey/choco.exe")] public void Should_Use_Chocolatey_Executable_From_Tool_Path_If_Provided_On_Windows(string toolPath, string expected) { // Given var fixture = new ChocolateyExportFixture(); fixture.Settings.ToolPath = toolPath; fixture.GivenSettingsToolPathExist(); // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Path.FullPath); } [Fact] public void Should_Throw_If_Process_Was_Not_Started() { // Given var fixture = new ChocolateyExportFixture(); fixture.GivenProcessCannotStart(); // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsCakeException(result, "Chocolatey: Process was not started."); } [Fact] public void Should_Throw_If_Process_Has_A_Non_Zero_Exit_Code() { // Given var fixture = new ChocolateyExportFixture(); fixture.GivenProcessExitsWithCode(1); // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsCakeException(result, "Chocolatey: Process returned an error (exit code 1)."); } [Fact] public void Should_Find_Chocolatey_Executable_If_Tool_Path_Not_Provided() { // Given var fixture = new ChocolateyExportFixture(); // When var result = fixture.Run(); // Then Assert.Equal("/Working/tools/choco.exe", result.Path.FullPath); } [Fact] public void Should_Add_Mandatory_Arguments() { // Given var fixture = new ChocolateyExportFixture(); // When var result = fixture.Run(); // Then Assert.Equal("export -y", result.Args); } [Theory] [InlineData(true, "export -d -y")] [InlineData(false, "export -y")] public void Should_Add_Debug_Flag_To_Arguments_If_Set(bool debug, string expected) { // Given var fixture = new ChocolateyExportFixture(); fixture.Settings.Debug = debug; // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Args); } [Theory] [InlineData(true, "export -v -y")] [InlineData(false, "export -y")] public void Should_Add_Verbose_Flag_To_Arguments_If_Set(bool verbose, string expected) { // Given var fixture = new ChocolateyExportFixture(); fixture.Settings.Verbose = verbose; // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Args); } [Theory] [InlineData(true, "export -y -f")] [InlineData(false, "export -y")] public void Should_Add_Force_Flag_To_Arguments_If_Set(bool force, string expected) { // Given var fixture = new ChocolateyExportFixture(); fixture.Settings.Force = force; // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Args); } [Theory] [InlineData(true, "export -y --noop")] [InlineData(false, "export -y")] public void Should_Add_Noop_Flag_To_Arguments_If_Set(bool noop, string expected) { // Given var fixture = new ChocolateyExportFixture(); fixture.Settings.Noop = noop; // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Args); } [Theory] [InlineData(true, "export -y -r")] [InlineData(false, "export -y")] public void Should_Add_LimitOutput_Flag_To_Arguments_If_Set(bool limitOutput, string expected) { // Given var fixture = new ChocolateyExportFixture(); fixture.Settings.LimitOutput = limitOutput; // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Args); } [Theory] [InlineData(5, "export -y --execution-timeout \"5\"")] [InlineData(0, "export -y")] public void Should_Add_ExecutionTimeout_To_Arguments_If_Set(int executionTimeout, string expected) { // Given var fixture = new ChocolateyExportFixture(); fixture.Settings.ExecutionTimeout = executionTimeout; // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Args); } [Theory] [InlineData(@"c:\temp", "export -y -c \"c:\\temp\"")] [InlineData("", "export -y")] public void Should_Add_CacheLocation_Flag_To_Arguments_If_Set(string cacheLocation, string expected) { // Given var fixture = new ChocolateyExportFixture(); fixture.Settings.CacheLocation = cacheLocation; // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Args); } [Theory] [InlineData(true, "export -y --allowunofficial")] [InlineData(false, "export -y")] public void Should_Add_AllowUnofficial_Flag_To_Arguments_If_Set(bool allowUnofficial, string expected) { // Given var fixture = new ChocolateyExportFixture(); fixture.Settings.AllowUnofficial = allowUnofficial; // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Args); } [Theory] [InlineData(@"c:\temp", "export -y --output-file-path \"c:/temp\"")] [InlineData(null, "export -y")] public void Should_Add_OutputFilePath_To_Arguments_If_Set(string outputFilePath, string expected) { // Given var fixture = new ChocolateyExportFixture(); fixture.Settings.OutputFilePath = outputFilePath; // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Args); } [Theory] [InlineData(true, "export -y --include-version-numbers")] [InlineData(false, "export -y")] public void Should_Add_IncludeVersionNumbers_Flag_To_Arguments_If_Set(bool includeVersionNumbers, string expected) { // Given var fixture = new ChocolateyExportFixture(); fixture.Settings.IncludeVersionNumbers = includeVersionNumbers; // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Args); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Globalization; using System.Reflection; using System.Reflection.Emit; using System.Text; namespace SiteGroupCms.Utils.fastJSON { /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// /// JSON uses Arrays and Objects. These correspond here to the datatypes ArrayList and Hashtable. /// All numbers are parsed to doubles. /// </summary> internal class JsonParser { private const int TOKEN_NONE = 0; private const int TOKEN_CURLY_OPEN = 1; private const int TOKEN_CURLY_CLOSE = 2; private const int TOKEN_SQUARED_OPEN = 3; private const int TOKEN_SQUARED_CLOSE = 4; private const int TOKEN_COLON = 5; private const int TOKEN_COMMA = 6; private const int TOKEN_STRING = 7; private const int TOKEN_NUMBER = 8; private const int TOKEN_TRUE = 9; private const int TOKEN_FALSE = 10; private const int TOKEN_NULL = 11; /// <summary> /// Parses the string json into a value /// </summary> /// <param name="json">A JSON string.</param> /// <returns>An ArrayList, a dictionary, a double, a string, null, true, or false</returns> internal static object JsonDecode(string json) { bool success = true; return JsonDecode(json, ref success); } /// <summary> /// Parses the string json into a value; and fills 'success' with the successfullness of the parse. /// </summary> /// <param name="json">A JSON string.</param> /// <param name="success">Successful parse?</param> /// <returns>An ArrayList, a Hashtable, a double, a string, null, true, or false</returns> private static object JsonDecode(string json, ref bool success) { success = true; if (json != null) { char[] charArray = json.ToCharArray(); int index = 0; object value = ParseValue(charArray, ref index, ref success); return value; } else { return null; } } protected static Dictionary<string,object> ParseObject(char[] json, ref int index, ref bool success) { Dictionary<string,object> table = new Dictionary<string, object>(); int token; // { NextToken(json, ref index); bool done = false; while (!done) { token = LookAhead(json, index); if (token == TOKEN_NONE) { success = false; return null; } else if (token == TOKEN_COMMA) { NextToken(json, ref index); } else if (token == TOKEN_CURLY_CLOSE) { NextToken(json, ref index); return table; } else { // name string name = ParseString(json, ref index, ref success); if (!success) { success = false; return null; } // : token = NextToken(json, ref index); if (token != TOKEN_COLON) { success = false; return null; } // value object value = ParseValue(json, ref index, ref success); if (!success) { success = false; return null; } table[name] = value; } } return table; } protected static ArrayList ParseArray(char[] json, ref int index, ref bool success) { ArrayList array = new ArrayList(); NextToken(json, ref index); bool done = false; while (!done) { int token = LookAhead(json, index); if (token == TOKEN_NONE) { success = false; return null; } else if (token == TOKEN_COMMA) { NextToken(json, ref index); } else if (token == TOKEN_SQUARED_CLOSE) { NextToken(json, ref index); break; } else { object value = ParseValue(json, ref index, ref success); if (!success) { return null; } array.Add(value); } } return array; } protected static object ParseValue(char[] json, ref int index, ref bool success) { switch (LookAhead(json, index)) { case TOKEN_NUMBER: return ParseNumber(json, ref index, ref success); case TOKEN_STRING: return ParseString(json, ref index, ref success); case TOKEN_CURLY_OPEN: return ParseObject(json, ref index, ref success); case TOKEN_SQUARED_OPEN: return ParseArray(json, ref index, ref success); case TOKEN_TRUE: NextToken(json, ref index); return true; case TOKEN_FALSE: NextToken(json, ref index); return false; case TOKEN_NULL: NextToken(json, ref index); return null; case TOKEN_NONE: break; } success = false; return null; } protected static string ParseString(char[] json, ref int index, ref bool success) { StringBuilder s = new StringBuilder(); char c; EatWhitespace(json, ref index); // " c = json[index++]; bool complete = false; while (!complete) { if (index == json.Length) { break; } c = json[index++]; if (c == '"') { complete = true; break; } else if (c == '\\') { if (index == json.Length) { break; } c = json[index++]; if (c == '"') { s.Append('"'); } else if (c == '\\') { s.Append('\\'); } else if (c == '/') { s.Append('/'); } else if (c == 'b') { s.Append('\b'); } else if (c == 'f') { s.Append('\f'); } else if (c == 'n') { s.Append('\n'); } else if (c == 'r') { s.Append('\r'); } else if (c == 't') { s.Append('\t'); } else if (c == 'u') { int remainingLength = json.Length - index; if (remainingLength >= 4) { // parse the 32 bit hex into an integer codepoint uint codePoint; if (!(success = UInt32.TryParse(new string(json, index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out codePoint))) { return ""; } // convert the integer codepoint to a unicode char and add to string s.Append(Char.ConvertFromUtf32((int)codePoint)); // skip 4 chars index += 4; } else { break; } } } else { s.Append(c); } } if (!complete) { success = false; return null; } return s.ToString(); } protected static string ParseNumber(char[] json, ref int index, ref bool success) { EatWhitespace(json, ref index); int lastIndex = GetLastIndexOfNumber(json, index); int charLength = (lastIndex - index) + 1; string number = new string(json,index,charLength); success = true; index = lastIndex + 1; return number; } protected static int GetLastIndexOfNumber(char[] json, int index) { int lastIndex; for (lastIndex = index; lastIndex < json.Length; lastIndex++) { if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) { break; } } return lastIndex - 1; } protected static void EatWhitespace(char[] json, ref int index) { for (; index < json.Length; index++) { if (" \t\n\r".IndexOf(json[index]) == -1) { break; } } } protected static int LookAhead(char[] json, int index) { int saveIndex = index; return NextToken(json, ref saveIndex); } protected static int NextToken(char[] json, ref int index) { EatWhitespace(json, ref index); if (index == json.Length) { return TOKEN_NONE; } char c = json[index]; index++; switch (c) { case '{': return TOKEN_CURLY_OPEN; case '}': return TOKEN_CURLY_CLOSE; case '[': return TOKEN_SQUARED_OPEN; case ']': return TOKEN_SQUARED_CLOSE; case ',': return TOKEN_COMMA; case '"': return TOKEN_STRING; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return TOKEN_NUMBER; case ':': return TOKEN_COLON; } index--; int remainingLength = json.Length - index; // false if (remainingLength >= 5) { if (json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e') { index += 5; return TOKEN_FALSE; } } // true if (remainingLength >= 4) { if (json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e') { index += 4; return TOKEN_TRUE; } } // null if (remainingLength >= 4) { if (json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l') { index += 4; return TOKEN_NULL; } } return TOKEN_NONE; } protected static bool SerializeValue(object value, StringBuilder builder) { bool success = true; if (value is string) { success = SerializeString((string)value, builder); } else if (value is Hashtable) { success = SerializeObject((Hashtable)value, builder); } else if (value is ArrayList) { success = SerializeArray((ArrayList)value, builder); } else if (IsNumeric(value)) { success = SerializeNumber(Convert.ToDouble(value), builder); } else if ((value is Boolean) && ((Boolean)value == true)) { builder.Append("true"); } else if ((value is Boolean) && ((Boolean)value == false)) { builder.Append("false"); } else if (value == null) { builder.Append("null"); } else { success = false; } return success; } protected static bool SerializeObject(Hashtable anObject, StringBuilder builder) { builder.Append("{"); IDictionaryEnumerator e = anObject.GetEnumerator(); bool first = true; while (e.MoveNext()) { string key = e.Key.ToString(); object value = e.Value; if (!first) { builder.Append(", "); } SerializeString(key, builder); builder.Append(":"); if (!SerializeValue(value, builder)) { return false; } first = false; } builder.Append("}"); return true; } protected static bool SerializeArray(ArrayList anArray, StringBuilder builder) { builder.Append("["); bool first = true; for (int i = 0; i < anArray.Count; i++) { object value = anArray[i]; if (!first) { builder.Append(", "); } if (!SerializeValue(value, builder)) { return false; } first = false; } builder.Append("]"); return true; } protected static bool SerializeString(string aString, StringBuilder builder) { builder.Append("\""); char[] charArray = aString.ToCharArray(); for (int i = 0; i < charArray.Length; i++) { char c = charArray[i]; if (c == '"') { builder.Append("\\\""); } else if (c == '\\') { builder.Append("\\\\"); } else if (c == '\b') { builder.Append("\\b"); } else if (c == '\f') { builder.Append("\\f"); } else if (c == '\n') { builder.Append("\\n"); } else if (c == '\r') { builder.Append("\\r"); } else if (c == '\t') { builder.Append("\\t"); } else { int codepoint = Convert.ToInt32(c); if ((codepoint >= 32) && (codepoint <= 126)) { builder.Append(c); } else { builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0')); } } } builder.Append("\""); return true; } protected static bool SerializeNumber(double number, StringBuilder builder) { builder.Append(Convert.ToString(number, CultureInfo.InvariantCulture)); return true; } protected static bool IsNumeric(object o) { double result; return (o == null) ? false : Double.TryParse(o.ToString(), out result); } } }
namespace Dashboard { partial class Dashboard { /// <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.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.localChat1 = new OpenMetaverse.GUI.LocalChat(); this.splitContainer2 = new System.Windows.Forms.SplitContainer(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.avatarList1 = new OpenMetaverse.GUI.AvatarList(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.friendsList1 = new OpenMetaverse.GUI.FriendList(); this.tabPage3 = new System.Windows.Forms.TabPage(); this.groupList1 = new OpenMetaverse.GUI.GroupList(); this.tabPage4 = new System.Windows.Forms.TabPage(); this.inventoryTree1 = new OpenMetaverse.GUI.InventoryTree(); this.miniMap1 = new OpenMetaverse.GUI.MiniMap(); this.txtStatus = new System.Windows.Forms.Label(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.splitContainer2.Panel1.SuspendLayout(); this.splitContainer2.Panel2.SuspendLayout(); this.splitContainer2.SuspendLayout(); this.tabControl1.SuspendLayout(); this.tabPage1.SuspendLayout(); this.tabPage2.SuspendLayout(); this.tabPage3.SuspendLayout(); this.tabPage4.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.miniMap1)).BeginInit(); this.SuspendLayout(); // // splitContainer1 // this.splitContainer1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.splitContainer1.Location = new System.Drawing.Point(2, 3); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.localChat1); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.splitContainer2); this.splitContainer1.Size = new System.Drawing.Size(627, 419); this.splitContainer1.SplitterDistance = 415; this.splitContainer1.TabIndex = 4; // // localChat1 // this.localChat1.Client = null; this.localChat1.Dock = System.Windows.Forms.DockStyle.Fill; this.localChat1.Location = new System.Drawing.Point(0, 0); this.localChat1.Name = "localChat1"; this.localChat1.Size = new System.Drawing.Size(415, 419); this.localChat1.TabIndex = 4; // // splitContainer2 // this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer2.Location = new System.Drawing.Point(0, 0); this.splitContainer2.Name = "splitContainer2"; this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainer2.Panel1 // this.splitContainer2.Panel1.Controls.Add(this.tabControl1); // // splitContainer2.Panel2 // this.splitContainer2.Panel2.Controls.Add(this.miniMap1); this.splitContainer2.Size = new System.Drawing.Size(208, 419); this.splitContainer2.SplitterDistance = 209; this.splitContainer2.TabIndex = 9; // // tabControl1 // this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Controls.Add(this.tabPage3); this.tabControl1.Controls.Add(this.tabPage4); this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControl1.Location = new System.Drawing.Point(0, 0); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(208, 209); this.tabControl1.TabIndex = 9; // // tabPage1 // this.tabPage1.Controls.Add(this.avatarList1); this.tabPage1.Location = new System.Drawing.Point(4, 22); this.tabPage1.Name = "tabPage1"; this.tabPage1.Padding = new System.Windows.Forms.Padding(3); this.tabPage1.Size = new System.Drawing.Size(200, 183); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "Nearby"; this.tabPage1.UseVisualStyleBackColor = true; // // avatarList1 // this.avatarList1.Client = null; this.avatarList1.Dock = System.Windows.Forms.DockStyle.Fill; this.avatarList1.Location = new System.Drawing.Point(3, 3); this.avatarList1.Name = "avatarList1"; this.avatarList1.Size = new System.Drawing.Size(194, 177); this.avatarList1.TabIndex = 3; this.avatarList1.UseCompatibleStateImageBehavior = false; this.avatarList1.View = System.Windows.Forms.View.Details; // // tabPage2 // this.tabPage2.Controls.Add(this.friendsList1); this.tabPage2.Location = new System.Drawing.Point(4, 22); this.tabPage2.Name = "tabPage2"; this.tabPage2.Padding = new System.Windows.Forms.Padding(3); this.tabPage2.Size = new System.Drawing.Size(200, 221); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Friends"; this.tabPage2.UseVisualStyleBackColor = true; // // friendsList1 // this.friendsList1.Client = null; this.friendsList1.Dock = System.Windows.Forms.DockStyle.Fill; this.friendsList1.Location = new System.Drawing.Point(3, 3); this.friendsList1.Name = "friendsList1"; this.friendsList1.Size = new System.Drawing.Size(194, 215); this.friendsList1.TabIndex = 5; this.friendsList1.UseCompatibleStateImageBehavior = false; this.friendsList1.View = System.Windows.Forms.View.Details; // // tabPage3 // this.tabPage3.Controls.Add(this.groupList1); this.tabPage3.Location = new System.Drawing.Point(4, 22); this.tabPage3.Name = "tabPage3"; this.tabPage3.Size = new System.Drawing.Size(200, 221); this.tabPage3.TabIndex = 2; this.tabPage3.Text = "Groups"; this.tabPage3.UseVisualStyleBackColor = true; // // groupList1 // this.groupList1.Client = null; this.groupList1.Dock = System.Windows.Forms.DockStyle.Fill; this.groupList1.Location = new System.Drawing.Point(0, 0); this.groupList1.Name = "groupList1"; this.groupList1.Size = new System.Drawing.Size(200, 221); this.groupList1.TabIndex = 7; this.groupList1.UseCompatibleStateImageBehavior = false; this.groupList1.View = System.Windows.Forms.View.Details; // // tabPage4 // this.tabPage4.Controls.Add(this.inventoryTree1); this.tabPage4.Location = new System.Drawing.Point(4, 22); this.tabPage4.Name = "tabPage4"; this.tabPage4.Size = new System.Drawing.Size(200, 221); this.tabPage4.TabIndex = 3; this.tabPage4.Text = "Inventory"; this.tabPage4.UseVisualStyleBackColor = true; // // inventoryTree1 // this.inventoryTree1.Client = null; this.inventoryTree1.Dock = System.Windows.Forms.DockStyle.Fill; this.inventoryTree1.Location = new System.Drawing.Point(0, 0); this.inventoryTree1.Name = "inventoryTree1"; this.inventoryTree1.Size = new System.Drawing.Size(200, 221); this.inventoryTree1.TabIndex = 1; // // miniMap1 // this.miniMap1.BackColor = System.Drawing.SystemColors.Control; this.miniMap1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.miniMap1.Client = null; this.miniMap1.Dock = System.Windows.Forms.DockStyle.Fill; this.miniMap1.Location = new System.Drawing.Point(0, 0); this.miniMap1.Name = "miniMap1"; this.miniMap1.Size = new System.Drawing.Size(208, 206); this.miniMap1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.miniMap1.TabIndex = 11; this.miniMap1.TabStop = false; // // txtStatus // this.txtStatus.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtStatus.AutoEllipsis = true; this.txtStatus.Location = new System.Drawing.Point(10, 426); this.txtStatus.Name = "txtStatus"; this.txtStatus.Size = new System.Drawing.Size(611, 13); this.txtStatus.TabIndex = 5; this.txtStatus.TextAlign = System.Drawing.ContentAlignment.TopCenter; // // Dashboard // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(632, 443); this.Controls.Add(this.txtStatus); this.Controls.Add(this.splitContainer1); this.Name = "Dashboard"; this.Text = "Dashboard"; this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); this.splitContainer1.ResumeLayout(false); this.splitContainer2.Panel1.ResumeLayout(false); this.splitContainer2.Panel2.ResumeLayout(false); this.splitContainer2.ResumeLayout(false); this.tabControl1.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.tabPage2.ResumeLayout(false); this.tabPage3.ResumeLayout(false); this.tabPage4.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.miniMap1)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.SplitContainer splitContainer1; private OpenMetaverse.GUI.LocalChat localChat1; private System.Windows.Forms.SplitContainer splitContainer2; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private OpenMetaverse.GUI.AvatarList avatarList1; private System.Windows.Forms.TabPage tabPage2; private OpenMetaverse.GUI.FriendList friendsList1; private System.Windows.Forms.TabPage tabPage3; private OpenMetaverse.GUI.GroupList groupList1; private System.Windows.Forms.TabPage tabPage4; private OpenMetaverse.GUI.InventoryTree inventoryTree1; private OpenMetaverse.GUI.MiniMap miniMap1; private System.Windows.Forms.Label txtStatus; } }
// 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.Linq; using System.Collections; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public static class CollectionTests { [Fact] public static void X509CertificateCollectionsProperties() { IList ilist = new X509CertificateCollection(); Assert.False(ilist.IsSynchronized); Assert.False(ilist.IsFixedSize); Assert.False(ilist.IsReadOnly); ilist = new X509Certificate2Collection(); Assert.False(ilist.IsSynchronized); Assert.False(ilist.IsFixedSize); Assert.False(ilist.IsReadOnly); } [Fact] public static void X509CertificateCollectionConstructors() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); Assert.Equal(3, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c3, cc[2]); X509CertificateCollection cc2 = new X509CertificateCollection(cc); Assert.Equal(3, cc2.Count); Assert.Same(c1, cc2[0]); Assert.Same(c2, cc2[1]); Assert.Same(c3, cc2[2]); Assert.Throws<ArgumentNullException>(() => new X509CertificateCollection(new X509Certificate[] { c1, c2, null, c3 })); } } [Fact] public static void X509Certificate2CollectionConstructors() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); Assert.Equal(3, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c3, cc[2]); X509Certificate2Collection cc2 = new X509Certificate2Collection(cc); Assert.Equal(3, cc2.Count); Assert.Same(c1, cc2[0]); Assert.Same(c2, cc2[1]); Assert.Same(c3, cc2[2]); Assert.Throws<ArgumentNullException>(() => new X509Certificate2Collection(new X509Certificate2[] { c1, c2, null, c3 })); using (X509Certificate c4 = new X509Certificate()) { X509Certificate2Collection collection = new X509Certificate2Collection { c1, c2, c3 }; ((IList)collection).Add(c4); // Add non-X509Certificate2 object Assert.Throws<InvalidCastException>(() => new X509Certificate2Collection(collection)); } } } [Fact] public static void X509Certificate2CollectionEnumerator() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); object ignored; X509Certificate2Enumerator e = cc.GetEnumerator(); for (int i = 0; i < 2; i++) { // Not started Assert.Throws<InvalidOperationException>(() => ignored = e.Current); Assert.True(e.MoveNext()); Assert.Same(c1, e.Current); Assert.True(e.MoveNext()); Assert.Same(c2, e.Current); Assert.True(e.MoveNext()); Assert.Same(c3, e.Current); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); // Ended Assert.Throws<InvalidOperationException>(() => ignored = e.Current); e.Reset(); } IEnumerator e2 = cc.GetEnumerator(); TestNonGenericEnumerator(e2, c1, c2, c3); IEnumerator e3 = ((IEnumerable)cc).GetEnumerator(); TestNonGenericEnumerator(e3, c1, c2, c3); } } [Fact] public static void X509CertificateCollectionEnumerator() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); object ignored; X509CertificateCollection.X509CertificateEnumerator e = cc.GetEnumerator(); for (int i = 0; i < 2; i++) { // Not started Assert.Throws<InvalidOperationException>(() => ignored = e.Current); Assert.True(e.MoveNext()); Assert.Same(c1, e.Current); Assert.True(e.MoveNext()); Assert.Same(c2, e.Current); Assert.True(e.MoveNext()); Assert.Same(c3, e.Current); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); // Ended Assert.Throws<InvalidOperationException>(() => ignored = e.Current); e.Reset(); } IEnumerator e2 = cc.GetEnumerator(); TestNonGenericEnumerator(e2, c1, c2, c3); IEnumerator e3 = ((IEnumerable)cc).GetEnumerator(); TestNonGenericEnumerator(e3, c1, c2, c3); } } private static void TestNonGenericEnumerator(IEnumerator e, object c1, object c2, object c3) { object ignored; for (int i = 0; i < 2; i++) { // Not started Assert.Throws<InvalidOperationException>(() => ignored = e.Current); Assert.True(e.MoveNext()); Assert.Same(c1, e.Current); Assert.True(e.MoveNext()); Assert.Same(c2, e.Current); Assert.True(e.MoveNext()); Assert.Same(c3, e.Current); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); // Ended Assert.Throws<InvalidOperationException>(() => ignored = e.Current); e.Reset(); } } [Fact] public static void X509CertificateCollectionThrowsArgumentNullException() { using (X509Certificate certificate = new X509Certificate()) { Assert.Throws<ArgumentNullException>(() => new X509CertificateCollection((X509Certificate[])null)); Assert.Throws<ArgumentNullException>(() => new X509CertificateCollection((X509CertificateCollection)null)); X509CertificateCollection collection = new X509CertificateCollection { certificate }; Assert.Throws<ArgumentNullException>(() => collection[0] = null); Assert.Throws<ArgumentNullException>(() => collection.Add(null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509Certificate[])null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509CertificateCollection)null)); Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0)); Assert.Throws<ArgumentNullException>(() => collection.Insert(0, null)); Assert.Throws<ArgumentNullException>(() => collection.Remove(null)); IList ilist = (IList)collection; Assert.Throws<ArgumentNullException>(() => ilist[0] = null); Assert.Throws<ArgumentNullException>(() => ilist.Add(null)); Assert.Throws<ArgumentNullException>(() => ilist.CopyTo(null, 0)); Assert.Throws<ArgumentNullException>(() => ilist.Insert(0, null)); Assert.Throws<ArgumentNullException>(() => ilist.Remove(null)); } AssertExtensions.Throws<ArgumentNullException, NullReferenceException>( () => new X509CertificateCollection.X509CertificateEnumerator(null)); } [Fact] public static void X509Certificate2CollectionThrowsArgumentNullException() { using (X509Certificate2 certificate = new X509Certificate2()) { Assert.Throws<ArgumentNullException>(() => new X509Certificate2Collection((X509Certificate2[])null)); Assert.Throws<ArgumentNullException>(() => new X509Certificate2Collection((X509Certificate2Collection)null)); X509Certificate2Collection collection = new X509Certificate2Collection { certificate }; Assert.Throws<ArgumentNullException>(() => collection[0] = null); Assert.Throws<ArgumentNullException>(() => collection.Add((X509Certificate)null)); Assert.Throws<ArgumentNullException>(() => collection.Add((X509Certificate2)null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509Certificate[])null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509CertificateCollection)null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509Certificate2[])null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509Certificate2Collection)null)); Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0)); Assert.Throws<ArgumentNullException>(() => collection.Insert(0, (X509Certificate)null)); Assert.Throws<ArgumentNullException>(() => collection.Insert(0, (X509Certificate2)null)); Assert.Throws<ArgumentNullException>(() => collection.Remove((X509Certificate)null)); Assert.Throws<ArgumentNullException>(() => collection.Remove((X509Certificate2)null)); Assert.Throws<ArgumentNullException>(() => collection.RemoveRange((X509Certificate2[])null)); Assert.Throws<ArgumentNullException>(() => collection.RemoveRange((X509Certificate2Collection)null)); Assert.Throws<ArgumentNullException>(() => collection.Import((byte[])null)); Assert.Throws<ArgumentNullException>(() => collection.Import((string)null)); IList ilist = (IList)collection; Assert.Throws<ArgumentNullException>(() => ilist[0] = null); Assert.Throws<ArgumentNullException>(() => ilist.Add(null)); Assert.Throws<ArgumentNullException>(() => ilist.CopyTo(null, 0)); Assert.Throws<ArgumentNullException>(() => ilist.Insert(0, null)); Assert.Throws<ArgumentNullException>(() => ilist.Remove(null)); } } [Fact] public static void X509CertificateCollectionThrowsArgumentOutOfRangeException() { using (X509Certificate certificate = new X509Certificate()) { X509CertificateCollection collection = new X509CertificateCollection { certificate }; Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => collection[collection.Count]); Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => collection[collection.Count] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(-1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(collection.Count + 1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(collection.Count)); IList ilist = (IList)collection; Assert.Throws<ArgumentOutOfRangeException>(() => ilist[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[collection.Count]); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[-1] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[collection.Count] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.Insert(-1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.Insert(collection.Count + 1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.RemoveAt(collection.Count)); } } [Fact] public static void X509Certificate2CollectionThrowsArgumentOutOfRangeException() { using (X509Certificate2 certificate = new X509Certificate2()) { X509Certificate2Collection collection = new X509Certificate2Collection { certificate }; Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => collection[collection.Count]); Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => collection[collection.Count] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(-1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(collection.Count + 1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(collection.Count)); IList ilist = (IList)collection; Assert.Throws<ArgumentOutOfRangeException>(() => ilist[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[collection.Count]); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[-1] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[collection.Count] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.Insert(-1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.Insert(collection.Count + 1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.RemoveAt(collection.Count)); } } [Fact] public static void X509CertificateCollectionContains() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection collection = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); Assert.True(collection.Contains(c1)); Assert.True(collection.Contains(c2)); Assert.True(collection.Contains(c3)); Assert.False(collection.Contains(null)); IList ilist = (IList)collection; Assert.True(ilist.Contains(c1)); Assert.True(ilist.Contains(c2)); Assert.True(ilist.Contains(c3)); Assert.False(ilist.Contains(null)); Assert.False(ilist.Contains("Bogus")); } } [Fact] public static void X509Certificate2CollectionContains() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection collection = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); Assert.True(collection.Contains(c1)); Assert.True(collection.Contains(c2)); Assert.True(collection.Contains(c3)); // Note: X509Certificate2Collection.Contains used to throw ArgumentNullException, but it // has been deliberately changed to no longer throw to match the behavior of // X509CertificateCollection.Contains and the IList.Contains implementation, which do not // throw. if (PlatformDetection.IsFullFramework) { Assert.Throws<ArgumentNullException>(() => collection.Contains(null)); } else { Assert.False(collection.Contains(null)); } IList ilist = (IList)collection; Assert.True(ilist.Contains(c1)); Assert.True(ilist.Contains(c2)); Assert.True(ilist.Contains(c3)); Assert.False(ilist.Contains(null)); Assert.False(ilist.Contains("Bogus")); } } [Fact] public static void X509CertificateCollectionEnumeratorModification() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); X509CertificateCollection.X509CertificateEnumerator e = cc.GetEnumerator(); cc.Add(c1); // Collection changed. Assert.Throws<InvalidOperationException>(() => e.MoveNext()); Assert.Throws<InvalidOperationException>(() => e.Reset()); } } [Fact] public static void X509Certificate2CollectionEnumeratorModification() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); X509Certificate2Enumerator e = cc.GetEnumerator(); cc.Add(c1); // Collection changed. Assert.Throws<InvalidOperationException>(() => e.MoveNext()); Assert.Throws<InvalidOperationException>(() => e.Reset()); } } [Fact] public static void X509CertificateCollectionAdd() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) { X509CertificateCollection cc = new X509CertificateCollection(); int idx = cc.Add(c1); Assert.Equal(0, idx); Assert.Same(c1, cc[0]); idx = cc.Add(c2); Assert.Equal(1, idx); Assert.Same(c2, cc[1]); Assert.Throws<ArgumentNullException>(() => cc.Add(null)); IList il = new X509CertificateCollection(); idx = il.Add(c1); Assert.Equal(0, idx); Assert.Same(c1, il[0]); idx = il.Add(c2); Assert.Equal(1, idx); Assert.Same(c2, il[1]); Assert.Throws<ArgumentNullException>(() => il.Add(null)); } } [Fact] public static void X509CertificateCollectionAsIList() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) { IList il = new X509CertificateCollection(); il.Add(c1); il.Add(c2); Assert.Throws<ArgumentNullException>(() => il[0] = null); } } [Fact] // On Desktop, list is untyped so it allows arbitrary types in it [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public static void X509CertificateCollectionAsIListBogusEntry() { using (X509Certificate2 c = new X509Certificate2()) { IList il = new X509CertificateCollection(); il.Add(c); string bogus = "Bogus"; AssertExtensions.Throws<ArgumentException>("value", () => il[0] = bogus); AssertExtensions.Throws<ArgumentException>("value", () => il.Add(bogus)); AssertExtensions.Throws<ArgumentException>("value", () => il.Remove(bogus)); AssertExtensions.Throws<ArgumentException>("value", () => il.Insert(0, bogus)); } } [Fact] public static void AddDoesNotClone() { using (X509Certificate2 c1 = new X509Certificate2()) { X509Certificate2Collection coll = new X509Certificate2Collection(); coll.Add(c1); Assert.Same(c1, coll[0]); } } [Fact] public static void ImportStoreSavedAsCerData() { using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { using (ImportedCollection ic = Cert.Import(TestData.StoreSavedAsCerData)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(1, count); using (X509Certificate2 c = cc2[0]) { // pfxCer was loaded directly, cc2[0] was Imported, two distinct copies. Assert.NotSame(pfxCer, c); Assert.Equal(pfxCer, c); Assert.Equal(pfxCer.Thumbprint, c.Thumbprint); } } } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // StoreSavedAsSerializedCerData not supported on Unix public static void ImportStoreSavedAsSerializedCerData_Windows() { using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, Cert.EphemeralIfPossible)) { using (ImportedCollection ic = Cert.Import(TestData.StoreSavedAsSerializedCerData)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(1, count); using (X509Certificate2 c = cc2[0]) { // pfxCer was loaded directly, cc2[0] was Imported, two distinct copies. Assert.NotSame(pfxCer, c); Assert.Equal(pfxCer, c); Assert.Equal(pfxCer.Thumbprint, c.Thumbprint); } } } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // StoreSavedAsSerializedCerData not supported on Unix public static void ImportStoreSavedAsSerializedCerData_Unix() { X509Certificate2Collection cc2 = new X509Certificate2Collection(); Assert.ThrowsAny<CryptographicException>(() => cc2.Import(TestData.StoreSavedAsSerializedCerData)); Assert.Equal(0, cc2.Count); } [Theory] [MemberData(nameof(StorageFlags))] [PlatformSpecific(TestPlatforms.Windows)] // StoreSavedAsSerializedStoreData not supported on Unix public static void ImportStoreSavedAsSerializedStoreData_Windows(X509KeyStorageFlags keyStorageFlags) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, keyStorageFlags)) using (ImportedCollection ic = Cert.Import(TestData.StoreSavedAsSerializedStoreData)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(2, count); X509Certificate2[] cs = cc2.ToArray().OrderBy(c => c.Subject).ToArray(); Assert.NotSame(msCer, cs[0]); Assert.Equal(msCer, cs[0]); Assert.Equal(msCer.Thumbprint, cs[0].Thumbprint); Assert.NotSame(pfxCer, cs[1]); Assert.Equal(pfxCer, cs[1]); Assert.Equal(pfxCer.Thumbprint, cs[1].Thumbprint); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // StoreSavedAsSerializedStoreData not supported on Unix public static void ImportStoreSavedAsSerializedStoreData_Unix() { X509Certificate2Collection cc2 = new X509Certificate2Collection(); Assert.ThrowsAny<CryptographicException>(() => cc2.Import(TestData.StoreSavedAsSerializedStoreData)); Assert.Equal(0, cc2.Count); } [Fact] public static void ImportStoreSavedAsPfxData() { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, Cert.EphemeralIfPossible)) using (ImportedCollection ic = Cert.Import(TestData.StoreSavedAsPfxData)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(2, count); X509Certificate2[] cs = cc2.ToArray().OrderBy(c => c.Subject).ToArray(); Assert.NotSame(msCer, cs[0]); Assert.Equal(msCer, cs[0]); Assert.Equal(msCer.Thumbprint, cs[0].Thumbprint); Assert.NotSame(pfxCer, cs[1]); Assert.Equal(pfxCer, cs[1]); Assert.Equal(pfxCer.Thumbprint, cs[1].Thumbprint); } } [Fact] public static void ImportInvalidData() { X509Certificate2Collection cc2 = new X509Certificate2Collection(); Assert.ThrowsAny<CryptographicException>(() => cc2.Import(new byte[] { 0, 1, 1, 2, 3, 5, 8, 13, 21 })); } [Theory] [MemberData(nameof(StorageFlags))] public static void ImportFromFileTests(X509KeyStorageFlags storageFlags) { using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, storageFlags)) { using (ImportedCollection ic = Cert.Import(Path.Combine("TestData", "My.pfx"), TestData.PfxDataPassword, storageFlags)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(1, count); using (X509Certificate2 c = cc2[0]) { // pfxCer was loaded directly, cc2[0] was Imported, two distinct copies. Assert.NotSame(pfxCer, c); Assert.Equal(pfxCer, c); Assert.Equal(pfxCer.Thumbprint, c.Thumbprint); } } } } [Fact] [ActiveIssue(2745, TestPlatforms.AnyUnix)] public static void ImportMultiplePrivateKeysPfx() { using (ImportedCollection ic = Cert.Import(TestData.MultiPrivateKeyPfx)) { X509Certificate2Collection collection = ic.Collection; Assert.Equal(2, collection.Count); foreach (X509Certificate2 cert in collection) { Assert.True(cert.HasPrivateKey, "cert.HasPrivateKey"); } } } [Fact] public static void ExportCert() { TestExportSingleCert(X509ContentType.Cert); } [Fact] public static void ExportCert_SecureString() { TestExportSingleCert_SecureStringPassword(X509ContentType.Cert); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // SerializedCert not supported on Unix public static void ExportSerializedCert_Windows() { TestExportSingleCert(X509ContentType.SerializedCert); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // SerializedCert not supported on Unix public static void ExportSerializedCert_Unix() { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var ecdsa256Cer = new X509Certificate2(TestData.ECDsa256Certificate)) { X509Certificate2Collection cc = new X509Certificate2Collection(new[] { msCer, ecdsa256Cer }); Assert.Throws<PlatformNotSupportedException>(() => cc.Export(X509ContentType.SerializedCert)); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // SerializedStore not supported on Unix public static void ExportSerializedStore_Windows() { TestExportStore(X509ContentType.SerializedStore); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // SerializedStore not supported on Unix public static void ExportSerializedStore_Unix() { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var ecdsa256Cer = new X509Certificate2(TestData.ECDsa256Certificate)) { X509Certificate2Collection cc = new X509Certificate2Collection(new[] { msCer, ecdsa256Cer }); Assert.Throws<PlatformNotSupportedException>(() => cc.Export(X509ContentType.SerializedStore)); } } [Fact] public static void ExportPkcs7() { TestExportStore(X509ContentType.Pkcs7); } [Fact] public static void X509CertificateCollectionSyncRoot() { var cc = new X509CertificateCollection(); Assert.NotNull(((ICollection)cc).SyncRoot); Assert.Same(((ICollection)cc).SyncRoot, ((ICollection)cc).SyncRoot); } [Fact] public static void ExportEmpty_Cert() { var collection = new X509Certificate2Collection(); byte[] exported = collection.Export(X509ContentType.Cert); Assert.Null(exported); } [Fact] [ActiveIssue(2746, TestPlatforms.AnyUnix)] public static void ExportEmpty_Pkcs12() { var collection = new X509Certificate2Collection(); byte[] exported = collection.Export(X509ContentType.Pkcs12); // The empty PFX is legal, the answer won't be null. Assert.NotNull(exported); } [Fact] [ActiveIssue(16705, TestPlatforms.OSX)] public static void ExportUnrelatedPfx() { // Export multiple certificates which are not part of any kind of certificate chain. // Nothing in the PKCS12 structure requires they're related, but it might be an underlying // assumption of the provider. using (var cert1 = new X509Certificate2(TestData.MsCertificate)) using (var cert2 = new X509Certificate2(TestData.ComplexNameInfoCert)) using (var cert3 = new X509Certificate2(TestData.CertWithPolicies)) { var collection = new X509Certificate2Collection { cert1, cert2, cert3, }; byte[] exported = collection.Export(X509ContentType.Pkcs12); using (ImportedCollection ic = Cert.Import(exported)) { X509Certificate2Collection importedCollection = ic.Collection; // Verify that the two collections contain the same certificates, // but the order isn't really a factor. Assert.Equal(collection.Count, importedCollection.Count); // Compare just the subject names first, because it's the easiest thing to read out of the failure message. string[] subjects = new string[collection.Count]; string[] importedSubjects = new string[collection.Count]; for (int i = 0; i < collection.Count; i++) { subjects[i] = collection[i].GetNameInfo(X509NameType.SimpleName, false); importedSubjects[i] = importedCollection[i].GetNameInfo(X509NameType.SimpleName, false); } Assert.Equal(subjects, importedSubjects); // But, really, the collections should be equivalent // (after being coerced to IEnumerable<X509Certificate2>) Assert.Equal(collection.OfType<X509Certificate2>(), importedCollection.OfType<X509Certificate2>()); } } } [Fact] public static void MultipleImport() { var collection = new X509Certificate2Collection(); try { collection.Import(Path.Combine("TestData", "DummyTcpServer.pfx"), (string)null, Cert.EphemeralIfPossible); collection.Import(TestData.PfxData, TestData.PfxDataPassword, Cert.EphemeralIfPossible); Assert.Equal(3, collection.Count); } finally { foreach (X509Certificate2 cert in collection) { cert.Dispose(); } } } [Fact] [ActiveIssue(2743, TestPlatforms.AnyUnix & ~TestPlatforms.OSX)] public static void ExportMultiplePrivateKeys() { var collection = new X509Certificate2Collection(); try { collection.Import(Path.Combine("TestData", "DummyTcpServer.pfx"), (string)null, X509KeyStorageFlags.Exportable | Cert.EphemeralIfPossible); collection.Import(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.Exportable | Cert.EphemeralIfPossible); // Pre-condition, we have multiple private keys int originalPrivateKeyCount = collection.OfType<X509Certificate2>().Count(c => c.HasPrivateKey); Assert.Equal(2, originalPrivateKeyCount); // Export, re-import. byte[] exported; bool expectSuccess = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); try { exported = collection.Export(X509ContentType.Pkcs12); } catch (PlatformNotSupportedException) { // [ActiveIssue(2743, TestPlatforms.AnyUnix)] // Our Unix builds can't export more than one private key in a single PFX, so this is // their exit point. // // If Windows gets here, or any exception other than PlatformNotSupportedException is raised, // let that fail the test. if (expectSuccess) { throw; } return; } // As the other half of issue 2743, if we make it this far we better be Windows (or remove the catch // above) Assert.True(expectSuccess, "Test is expected to fail on this platform"); using (ImportedCollection ic = Cert.Import(exported)) { X509Certificate2Collection importedCollection = ic.Collection; Assert.Equal(collection.Count, importedCollection.Count); int importedPrivateKeyCount = importedCollection.OfType<X509Certificate2>().Count(c => c.HasPrivateKey); Assert.Equal(originalPrivateKeyCount, importedPrivateKeyCount); } } finally { foreach (X509Certificate2 cert in collection) { cert.Dispose(); } } } [Fact] [ActiveIssue(26397, TestPlatforms.OSX)] public static void CanAddMultipleCertsWithSinglePrivateKey() { using (var oneWithKey = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.Exportable | Cert.EphemeralIfPossible)) using (var twoWithoutKey = new X509Certificate2(TestData.ComplexNameInfoCert)) { Assert.True(oneWithKey.HasPrivateKey); var col = new X509Certificate2Collection { oneWithKey, twoWithoutKey, }; Assert.Equal(1, col.Cast<X509Certificate2>().Count(x => x.HasPrivateKey)); Assert.Equal(2, col.Count); byte[] buffer = col.Export(X509ContentType.Pfx); using (ImportedCollection newCollection = Cert.Import(buffer)) { Assert.Equal(2, newCollection.Collection.Count); } } } [Fact] public static void X509CertificateCollectionCopyTo() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); X509Certificate[] array1 = new X509Certificate[cc.Count]; cc.CopyTo(array1, 0); Assert.Same(c1, array1[0]); Assert.Same(c2, array1[1]); Assert.Same(c3, array1[2]); X509Certificate[] array2 = new X509Certificate[cc.Count]; ((ICollection)cc).CopyTo(array2, 0); Assert.Same(c1, array2[0]); Assert.Same(c2, array2[1]); Assert.Same(c3, array2[2]); } } public static void X509ChainElementCollection_CopyTo_NonZeroLowerBound_ThrowsIndexOutOfRangeException() { using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes)) using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes)) using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes)) using (var chainHolder = new ChainHolder()) { X509Chain chain = chainHolder.Chain; chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot); chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags; chain.Build(microsoftDotCom); ICollection collection = chain.ChainElements; Array array = Array.CreateInstance(typeof(object), new int[] { 10 }, new int[] { 10 }); Assert.Throws<IndexOutOfRangeException>(() => collection.CopyTo(array, 0)); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Arrays with non-zero lower bounds are not supported.")] public static void X509ExtensionCollection_CopyTo_NonZeroLowerBound_ThrowsIndexOutOfRangeException() { using (X509Certificate2 cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, Cert.EphemeralIfPossible)) { ICollection collection = cert.Extensions; Array array = Array.CreateInstance(typeof(object), new int[] { 10 }, new int[] { 10 }); Assert.Throws<IndexOutOfRangeException>(() => collection.CopyTo(array, 0)); } } [Fact] public static void X509CertificateCollectionIndexOf() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, Cert.EphemeralIfPossible)) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2 }); Assert.Equal(0, cc.IndexOf(c1)); Assert.Equal(1, cc.IndexOf(c2)); IList il = cc; Assert.Equal(0, il.IndexOf(c1)); Assert.Equal(1, il.IndexOf(c2)); } } [Fact] public static void X509CertificateCollectionRemove() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, Cert.EphemeralIfPossible)) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2 }); cc.Remove(c1); Assert.Equal(1, cc.Count); Assert.Same(c2, cc[0]); cc.Remove(c2); Assert.Equal(0, cc.Count); AssertExtensions.Throws<ArgumentException>(null, () => cc.Remove(c2)); IList il = new X509CertificateCollection(new X509Certificate[] { c1, c2 }); il.Remove(c1); Assert.Equal(1, il.Count); Assert.Same(c2, il[0]); il.Remove(c2); Assert.Equal(0, il.Count); AssertExtensions.Throws<ArgumentException>(null, () => il.Remove(c2)); } } [Fact] public static void X509CertificateCollectionRemoveAt() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); cc.RemoveAt(0); Assert.Equal(2, cc.Count); Assert.Same(c2, cc[0]); Assert.Same(c3, cc[1]); cc.RemoveAt(1); Assert.Equal(1, cc.Count); Assert.Same(c2, cc[0]); cc.RemoveAt(0); Assert.Equal(0, cc.Count); IList il = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); il.RemoveAt(0); Assert.Equal(2, il.Count); Assert.Same(c2, il[0]); Assert.Same(c3, il[1]); il.RemoveAt(1); Assert.Equal(1, il.Count); Assert.Same(c2, il[0]); il.RemoveAt(0); Assert.Equal(0, il.Count); } } [Fact] public static void X509Certificate2CollectionRemoveRangeArray() { using (X509Certificate2 c1 = new X509Certificate2(TestData.MsCertificate)) using (X509Certificate2 c2 = new X509Certificate2(TestData.DssCer)) using (X509Certificate2 c1Clone = new X509Certificate2(TestData.MsCertificate)) { X509Certificate2[] array = new X509Certificate2[] { c1, c2 }; X509Certificate2Collection cc = new X509Certificate2Collection(array); cc.RemoveRange(array); Assert.Equal(0, cc.Count); cc = new X509Certificate2Collection(array); cc.RemoveRange(new X509Certificate2[] { c2, c1 }); Assert.Equal(0, cc.Count); cc = new X509Certificate2Collection(array); cc.RemoveRange(new X509Certificate2[] { c1 }); Assert.Equal(1, cc.Count); Assert.Same(c2, cc[0]); cc = new X509Certificate2Collection(array); Assert.Throws<ArgumentNullException>(() => cc.RemoveRange(new X509Certificate2[] { c1, c2, null })); Assert.Equal(2, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); cc = new X509Certificate2Collection(array); Assert.Throws<ArgumentNullException>(() => cc.RemoveRange(new X509Certificate2[] { c1, null, c2 })); Assert.Equal(2, cc.Count); Assert.Same(c2, cc[0]); Assert.Same(c1, cc[1]); // Remove c1Clone (success) // Remove c1 (exception) // Add c1Clone back // End state: { c1, c2 } => { c2, c1Clone } cc = new X509Certificate2Collection(array); AssertExtensions.Throws<ArgumentException>(null, () => cc.RemoveRange(new X509Certificate2[] { c1Clone, c1, c2 })); Assert.Equal(2, cc.Count); Assert.Same(c2, cc[0]); Assert.Same(c1Clone, cc[1]); } } [Fact] public static void X509Certificate2CollectionRemoveRangeCollection() { using (X509Certificate2 c1 = new X509Certificate2(TestData.MsCertificate)) using (X509Certificate2 c2 = new X509Certificate2(TestData.DssCer)) using (X509Certificate2 c1Clone = new X509Certificate2(TestData.MsCertificate)) using (X509Certificate c3 = new X509Certificate()) { X509Certificate2[] array = new X509Certificate2[] { c1, c2 }; X509Certificate2Collection cc = new X509Certificate2Collection(array); cc.RemoveRange(new X509Certificate2Collection { c1, c2 }); Assert.Equal(0, cc.Count); cc = new X509Certificate2Collection(array); cc.RemoveRange(new X509Certificate2Collection { c2, c1 }); Assert.Equal(0, cc.Count); cc = new X509Certificate2Collection(array); cc.RemoveRange(new X509Certificate2Collection { c1 }); Assert.Equal(1, cc.Count); Assert.Same(c2, cc[0]); cc = new X509Certificate2Collection(array); X509Certificate2Collection collection = new X509Certificate2Collection(); collection.Add(c1); collection.Add(c2); ((IList)collection).Add(c3); // Add non-X509Certificate2 object Assert.Throws<InvalidCastException>(() => cc.RemoveRange(collection)); Assert.Equal(2, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); cc = new X509Certificate2Collection(array); collection = new X509Certificate2Collection(); collection.Add(c1); ((IList)collection).Add(c3); // Add non-X509Certificate2 object collection.Add(c2); Assert.Throws<InvalidCastException>(() => cc.RemoveRange(collection)); Assert.Equal(2, cc.Count); Assert.Same(c2, cc[0]); Assert.Same(c1, cc[1]); // Remove c1Clone (success) // Remove c1 (exception) // Add c1Clone back // End state: { c1, c2 } => { c2, c1Clone } cc = new X509Certificate2Collection(array); collection = new X509Certificate2Collection { c1Clone, c1, c2, }; AssertExtensions.Throws<ArgumentException>(null, () => cc.RemoveRange(collection)); Assert.Equal(2, cc.Count); Assert.Same(c2, cc[0]); Assert.Same(c1Clone, cc[1]); } } [Fact] public static void X509CertificateCollectionIndexer() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); cc[0] = c3; cc[1] = c2; cc[2] = c1; Assert.Same(c3, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c1, cc[2]); IList il = cc; il[0] = c1; il[1] = c2; il[2] = c3; Assert.Same(c1, il[0]); Assert.Same(c2, il[1]); Assert.Same(c3, il[2]); } } [Fact] public static void X509Certificate2CollectionIndexer() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); cc[0] = c3; cc[1] = c2; cc[2] = c1; Assert.Same(c3, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c1, cc[2]); IList il = cc; il[0] = c1; il[1] = c2; il[2] = c3; Assert.Same(c1, il[0]); Assert.Same(c2, il[1]); Assert.Same(c3, il[2]); } } [Fact] public static void X509CertificateCollectionInsertAndClear() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(); cc.Insert(0, c1); cc.Insert(1, c2); cc.Insert(2, c3); Assert.Equal(3, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c3, cc[2]); cc.Clear(); Assert.Equal(0, cc.Count); cc.Add(c1); cc.Add(c3); Assert.Equal(2, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c3, cc[1]); cc.Insert(1, c2); Assert.Equal(3, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c3, cc[2]); cc.Clear(); Assert.Equal(0, cc.Count); IList il = cc; il.Insert(0, c1); il.Insert(1, c2); il.Insert(2, c3); Assert.Equal(3, il.Count); Assert.Same(c1, il[0]); Assert.Same(c2, il[1]); Assert.Same(c3, il[2]); il.Clear(); Assert.Equal(0, il.Count); il.Add(c1); il.Add(c3); Assert.Equal(2, il.Count); Assert.Same(c1, il[0]); Assert.Same(c3, il[1]); il.Insert(1, c2); Assert.Equal(3, il.Count); Assert.Same(c1, il[0]); Assert.Same(c2, il[1]); Assert.Same(c3, il[2]); il.Clear(); Assert.Equal(0, il.Count); } } [Fact] public static void X509Certificate2CollectionInsert() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(); cc.Insert(0, c3); cc.Insert(0, c2); cc.Insert(0, c1); Assert.Equal(3, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c3, cc[2]); } } [Fact] public static void X509Certificate2CollectionCopyTo() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); X509Certificate2[] array1 = new X509Certificate2[cc.Count]; cc.CopyTo(array1, 0); Assert.Same(c1, array1[0]); Assert.Same(c2, array1[1]); Assert.Same(c3, array1[2]); X509Certificate2[] array2 = new X509Certificate2[cc.Count]; ((ICollection)cc).CopyTo(array2, 0); Assert.Same(c1, array2[0]); Assert.Same(c2, array2[1]); Assert.Same(c3, array2[2]); } } [Fact] public static void X509CertificateCollectionGetHashCode() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); int expected = c1.GetHashCode() + c2.GetHashCode() + c3.GetHashCode(); Assert.Equal(expected, cc.GetHashCode()); } } [Fact] public static void X509Certificate2CollectionGetHashCode() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); int expected = c1.GetHashCode() + c2.GetHashCode() + c3.GetHashCode(); Assert.Equal(expected, cc.GetHashCode()); } } [Fact] public static void X509ChainElementCollection_IndexerVsEnumerator() { using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes)) using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes)) using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes)) using (var chainHolder = new ChainHolder()) { X509Chain chain = chainHolder.Chain; chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot); chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer); chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; // Halfway between microsoftDotCom's NotBefore and NotAfter // This isn't a boundary condition test. chain.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; bool valid = chain.Build(microsoftDotCom); Assert.True(valid, "Precondition: Chain built validly"); int position = 0; foreach (X509ChainElement chainElement in chain.ChainElements) { X509ChainElement indexerElement = chain.ChainElements[position]; Assert.NotNull(chainElement); Assert.NotNull(indexerElement); Assert.Same(indexerElement, chainElement); position++; } } } [Fact] public static void X509ExtensionCollection_OidIndexer_ByOidValue() { const string SubjectKeyIdentifierOidValue = "2.5.29.14"; using (var cert = new X509Certificate2(TestData.MsCertificate)) { X509ExtensionCollection extensions = cert.Extensions; // Stable index can be counted on by ExtensionsTests.ReadExtensions(). X509Extension skidExtension = extensions[1]; // Precondition: We've found the SKID extension. Assert.Equal(SubjectKeyIdentifierOidValue, skidExtension.Oid.Value); X509Extension byValue = extensions[SubjectKeyIdentifierOidValue]; Assert.Same(skidExtension, byValue); } } [Fact] public static void X509ExtensionCollection_OidIndexer_ByOidFriendlyName() { const string SubjectKeyIdentifierOidValue = "2.5.29.14"; using (var cert = new X509Certificate2(TestData.MsCertificate)) { X509ExtensionCollection extensions = cert.Extensions; // Stable index can be counted on by ExtensionsTests.ReadExtensions(). X509Extension skidExtension = extensions[1]; // Precondition: We've found the SKID extension. Assert.Equal(SubjectKeyIdentifierOidValue, skidExtension.Oid.Value); // The friendly name of "Subject Key Identifier" is localized, but // we can use the invariant form to ask for the friendly name to ask // for the extension by friendly name. X509Extension byFriendlyName = extensions[new Oid(SubjectKeyIdentifierOidValue).FriendlyName]; Assert.Same(skidExtension, byFriendlyName); } } [Fact] public static void X509ExtensionCollection_OidIndexer_NoMatchByValue() { const string RsaOidValue = "1.2.840.113549.1.1.1"; using (var cert = new X509Certificate2(TestData.MsCertificate)) { X509ExtensionCollection extensions = cert.Extensions; X509Extension byValue = extensions[RsaOidValue]; Assert.Null(byValue); } } [Fact] public static void X509ExtensionCollection_OidIndexer_NoMatchByFriendlyName() { const string RsaOidValue = "1.2.840.113549.1.1.1"; using (var cert = new X509Certificate2(TestData.MsCertificate)) { X509ExtensionCollection extensions = cert.Extensions; // While "RSA" is actually invariant, this just guarantees that we're doing // the system-preferred lookup. X509Extension byFriendlyName = extensions[new Oid(RsaOidValue).FriendlyName]; Assert.Null(byFriendlyName); } } private static void TestExportSingleCert_SecureStringPassword(X509ContentType ct) { using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.CreatePfxDataPasswordSecureString(), Cert.EphemeralIfPossible)) { TestExportSingleCert(ct, pfxCer); } } private static void TestExportSingleCert(X509ContentType ct) { using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, Cert.EphemeralIfPossible)) { TestExportSingleCert(ct, pfxCer); } } private static void TestExportSingleCert(X509ContentType ct, X509Certificate2 pfxCer) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { msCer, pfxCer }); byte[] blob = cc.Export(ct); Assert.Equal(ct, X509Certificate2.GetCertContentType(blob)); using (ImportedCollection ic = Cert.Import(blob)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(1, count); using (X509Certificate2 c = cc2[0]) { Assert.NotSame(msCer, c); Assert.NotSame(pfxCer, c); Assert.True(msCer.Equals(c) || pfxCer.Equals(c)); } } } } private static void TestExportStore(X509ContentType ct) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, Cert.EphemeralIfPossible)) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { msCer, pfxCer }); byte[] blob = cc.Export(ct); Assert.Equal(ct, X509Certificate2.GetCertContentType(blob)); using (ImportedCollection ic = Cert.Import(blob)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(2, count); X509Certificate2[] cs = cc2.ToArray().OrderBy(c => c.Subject).ToArray(); using (X509Certificate2 first = cs[0]) { Assert.NotSame(msCer, first); Assert.Equal(msCer, first); } using (X509Certificate2 second = cs[1]) { Assert.NotSame(pfxCer, second); Assert.Equal(pfxCer, second); } } } } public static IEnumerable<object[]> StorageFlags => CollectionImportTests.StorageFlags; private static X509Certificate2[] ToArray(this X509Certificate2Collection col) { X509Certificate2[] array = new X509Certificate2[col.Count]; for (int i = 0; i < col.Count; i++) { array[i] = col[i]; } return array; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////// // // Class: TextInfo // // Purpose: This Class defines behaviors specific to a writing system. // A writing system is the collection of scripts and // orthographic rules required to represent a language as text. // // Date: [....] 31, 1999 // //////////////////////////////////////////////////////////////////////////// using System.Security; namespace System.Globalization { using System; using System.Text; using System.Threading; using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security.Permissions; using System.Diagnostics.Contracts; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public partial class TextInfo : ICloneable, IDeserializationCallback { //--------------------------------------------------------------------// // Internal Information // //--------------------------------------------------------------------// // // Variables. // [OptionalField(VersionAdded = 2)] private String m_listSeparator; [OptionalField(VersionAdded = 2)] private bool m_isReadOnly = false; // // In Whidbey we had several names: // m_win32LangID is the name of the culture, but only used for (de)serialization. // customCultureName is the name of the creating custom culture (if custom) In combination with m_win32LangID // this is authoratative, ie when deserializing. // m_cultureTableRecord was the data record of the creating culture. (could have different name if custom) // m_textInfoID is the LCID of the textinfo itself (no longer used) // m_name is the culture name (from cultureinfo.name) // // In Silverlight/Arrowhead this is slightly different: // m_cultureName is the name of the creating culture. Note that we consider this authoratative, // if the culture's textinfo changes when deserializing, then behavior may change. // (ala Whidbey behavior). This is the only string Arrowhead needs to serialize. // m_cultureData is the data that backs this class. // m_textInfoName is the actual name of the textInfo (from cultureData.STEXTINFO) // m_textInfoName can be the same as m_cultureName on Silverlight since the OS knows // how to do the sorting. However in the desktop, when we call the sorting dll, it doesn't // know how to resolve custom locle names to sort ids so we have to have alredy resolved this. // [OptionalField(VersionAdded = 3)] private String m_cultureName; // Name of the culture that created this text info [NonSerialized]private CultureData m_cultureData; // Data record for the culture that made us, not for this textinfo [NonSerialized]private String m_textInfoName; // Name of the text info we're using (ie: m_cultureData.STEXTINFO) #if !MONO [NonSerialized]private IntPtr m_dataHandle; // Sort handle [NonSerialized]private IntPtr m_handleOrigin; #endif [NonSerialized]private bool? m_IsAsciiCasingSameAsInvariant; // Invariant text info internal static TextInfo Invariant { get { if (s_Invariant == null) s_Invariant = new TextInfo(CultureData.Invariant); return s_Invariant; } } internal volatile static TextInfo s_Invariant; //////////////////////////////////////////////////////////////////////// // // TextInfo Constructors // // Implements CultureInfo.TextInfo. // //////////////////////////////////////////////////////////////////////// internal TextInfo(CultureData cultureData) { // This is our primary data source, we don't need most of the rest of this this.m_cultureData = cultureData; this.m_cultureName = this.m_cultureData.CultureName; this.m_textInfoName = this.m_cultureData.STEXTINFO; #if !FEATURE_CORECLR && !MONO IntPtr handleOrigin; this.m_dataHandle = CompareInfo.InternalInitSortHandle(m_textInfoName, out handleOrigin); this.m_handleOrigin = handleOrigin; #endif } //////////////////////////////////////////////////////////////////////// // // Serialization / Deserialization // // Note that we have to respect the Whidbey behavior for serialization compatibility // //////////////////////////////////////////////////////////////////////// #region Serialization // the following fields are defined to keep the compatibility with Whidbey. // don't change/remove the names/types of these fields. [OptionalField(VersionAdded = 2)] private string customCultureName; #if !FEATURE_CORECLR // the following fields are defined to keep compatibility with Everett. // don't change/remove the names/types of these fields. [OptionalField(VersionAdded = 1)] internal int m_nDataItem; [OptionalField(VersionAdded = 1)] internal bool m_useUserOverride; [OptionalField(VersionAdded = 1)] internal int m_win32LangID; #endif // !FEATURE_CORECLR [OnDeserializing] private void OnDeserializing(StreamingContext ctx) { // Clear these so we can check if we've fixed them yet this.m_cultureData = null; this.m_cultureName = null; } private void OnDeserialized() { // this method will be called twice because of the support of IDeserializationCallback if (this.m_cultureData == null) { if (this.m_cultureName == null) { // This is whidbey data, get it from customCultureName/win32langid if (this.customCultureName != null) { // They gave a custom cultuer name, so use that this.m_cultureName = this.customCultureName; } #if FEATURE_USE_LCID else { if (m_win32LangID == 0) { // m_cultureName and m_win32LangID are nulls which means we got uninitialized textinfo serialization stream. // To be compatible with v2/3/3.5 we need to return ar-SA TextInfo in this case. m_cultureName = "ar-SA"; } else { // No custom culture, use the name from the LCID m_cultureName = CultureInfo.GetCultureInfo(m_win32LangID).m_cultureData.CultureName; } } #endif } // Get the text info name belonging to that culture this.m_cultureData = CultureInfo.GetCultureInfo(m_cultureName).m_cultureData; this.m_textInfoName = this.m_cultureData.STEXTINFO; #if !FEATURE_CORECLR && !MONO IntPtr handleOrigin; this.m_dataHandle = CompareInfo.InternalInitSortHandle(m_textInfoName, out handleOrigin); this.m_handleOrigin = handleOrigin; #endif } } [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { OnDeserialized(); } [OnSerializing] private void OnSerializing(StreamingContext ctx) { #if !FEATURE_CORECLR // Initialize the fields Whidbey expects: // Whidbey expected this, so set it, but the value doesn't matter much this.m_useUserOverride = false; #endif // FEATURE_CORECLR // Relabel our name since Whidbey expects it to be called customCultureName this.customCultureName = this.m_cultureName; #if FEATURE_USE_LCID // Ignore the m_win32LangId because whidbey'll just get it by name if we make it the LOCALE_CUSTOM_UNSPECIFIED. this.m_win32LangID = (CultureInfo.GetCultureInfo(m_cultureName)).LCID; #endif } #endregion Serialization // // Internal ordinal comparison functions // [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] internal static int GetHashCodeOrdinalIgnoreCase(String s) { return GetHashCodeOrdinalIgnoreCase(s, false, 0); } [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] internal static int GetHashCodeOrdinalIgnoreCase(String s, bool forceRandomizedHashing, long additionalEntropy) { // This is the same as an case insensitive hash for Invariant // (not necessarily true for sorting, but OK for casing & then we apply normal hash code rules) return (Invariant.GetCaseInsensitiveHashCode(s, forceRandomizedHashing, additionalEntropy)); } #if !MONO [System.Security.SecuritySafeCritical] [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] internal static unsafe bool TryFastFindStringOrdinalIgnoreCase(int searchFlags, String source, int startIndex, String value, int count, ref int foundIndex) { return InternalTryFindStringOrdinalIgnoreCase(searchFlags, source, count, startIndex, value, value.Length, ref foundIndex); } #endif // This function doesn't check arguments. Please do check in the caller. // The underlying unmanaged code will assert the sanity of arguments. [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] internal static unsafe int CompareOrdinalIgnoreCase(String str1, String str2) { // Compare the whole string and ignore case. return InternalCompareStringOrdinalIgnoreCase(str1, 0, str2, 0, str1.Length, str2.Length); } // This function doesn't check arguments. Please do check in the caller. // The underlying unmanaged code will assert the sanity of arguments. [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] internal static unsafe int CompareOrdinalIgnoreCaseEx(String strA, int indexA, String strB, int indexB, int lengthA, int lengthB ) { Contract.Assert(strA.Length >= indexA + lengthA, "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strA.Length >= indexA + lengthA"); Contract.Assert(strB.Length >= indexB + lengthB, "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strB.Length >= indexB + lengthB"); return InternalCompareStringOrdinalIgnoreCase(strA, indexA, strB, indexB, lengthA, lengthB); } [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] internal static int IndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count) { Contract.Assert(source != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated source != null"); Contract.Assert(value != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated value != null"); Contract.Assert(startIndex + count <= source.Length, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex + count <= source.Length"); // We return 0 if both inputs are empty strings if (source.Length == 0 && value.Length == 0) { return 0; } // fast path #if !MONO int ret = -1; if (TryFastFindStringOrdinalIgnoreCase(Microsoft.Win32.Win32Native.FIND_FROMSTART, source, startIndex, value, count, ref ret)) return ret; #endif // the search space within [source] starts at offset [startIndex] inclusive and includes // [count] characters (thus the last included character is at index [startIndex + count -1] // [end] is the index of the next character after the search space // (it points past the end of the search space) int end = startIndex + count; // maxStartIndex is the index beyond which we never *start* searching, inclusive; in other words; // a search could include characters beyond maxStartIndex, but we'd never begin a search at an // index strictly greater than maxStartIndex. int maxStartIndex = end - value.Length; for (; startIndex <= maxStartIndex; startIndex++) { // We should always have the same or more characters left to search than our actual pattern Contract.Assert(end - startIndex >= value.Length); // since this is an ordinal comparison, we can assume that the lengths must match if (CompareOrdinalIgnoreCaseEx(source, startIndex, value, 0, value.Length, value.Length) == 0) { return startIndex; } } // Not found return -1; } [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] internal static int LastIndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count) { Contract.Assert(source != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated source != null"); Contract.Assert(value != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated value != null"); Contract.Assert(startIndex - count+1 >= 0, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex - count+1 >= 0"); Contract.Assert(startIndex <= source.Length, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex <= source.Length"); // If value is Empty, the return value is startIndex if (value.Length == 0) { return startIndex; } // fast path #if !MONO int ret = -1; if (TryFastFindStringOrdinalIgnoreCase(Microsoft.Win32.Win32Native.FIND_FROMEND, source, startIndex, value, count, ref ret)) return ret; #endif // the search space within [source] ends at offset [startIndex] inclusive // and includes [count] characters // minIndex is the first included character and is at index [startIndex - count + 1] int minIndex = startIndex - count + 1; // First place we can find it is start index - (value.length -1) if (value.Length > 0) { startIndex -= (value.Length - 1); } for (; startIndex >= minIndex; startIndex--) { if (CompareOrdinalIgnoreCaseEx(source, startIndex, value, 0, value.Length, value.Length) == 0) { return startIndex; } } // Not found return -1; } //////////////////////////////////////////////////////////////////////// // // CodePage // // Returns the number of the code page used by this writing system. // The type parameter can be any of the following values: // ANSICodePage // OEMCodePage // MACCodePage // //////////////////////////////////////////////////////////////////////// #if !FEATURE_CORECLR public virtual int ANSICodePage { get { return (this.m_cultureData.IDEFAULTANSICODEPAGE); } } public virtual int OEMCodePage { get { return (this.m_cultureData.IDEFAULTOEMCODEPAGE); } } public virtual int MacCodePage { get { return (this.m_cultureData.IDEFAULTMACCODEPAGE); } } public virtual int EBCDICCodePage { get { return (this.m_cultureData.IDEFAULTEBCDICCODEPAGE); } } #endif //////////////////////////////////////////////////////////////////////// // // LCID // // We need a way to get an LCID from outside of the BCL. This prop is the way. // NOTE: neutral cultures will cause GPS incorrect LCIDS from this // //////////////////////////////////////////////////////////////////////// #if FEATURE_USE_LCID [System.Runtime.InteropServices.ComVisible(false)] public int LCID { get { // Just use the LCID from our text info name return CultureInfo.GetCultureInfo(this.m_textInfoName).LCID; } } #endif //////////////////////////////////////////////////////////////////////// // // CultureName // // The name of the culture associated with the current TextInfo. // //////////////////////////////////////////////////////////////////////// [System.Runtime.InteropServices.ComVisible(false)] public string CultureName { get { return(this.m_textInfoName); } } //////////////////////////////////////////////////////////////////////// // // IsReadOnly // // Detect if the object is readonly. // //////////////////////////////////////////////////////////////////////// [System.Runtime.InteropServices.ComVisible(false)] public bool IsReadOnly { get { return (m_isReadOnly); } } //////////////////////////////////////////////////////////////////////// // // Clone // // Is the implementation of IColnable. // //////////////////////////////////////////////////////////////////////// [System.Runtime.InteropServices.ComVisible(false)] public virtual Object Clone() { object o = MemberwiseClone(); ((TextInfo) o).SetReadOnlyState(false); return (o); } //////////////////////////////////////////////////////////////////////// // // ReadOnly // // Create a cloned readonly instance or return the input one if it is // readonly. // //////////////////////////////////////////////////////////////////////// [System.Runtime.InteropServices.ComVisible(false)] public static TextInfo ReadOnly(TextInfo textInfo) { if (textInfo == null) { throw new ArgumentNullException("textInfo"); } Contract.EndContractBlock(); if (textInfo.IsReadOnly) { return (textInfo); } TextInfo clonedTextInfo = (TextInfo)(textInfo.MemberwiseClone()); clonedTextInfo.SetReadOnlyState(true); return (clonedTextInfo); } private void VerifyWritable() { if (m_isReadOnly) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); } Contract.EndContractBlock(); } internal void SetReadOnlyState(bool readOnly) { m_isReadOnly = readOnly; } //////////////////////////////////////////////////////////////////////// // // ListSeparator // // Returns the string used to separate items in a list. // //////////////////////////////////////////////////////////////////////// public virtual String ListSeparator { [System.Security.SecuritySafeCritical] // auto-generated get { if (m_listSeparator == null) { m_listSeparator = this.m_cultureData.SLIST; } return (m_listSeparator); } [System.Runtime.InteropServices.ComVisible(false)] set { if (value == null) { throw new ArgumentNullException("value", Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); VerifyWritable(); m_listSeparator = value; } } //////////////////////////////////////////////////////////////////////// // // ToLower // // Converts the character or string to lower case. Certain locales // have different casing semantics from the file systems in Win32. // //////////////////////////////////////////////////////////////////////// [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual char ToLower(char c) { if(IsAscii(c) && IsAsciiCasingSameAsInvariant) { return ToLowerAsciiInvariant(c); } #if MONO return ToLowerInternal (c); #else return (InternalChangeCaseChar(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, c, false)); #endif } [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual String ToLower(String str) { if (str == null) { throw new ArgumentNullException("str"); } Contract.EndContractBlock(); #if MONO return ToLowerInternal (str); #else return InternalChangeCaseString(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, str, false); #endif } static private Char ToLowerAsciiInvariant(Char c) { if ('A' <= c && c <= 'Z') { c = (Char)(c | 0x20); } return c; } //////////////////////////////////////////////////////////////////////// // // ToUpper // // Converts the character or string to upper case. Certain locales // have different casing semantics from the file systems in Win32. // //////////////////////////////////////////////////////////////////////// [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual char ToUpper(char c) { if (IsAscii(c) && IsAsciiCasingSameAsInvariant) { return ToUpperAsciiInvariant(c); } #if MONO return ToUpperInternal (c); #else return (InternalChangeCaseChar(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, c, true)); #endif } [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual String ToUpper(String str) { if (str == null) { throw new ArgumentNullException("str"); } Contract.EndContractBlock(); #if MONO return ToUpperInternal (str); #else return InternalChangeCaseString(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, str, true); #endif } static private Char ToUpperAsciiInvariant(Char c) { if ('a' <= c && c <= 'z') { c = (Char)(c & ~0x20); } return c; } static private bool IsAscii(Char c) { return c < 0x80; } private bool IsAsciiCasingSameAsInvariant { get { if (m_IsAsciiCasingSameAsInvariant == null) { #if MONO m_IsAsciiCasingSameAsInvariant = !(m_cultureData.SISO639LANGNAME == "az" || m_cultureData.SISO639LANGNAME == "tr"); #else m_IsAsciiCasingSameAsInvariant = CultureInfo.GetCultureInfo(m_textInfoName).CompareInfo.Compare("abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", CompareOptions.IgnoreCase) == 0; #endif } return (bool)m_IsAsciiCasingSameAsInvariant; } } //////////////////////////////////////////////////////////////////////// // // Equals // // Implements Object.Equals(). Returns a boolean indicating whether // or not object refers to the same CultureInfo as the current instance. // //////////////////////////////////////////////////////////////////////// public override bool Equals(Object obj) { TextInfo that = obj as TextInfo; if (that != null) { return this.CultureName.Equals(that.CultureName); } return (false); } //////////////////////////////////////////////////////////////////////// // // GetHashCode // // Implements Object.GetHashCode(). Returns the hash code for the // CultureInfo. The hash code is guaranteed to be the same for CultureInfo A // and B where A.Equals(B) is true. // //////////////////////////////////////////////////////////////////////// public override int GetHashCode() { return (this.CultureName.GetHashCode()); } //////////////////////////////////////////////////////////////////////// // // ToString // // Implements Object.ToString(). Returns a string describing the // TextInfo. // //////////////////////////////////////////////////////////////////////// public override String ToString() { return ("TextInfo - " + this.m_cultureData.CultureName); } // // Titlecasing: // ----------- // Titlecasing refers to a casing practice wherein the first letter of a word is an uppercase letter // and the rest of the letters are lowercase. The choice of which words to titlecase in headings // and titles is dependent on language and local conventions. For example, "The Merry Wives of Windor" // is the appropriate titlecasing of that play's name in English, with the word "of" not titlecased. // In German, however, the title is "Die lustigen Weiber von Windsor," and both "lustigen" and "von" // are not titlecased. In French even fewer words are titlecased: "Les joyeuses commeres de Windsor." // // Moreover, the determination of what actually constitutes a word is language dependent, and this can // influence which letter or letters of a "word" are uppercased when titlecasing strings. For example // "l'arbre" is considered two words in French, whereas "can't" is considered one word in English. // // // Differences between UNICODE 5.0 and the .NET Framework ( #if !FEATURE_CORECLR public unsafe String ToTitleCase(String str) { if (str==null) { throw new ArgumentNullException("str"); } Contract.EndContractBlock(); if (str.Length == 0) { return (str); } StringBuilder result = new StringBuilder(); String lowercaseData = null; for (int i = 0; i < str.Length; i++) { UnicodeCategory charType; int charLen; charType = CharUnicodeInfo.InternalGetUnicodeCategory(str, i, out charLen); if (Char.CheckLetter(charType)) { // Do the titlecasing for the first character of the word. i = AddTitlecaseLetter(ref result, ref str, i, charLen) + 1; // // Convert the characters until the end of the this word // to lowercase. // int lowercaseStart = i; // // Use hasLowerCase flag to prevent from lowercasing acronyms (like "URT", "USA", etc) // This is in line with Word 2000 behavior of titlecasing. // bool hasLowerCase = (charType == UnicodeCategory.LowercaseLetter); // Use a loop to find all of the other letters following this letter. while (i < str.Length) { charType = CharUnicodeInfo.InternalGetUnicodeCategory(str, i, out charLen); if (IsLetterCategory(charType)) { if (charType == UnicodeCategory.LowercaseLetter) { hasLowerCase = true; } i += charLen; } else if (str[i] == '\'') { // i++; if (hasLowerCase) { if (lowercaseData==null) { lowercaseData = this.ToLower(str); } result.Append(lowercaseData, lowercaseStart, i - lowercaseStart); } else { result.Append(str, lowercaseStart, i - lowercaseStart); } lowercaseStart = i; hasLowerCase = true; } else if (!IsWordSeparator(charType)) { // This category is considered to be part of the word. // This is any category that is marked as false in wordSeprator array. i+= charLen; } else { // A word separator. Break out of the loop. break; } } int count = i - lowercaseStart; if (count>0) { if (hasLowerCase) { if (lowercaseData==null) { lowercaseData = this.ToLower(str); } result.Append(lowercaseData, lowercaseStart, count); } else { result.Append(str, lowercaseStart, count); } } if (i < str.Length) { // not a letter, just append it i = AddNonLetter(ref result, ref str, i, charLen); } } else { // not a letter, just append it i = AddNonLetter(ref result, ref str, i, charLen); } } return (result.ToString()); } private static int AddNonLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen) { Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!"); if (charLen == 2) { // Surrogate pair result.Append(input[inputIndex++]); result.Append(input[inputIndex]); } else { result.Append(input[inputIndex]); } return inputIndex; } private int AddTitlecaseLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen) { Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!"); // for surrogate pairs do a simple ToUpper operation on the substring if (charLen == 2) { // Surrogate pair result.Append( this.ToUpper(input.Substring(inputIndex, charLen)) ); inputIndex++; } else { switch (input[inputIndex]) { // // For AppCompat, the Titlecase Case Mapping data from NDP 2.0 is used below. // case (char)0x01C4: // DZ with Caron -> Dz with Caron case (char)0x01C5: // Dz with Caron -> Dz with Caron case (char)0x01C6: // dz with Caron -> Dz with Caron result.Append( (char)0x01C5 ); break; case (char)0x01C7: // LJ -> Lj case (char)0x01C8: // Lj -> Lj case (char)0x01C9: // lj -> Lj result.Append( (char)0x01C8 ); break; case (char)0x01CA: // NJ -> Nj case (char)0x01CB: // Nj -> Nj case (char)0x01CC: // nj -> Nj result.Append( (char)0x01CB ); break; case (char)0x01F1: // DZ -> Dz case (char)0x01F2: // Dz -> Dz case (char)0x01F3: // dz -> Dz result.Append( (char)0x01F2 ); break; default: result.Append( this.ToUpper(input[inputIndex]) ); break; } } return inputIndex; } // // Used in ToTitleCase(): // When we find a starting letter, the following array decides if a category should be // considered as word seprator or not. // private const int wordSeparatorMask = /* false */ (0 << 0) | // UppercaseLetter = 0, /* false */ (0 << 1) | // LowercaseLetter = 1, /* false */ (0 << 2) | // TitlecaseLetter = 2, /* false */ (0 << 3) | // ModifierLetter = 3, /* false */ (0 << 4) | // OtherLetter = 4, /* false */ (0 << 5) | // NonSpacingMark = 5, /* false */ (0 << 6) | // SpacingCombiningMark = 6, /* false */ (0 << 7) | // EnclosingMark = 7, /* false */ (0 << 8) | // DecimalDigitNumber = 8, /* false */ (0 << 9) | // LetterNumber = 9, /* false */ (0 << 10) | // OtherNumber = 10, /* true */ (1 << 11) | // SpaceSeparator = 11, /* true */ (1 << 12) | // LineSeparator = 12, /* true */ (1 << 13) | // ParagraphSeparator = 13, /* true */ (1 << 14) | // Control = 14, /* true */ (1 << 15) | // Format = 15, /* false */ (0 << 16) | // Surrogate = 16, /* false */ (0 << 17) | // PrivateUse = 17, /* true */ (1 << 18) | // ConnectorPunctuation = 18, /* true */ (1 << 19) | // DashPunctuation = 19, /* true */ (1 << 20) | // OpenPunctuation = 20, /* true */ (1 << 21) | // ClosePunctuation = 21, /* true */ (1 << 22) | // InitialQuotePunctuation = 22, /* true */ (1 << 23) | // FinalQuotePunctuation = 23, /* true */ (1 << 24) | // OtherPunctuation = 24, /* true */ (1 << 25) | // MathSymbol = 25, /* true */ (1 << 26) | // CurrencySymbol = 26, /* true */ (1 << 27) | // ModifierSymbol = 27, /* true */ (1 << 28) | // OtherSymbol = 28, /* false */ (0 << 29); // OtherNotAssigned = 29; private static bool IsWordSeparator(UnicodeCategory category) { return (wordSeparatorMask & (1 << (int)category)) != 0; } private static bool IsLetterCategory(UnicodeCategory uc) { return (uc == UnicodeCategory.UppercaseLetter || uc == UnicodeCategory.LowercaseLetter || uc == UnicodeCategory.TitlecaseLetter || uc == UnicodeCategory.ModifierLetter || uc == UnicodeCategory.OtherLetter); } #endif // IsRightToLeft // // Returns true if the dominant direction of text and UI such as the relative position of buttons and scroll bars // [System.Runtime.InteropServices.ComVisible(false)] public bool IsRightToLeft { get { return this.m_cultureData.IsRightToLeft; } } #if FEATURE_SERIALIZATION /// <internalonly/> void IDeserializationCallback.OnDeserialization(Object sender) { OnDeserialized(); } #endif // // Get case-insensitive hash code for the specified string. // // NOTENOTE: this is an internal function. The caller should verify the string // is not null before calling this. Currenlty, CaseInsensitiveHashCodeProvider // does that. // [System.Security.SecuritySafeCritical] // auto-generated internal unsafe int GetCaseInsensitiveHashCode(String str) { return GetCaseInsensitiveHashCode(str, false, 0); } [System.Security.SecuritySafeCritical] // auto-generated internal unsafe int GetCaseInsensitiveHashCode(String str, bool forceRandomizedHashing, long additionalEntropy) { // Validate inputs if (str==null) { throw new ArgumentNullException("str"); } Contract.EndContractBlock(); #if MONO return this == s_Invariant ? GetInvariantCaseInsensitiveHashCode (str) : StringComparer.CurrentCultureIgnoreCase.GetHashCode (str); #else // Return our result return (InternalGetCaseInsHash(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, str, forceRandomizedHashing, additionalEntropy)); #endif } #if MONO unsafe int GetInvariantCaseInsensitiveHashCode (string str) { fixed (char * c = str) { char * cc = c; char * end = cc + str.Length - 1; int h = 0; for (;cc < end; cc += 2) { h = (h << 5) - h + Char.ToUpperInvariant (*cc); h = (h << 5) - h + Char.ToUpperInvariant (cc [1]); } ++end; if (cc < end) h = (h << 5) - h + Char.ToUpperInvariant (*cc); return h; } } #else // Change case (ToUpper/ToLower) -- COMNlsInfo::InternalChangeCaseChar [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static unsafe extern char InternalChangeCaseChar(IntPtr handle, IntPtr handleOrigin, String localeName, char ch, bool isToUpper); // Change case (ToUpper/ToLower) -- COMNlsInfo::InternalChangeCaseString [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static unsafe extern String InternalChangeCaseString(IntPtr handle, IntPtr handleOrigin, String localeName, String str, bool isToUpper); // Get case insensitive hash -- ComNlsInfo::InternalGetCaseInsHash [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static unsafe extern int InternalGetCaseInsHash(IntPtr handle, IntPtr handleOrigin, String localeName, String str, bool forceRandomizedHashing, long additionalEntropy); // Call ::CompareStringOrdinal -- ComNlsInfo::InternalCompareStringOrdinalIgnoreCase // Start at indexes and compare for length characters (or remainder of string if length == -1) [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static unsafe extern int InternalCompareStringOrdinalIgnoreCase(String string1, int index1, String string2, int index2, int length1, int length2); // ComNlsInfo::InternalTryFindStringOrdinalIgnoreCase attempts a faster IndexOf/LastIndexOf OrdinalIgnoreCase using a kernel function. // Returns true if FindStringOrdinal was handled, with foundIndex set to the target's index into the source // Returns false when FindStringOrdinal wasn't handled [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private static unsafe extern bool InternalTryFindStringOrdinalIgnoreCase(int searchFlags, String source, int sourceCount, int startIndex, String target, int targetCount, ref int foundIndex); #endif } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.IdentityModel { using System; using System.IdentityModel.Tokens; using System.Security.Claims; using RST = System.IdentityModel.Protocols.WSTrust.RequestSecurityToken; using RSTR = System.IdentityModel.Protocols.WSTrust.RequestSecurityTokenResponse; using System.IdentityModel.Protocols.WSTrust; using System.IdentityModel.Configuration; /// <summary> /// Abstract class for building WS-Security token services. /// </summary> public abstract class SecurityTokenService { /// <summary> /// This class is used to maintain request state across asynchronous calls /// within the security token service. /// </summary> protected class FederatedAsyncState { RST _request; ClaimsPrincipal _claimsPrincipal; SecurityTokenHandler _securityTokenHandler; IAsyncResult _result; /// <summary> /// Copy constructor. /// </summary> /// <param name="federatedAsyncState">The input FederatedAsyncState instance.</param> /// <exception cref="ArgumentNullException">The input 'FederatedAsyncState' is null.</exception> public FederatedAsyncState(FederatedAsyncState federatedAsyncState) { if (null == federatedAsyncState) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("FederatedAsyncState"); } _request = federatedAsyncState.Request; _claimsPrincipal = federatedAsyncState.ClaimsPrincipal; _securityTokenHandler = federatedAsyncState.SecurityTokenHandler; _result = federatedAsyncState.Result; } /// <summary> /// Constructs a FederatedAsyncState instance with token request, principal, and the async result. /// </summary> /// <param name="request">The token request instance.</param> /// <param name="principal">The identity of the token requestor.</param> /// <param name="result">The async result.</param> /// <exception cref="ArgumentNullException">When the given request or async result is null.</exception> public FederatedAsyncState(RST request, ClaimsPrincipal principal, IAsyncResult result) { if (null == request) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request"); } if (null == result) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("result"); } _request = request; _claimsPrincipal = principal; _result = result; } /// <summary> /// Gets the token request instance. /// </summary> public RST Request { get { return _request; } } /// <summary> /// Gets the ClaimsPrincipal instance. /// </summary> public ClaimsPrincipal ClaimsPrincipal { get { return _claimsPrincipal; } } /// <summary> /// Gets or sets the SecurityTokenHandler to be used during an async token-issuance call. /// </summary> public SecurityTokenHandler SecurityTokenHandler { get { return _securityTokenHandler; } set { _securityTokenHandler = value; } } /// <summary> /// Gets the async result. /// </summary> public IAsyncResult Result { get { return _result; } } } // // STS settings // SecurityTokenServiceConfiguration _securityTokenServiceConfiguration; ClaimsPrincipal _principal; RequestSecurityToken _request; SecurityTokenDescriptor _tokenDescriptor; /// <summary> /// Use this constructor to initialize scope provider and token issuer certificate. /// </summary> /// <param name="securityTokenServiceConfiguration">The SecurityTokenServiceConfiguration that will have the related settings for the STS.</param> protected SecurityTokenService(SecurityTokenServiceConfiguration securityTokenServiceConfiguration) { if (securityTokenServiceConfiguration == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityTokenServiceConfiguration"); } _securityTokenServiceConfiguration = securityTokenServiceConfiguration; } /// <summary> /// Async Cancel. /// </summary> /// <param name="principal">The identity of the token requestor.</param> /// <param name="request">The security token request which includes request message as well as other client /// related information such as authorization context.</param> /// <param name="callback">The async call back.</param> /// <param name="state">The state object.</param> /// <returns>The async result.</returns> public virtual IAsyncResult BeginCancel(ClaimsPrincipal principal, RST request, AsyncCallback callback, object state) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID3141, (request != null ? request.RequestType : "Cancel")))); } /// <summary> /// Begins async call for GetScope routine. Default implementation will throw a NotImplementedExcetion. /// Refer MSDN articles on Using an AsyncCallback Delegate to End an Asynchronous Operation. /// </summary> /// <param name="principal">The identity of the token requestor.</param> /// <param name="request">The request.</param> /// <param name="callback">The callback to be invoked when the user Asynchronous operation completed.</param> /// <param name="state">The state object.</param> /// <returns>IAsyncResult. Represents the status of an asynchronous operation. This will be passed into /// EndGetScope.</returns> protected virtual IAsyncResult BeginGetScope(ClaimsPrincipal principal, RST request, AsyncCallback callback, object state) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException(SR.GetString(SR.ID2081))); } /// <summary> /// Begins the async call of the Issue request. /// </summary> /// <param name="principal">The <see cref="ClaimsPrincipal"/> to issue a token for.</param> /// <param name="request">The security token request which includes request message as well as other client /// related information such as authorization context.</param> /// <param name="callback">The async call back.</param> /// <param name="state">The state object.</param> /// <returns>The async result.</returns> public virtual IAsyncResult BeginIssue(ClaimsPrincipal principal, RST request, AsyncCallback callback, object state) { if (request == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request"); } _principal = principal; _request = request; // // Step 1: Validate the rst: check if this STS is capable of handling this // rst // ValidateRequest(request); // // FederatedAsyncState asyncState = new FederatedAsyncState(request, principal, new TypedAsyncResult<RSTR>(callback, state)); BeginGetScope(principal, request, OnGetScopeComplete, asyncState); return asyncState.Result; } /// <summary> /// Async Renew. /// </summary> /// <param name="principal">The <see cref="ClaimsPrincipal"/> to renew.</param> /// <param name="request">The security token request which includes request message as well as other client /// related information such as authorization context.</param> /// <param name="callback">The async call back.</param> /// <param name="state">The state object.</param> /// <returns>The async result.</returns> public virtual IAsyncResult BeginRenew(ClaimsPrincipal principal, RST request, AsyncCallback callback, object state) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID3141, (request != null && request.RequestType != null ? request.RequestType : "Renew")))); } /// <summary> /// Async Validate. /// </summary> /// <param name="principal">The <see cref="ClaimsPrincipal"/> to validate.</param> /// <param name="request">The security token request which includes request message as well as other client /// related information such as authorization context.</param> /// <param name="callback">The async call back.</param> /// <param name="state">The state object.</param> /// <returns>The async result.</returns> public virtual IAsyncResult BeginValidate(ClaimsPrincipal principal, RST request, AsyncCallback callback, object state) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID3141, (request != null && request.RequestType != null ? request.RequestType : "Validate")))); } /// <summary> /// Cancel. /// </summary> /// <param name="principal">The <see cref="ClaimsPrincipal"/> to cancel.</param> /// <param name="request">The request.</param> /// <returns>The response.</returns> public virtual RSTR Cancel(ClaimsPrincipal principal, RST request) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID3141, (request != null && request.RequestType != null ? request.RequestType : "Cancel")))); } /// <summary> /// Creates an instance of a <see cref="SecurityTokenDescriptor"/>. /// </summary> /// <param name="request">The incoming token request.</param> /// <param name="scope">The <see cref="Scope"/> object returned from <see cref="SecurityTokenService.GetScope"/>.</param> /// <returns>The <see cref="SecurityTokenDescriptor"/>.</returns> /// <remarks>Invoked during token issuance after <see cref="SecurityTokenService.GetScope"/>.</remarks> protected virtual SecurityTokenDescriptor CreateSecurityTokenDescriptor(RST request, Scope scope) { if (request == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request"); } if (scope == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("scope"); } SecurityTokenDescriptor d = new SecurityTokenDescriptor(); d.AppliesToAddress = scope.AppliesToAddress; d.ReplyToAddress = scope.ReplyToAddress; d.SigningCredentials = scope.SigningCredentials; if (null == d.SigningCredentials) { d.SigningCredentials = this.SecurityTokenServiceConfiguration.SigningCredentials; } // // The encrypting credentials specified on the Scope object // are invariant relative to a specific RP. Allowing the STS to // cache the Scope for each RP. // Our default implementation will generate the symmetric bulk // encryption key on the fly. // if (scope.EncryptingCredentials != null && scope.EncryptingCredentials.SecurityKey is AsymmetricSecurityKey ) { if ((request.EncryptionAlgorithm == null || request.EncryptionAlgorithm == SecurityAlgorithms.Aes256Encryption) && (request.SecondaryParameters == null || request.SecondaryParameters.EncryptionAlgorithm == null || request.SecondaryParameters.EncryptionAlgorithm == SecurityAlgorithms.Aes256Encryption) ) { d.EncryptingCredentials = new EncryptedKeyEncryptingCredentials(scope.EncryptingCredentials, 256, SecurityAlgorithms.Aes256Encryption); } } return d; } /// <summary> /// Gets the STS's name. /// </summary> /// <returns>Returns the issuer name.</returns> protected virtual string GetIssuerName() { return SecurityTokenServiceConfiguration.TokenIssuerName; } /// <summary> /// Checks the IssuerName for validity (non-null) /// </summary> private string GetValidIssuerName() { string issuerName = GetIssuerName(); if (string.IsNullOrEmpty(issuerName)) { throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID2083)); } return issuerName; } /// <summary> /// Gets the proof token. /// </summary> /// <param name="request">The incoming token request.</param> /// <param name="scope">The scope instance encapsulating information about the relying party.</param> /// <returns>The newly created proof decriptor that could be either asymmetric proof descriptor or symmetric proof descriptor or null in the bearer token case.</returns> protected virtual ProofDescriptor GetProofToken(RST request, Scope scope) { if (request == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request"); } if (scope == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("scope"); } EncryptingCredentials requestorWrappingCredentials = GetRequestorProofEncryptingCredentials(request); if (scope.EncryptingCredentials != null && !(scope.EncryptingCredentials.SecurityKey is AsymmetricSecurityKey)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityTokenException(SR.GetString(SR.ID4179))); } EncryptingCredentials targetWrappingCredentials = scope.EncryptingCredentials; // // Generate the proof key // string keyType = (string.IsNullOrEmpty(request.KeyType)) ? KeyTypes.Symmetric : request.KeyType; ProofDescriptor result = null; if (StringComparer.Ordinal.Equals(keyType, KeyTypes.Asymmetric)) { // // Asymmetric is only supported with UseKey // if (request.UseKey == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID3091))); } result = new AsymmetricProofDescriptor(request.UseKey.SecurityKeyIdentifier); } else if (StringComparer.Ordinal.Equals(keyType, KeyTypes.Symmetric)) { // // Only support PSHA1. Overwrite STS to support custom key algorithm // if (request.ComputedKeyAlgorithm != null && !StringComparer.Ordinal.Equals(request.ComputedKeyAlgorithm, ComputedKeyAlgorithms.Psha1)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new RequestFailedException(SR.GetString(SR.ID2011, request.ComputedKeyAlgorithm))); } // // We must wrap the symmetric key inside the security token // if (targetWrappingCredentials == null && scope.SymmetricKeyEncryptionRequired) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new RequestFailedException(SR.GetString(SR.ID4007))); } // // We are encrypting the proof token or the server entropy using client's encrypting credential if present, // which will be used to encrypt the key during serialization. // Otherwise, we can only send back the key in plain text. However, the current implementation of // WSTrustServiceContract sets the rst.ProofEncryption = null by default. Therefore, the server entropy // or the proof token will be sent in plain text no matter the client's entropy is sent encrypted or unencrypted. // if (request.KeySizeInBits.HasValue) { if (request.Entropy != null) { result = new SymmetricProofDescriptor(request.KeySizeInBits.Value, targetWrappingCredentials, requestorWrappingCredentials, request.Entropy.GetKeyBytes(), request.EncryptWith); } else { result = new SymmetricProofDescriptor(request.KeySizeInBits.Value, targetWrappingCredentials, requestorWrappingCredentials, request.EncryptWith); } } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new RequestFailedException(SR.GetString(SR.ID2059))); } } else if (StringComparer.Ordinal.Equals(keyType, KeyTypes.Bearer)) { // // Intentionally empty, no proofDescriptor // } return result; } /// <summary> /// Get the Requestor's Proof encrypting credentials. /// </summary> /// <param name="request">RequestSecurityToken</param> /// <returns>EncryptingCredentials</returns> /// <exception cref="ArgumentNullException">Input argument 'request' is null.</exception> protected virtual EncryptingCredentials GetRequestorProofEncryptingCredentials(RST request) { if (request == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request"); } if (request.ProofEncryption == null) { return null; } X509SecurityToken x509SecurityToken = request.ProofEncryption.GetSecurityToken() as X509SecurityToken; if (x509SecurityToken != null) { return new X509EncryptingCredentials(x509SecurityToken); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new RequestFailedException(SR.GetString(SR.ID2084, request.ProofEncryption.GetSecurityToken()))); } /// <summary> /// Gets the lifetime of the issued token. /// Normally called with the lifetime that arrived in the RST. /// The algorithm for calculating the token lifetime is: /// requestLifeTime (in) LifeTime (returned) /// Created Expires Created Expires /// null null DateTime.UtcNow DateTime.UtcNow + SecurityTokenServiceConfiguration.DefaultTokenLifetime /// C null C C + SecurityTokenServiceConfiguration.DefaultTokenLifetime /// null E DateTime.UtcNow E /// C E C E /// </summary> /// <param name="requestLifetime">The requestor's desired life time.</param> protected virtual Lifetime GetTokenLifetime(Lifetime requestLifetime) { DateTime created; DateTime expires; if (requestLifetime == null) { created = DateTime.UtcNow; expires = DateTimeUtil.Add(created, _securityTokenServiceConfiguration.DefaultTokenLifetime); } else { if (requestLifetime.Created.HasValue) { created = requestLifetime.Created.Value; } else { created = DateTime.UtcNow; } if (requestLifetime.Expires.HasValue) { expires = requestLifetime.Expires.Value; } else { expires = DateTimeUtil.Add(created, _securityTokenServiceConfiguration.DefaultTokenLifetime); } } VerifyComputedLifetime(created, expires); return new Lifetime(created, expires); } private void VerifyComputedLifetime(DateTime created, DateTime expires) { DateTime utcNow = DateTime.UtcNow; // if expires in past, throw if (DateTimeUtil.Add(DateTimeUtil.ToUniversalTime(expires), _securityTokenServiceConfiguration.MaxClockSkew) < utcNow) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID2075, created, expires, utcNow))); } // if creation time specified is greater than one day in future, throw if (DateTimeUtil.ToUniversalTime(created) > DateTimeUtil.Add(utcNow + TimeSpan.FromDays(1), _securityTokenServiceConfiguration.MaxClockSkew)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID2076, created, expires, utcNow))); } // if expiration time is equal to or before creation time, throw. This would be hard to make happen as the Lifetime class checks this condition in the constructor if (expires <= created) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID2077, created, expires))); } // if timespan is greater than allowed, throw if ((expires - created) > _securityTokenServiceConfiguration.MaximumTokenLifetime) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID2078, created, expires, _securityTokenServiceConfiguration.MaximumTokenLifetime))); } return; } /// <summary> /// Creates the RSTR and finally read the information from TokenDescriptor and apply /// those to the RSTR. /// </summary> /// <param name="request">The RST from the request.</param> /// <param name="tokenDescriptor">The token descriptor which contains the information for the issued token.</param> /// <returns>The RSTR for the response, null if the token descriptor is null.</returns> protected virtual RSTR GetResponse(RST request, SecurityTokenDescriptor tokenDescriptor) { if (tokenDescriptor != null) { RSTR rstr = new RSTR(request); tokenDescriptor.ApplyTo(rstr); // Set the replyTo address of the relying party (if any) in the outgoing RSTR from the generated // token descriptor (STD) based on the table below: // // RST.ReplyTo STD.ReplyToAddress RSTR.ReplyTo // =========== ==================== ============ // Set Not Set Not Set // Set Set Set to STD.ReplyToAddress // Not Set Not Set Not Set // Not Set Set Not Set // if (request.ReplyTo != null) { rstr.ReplyTo = tokenDescriptor.ReplyToAddress; } // // Set the appliesTo address (if any) in the outgoing RSTR from the generated token descriptor. // if (!string.IsNullOrEmpty(tokenDescriptor.AppliesToAddress)) { rstr.AppliesTo = new EndpointReference(tokenDescriptor.AppliesToAddress); } return rstr; } else { return null; } } /// <summary> /// Async Cancel. /// </summary> /// <param name="result"></param> /// <returns></returns> public virtual RSTR EndCancel(IAsyncResult result) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID3141, "Cancel"))); } /// <summary> /// Ends the Async call to BeginGetScope. Default implementation will throw a NotImplementedException. /// Refer MSDN articles on Using an AsyncCallback Delegate to End an Asynchronous Operation. /// </summary> /// <param name="result">Typed Async result which contains the result. This is the same instance of /// IAsyncResult that was returned by the BeginGetScope method.</param> /// <returns>The scope.</returns> protected virtual Scope EndGetScope(IAsyncResult result) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException(SR.GetString(SR.ID2081))); } /// <summary> /// Ends the async call of Issue request. This would finally return the RequestSecurityTokenResponse. /// </summary> /// <param name="result">The async result returned from the BeginIssue method.</param> /// <returns>The security token response.</returns> public virtual RSTR EndIssue(IAsyncResult result) { if (result == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("result"); } if (!(result is TypedAsyncResult<RSTR>)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID2012, typeof(TypedAsyncResult<RSTR>), result.GetType()))); } return TypedAsyncResult<RSTR>.End(result); } /// <summary> /// Async Renew. /// </summary> /// <param name="result"></param> /// <returns></returns> public virtual RSTR EndRenew(IAsyncResult result) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID3141, "Renew"))); } /// <summary> /// Async Validate. /// </summary> /// <param name="result"></param> /// <returns></returns> public virtual RSTR EndValidate(IAsyncResult result) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID3141, "Validate"))); } /// <summary> /// Retrieves the relying party information. Override this method to provide a custom scope with /// relying party related information. /// </summary> /// <param name="principal">The identity of the token requestor.</param> /// <param name="request">The request message.</param> /// <returns>A scope object based on the relying party related information.</returns> protected abstract Scope GetScope(ClaimsPrincipal principal, RST request); /// <summary> /// When overridden in a derived class, this method should return a collection of output subjects to be included in the issued token. /// </summary> /// <param name="principal">The ClaimsPrincipal that represents the identity of the requestor.</param> /// <param name="request">The token request parameters that arrived in the call.</param> /// <param name="scope">The scope information about the Relying Party.</param> /// <returns>The ClaimsIdentity representing the collection of claims that will be placed in the issued security token.</returns> protected abstract ClaimsIdentity GetOutputClaimsIdentity(ClaimsPrincipal principal, RequestSecurityToken request, Scope scope); /// <summary> /// Begins async call for GetOutputSubjects routine. Default implementation will throw a NotImplementedExcetion. /// Refer MSDN articles on Using an AsyncCallback Delegate to End an Asynchronous Operation. /// </summary> /// <param name="principal">The authorization context that represents the identity of the requestor.</param> /// <param name="request">The token request parameters that arrived in the call.</param> /// <param name="scope">The scope information about the Relying Party.</param> /// <param name="callback">The callback to be invoked when the user Asynchronous operation completed.</param> /// <param name="state">The state object.</param> /// <returns>IAsyncResult. Represents the status of an asynchronous operation. This will be passed into /// EndGetOutputClaimsIdentity.</returns> protected virtual IAsyncResult BeginGetOutputClaimsIdentity(ClaimsPrincipal principal, RequestSecurityToken request, Scope scope, AsyncCallback callback, object state) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException(SR.GetString(SR.ID2081))); } /// <summary> /// Ends the Async call to BeginGetOutputSubjects. Default implementation will throw a NotImplementedExcetion. /// Refer MSDN articles on Using an AsyncCallback Delegate to End an Asynchronous Operation. /// </summary> /// <param name="result">Typed Async result which contains the result. This was the same IAsyncResult that /// was returned by the BeginGetOutputClaimsIdentity.</param> /// <returns>The claimsets collection that will be placed inside the issued token.</returns> protected virtual ClaimsIdentity EndGetOutputClaimsIdentity(IAsyncResult result) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException(SR.GetString(SR.ID2081))); } /// <summary> /// Issues a Security Token. /// </summary> /// <param name="principal">The identity of the token requestor.</param> /// <param name="request">The request.</param> /// <returns>The response.</returns> public virtual RSTR Issue(ClaimsPrincipal principal, RST request) { if (request == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request"); } _principal = principal; _request = request; // 1. Do request validation ValidateRequest(request); // 2. Get the scope and populate into tokenDescriptor Scope scope = GetScope(principal, request); if (scope == null) { throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID2013)); } this.Scope = scope; // Create the security token descriptor now that we have a scope. this.SecurityTokenDescriptor = CreateSecurityTokenDescriptor(request, scope); if (this.SecurityTokenDescriptor == null) { throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID2003)); } if (this.SecurityTokenDescriptor.SigningCredentials == null) { throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID2079)); } // // If TokenEncryptionRequired is set to true, then we must encrypt the token. // if (this.Scope.TokenEncryptionRequired && this.SecurityTokenDescriptor.EncryptingCredentials == null) { throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4184)); } // 3. Get the token-handler SecurityTokenHandler securityTokenHandler = GetSecurityTokenHandler(request.TokenType); if (securityTokenHandler == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ID4010, request.TokenType))); } // 4. Get the issuer name and populate into tokenDescriptor _tokenDescriptor.TokenIssuerName = GetValidIssuerName(); // 5. Get the token lifetime and populate into tokenDescriptor _tokenDescriptor.Lifetime = GetTokenLifetime(request.Lifetime); // 6. Get the proof token and populate into tokenDescriptor _tokenDescriptor.Proof = GetProofToken(request, scope); // 7. Get the subjects and populate into tokenDescriptor _tokenDescriptor.Subject = GetOutputClaimsIdentity(principal, request, scope); // use the securityTokenHandler from Step 3 to create and setup the issued token information on the tokenDescriptor // (actual issued token, AttachedReference and UnattachedReference) // TokenType is preserved from the request if possible if (!string.IsNullOrEmpty(request.TokenType)) { _tokenDescriptor.TokenType = request.TokenType; } else { string[] identifiers = securityTokenHandler.GetTokenTypeIdentifiers(); if (identifiers == null || identifiers.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4264, request.TokenType))); } _tokenDescriptor.TokenType = identifiers[0]; } _tokenDescriptor.Token = securityTokenHandler.CreateToken(_tokenDescriptor); _tokenDescriptor.AttachedReference = securityTokenHandler.CreateSecurityTokenReference(_tokenDescriptor.Token, true); _tokenDescriptor.UnattachedReference = securityTokenHandler.CreateSecurityTokenReference(_tokenDescriptor.Token, false); // 9. Create the RSTR RSTR rstr = GetResponse(request, _tokenDescriptor); return rstr; } /// <summary> /// Gets an appropriate SecurityTokenHandler for issuing a security token. /// </summary> /// <param name="requestedTokenType">The requested TokenType.</param> /// <returns>The SecurityTokenHandler to be used for creating the issued security token.</returns> protected virtual SecurityTokenHandler GetSecurityTokenHandler(string requestedTokenType) { string tokenType = string.IsNullOrEmpty(requestedTokenType) ? _securityTokenServiceConfiguration.DefaultTokenType : requestedTokenType; SecurityTokenHandler securityTokenHandler = _securityTokenServiceConfiguration.SecurityTokenHandlers[tokenType]; return securityTokenHandler; } /// <summary> /// This routine processes the stored data about the target resource /// for who the Issued token is for. /// </summary> /// <param name="result">The async result.</param> /// <exception cref="ArgumentNullException">When the given async result is null.</exception> void OnGetScopeComplete(IAsyncResult result) { if (null == result) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("result"); } FederatedAsyncState state = result.AsyncState as FederatedAsyncState; if (state == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID2001))); } Exception unhandledException = null; TypedAsyncResult<RSTR> typedResult = state.Result as TypedAsyncResult<RSTR>; if (typedResult == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID2004, typeof(TypedAsyncResult<RSTR>), state.Result.GetType()))); } RST request = state.Request; try { // // 2. Retrieve the scope information // Scope scope = EndGetScope(result); if (scope == null) { throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID2013)); } this.Scope = scope; // // Create a security token descriptor // this.SecurityTokenDescriptor = CreateSecurityTokenDescriptor(request, this.Scope); if (this.SecurityTokenDescriptor == null) { throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID2003)); } if (this.SecurityTokenDescriptor.SigningCredentials == null) { throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID2079)); } // // If TokenEncryptionRequired is set to true, then we must encrypt the token. // if (this.Scope.TokenEncryptionRequired && this.SecurityTokenDescriptor.EncryptingCredentials == null) { throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4184)); } // // Step 3: Retrieve the token handler to use for creating token and store it in the state // SecurityTokenHandler securityTokenHandler = GetSecurityTokenHandler(request == null ? null : request.TokenType); if (securityTokenHandler == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ID4010, request == null ? String.Empty : request.TokenType))); } state.SecurityTokenHandler = securityTokenHandler; // // Step 4: Logical issuer name // _tokenDescriptor.TokenIssuerName = GetValidIssuerName(); // // Step 5: Establish token lifetime // _tokenDescriptor.Lifetime = GetTokenLifetime(request == null ? null : request.Lifetime); // // Step 6: Compute the proof key // _tokenDescriptor.Proof = GetProofToken(request, this.Scope); // // Start the async call for generating the output subjects. // BeginGetOutputClaimsIdentity(state.ClaimsPrincipal, state.Request, scope, OnGetOutputClaimsIdentityComplete, state); } #pragma warning suppress 56500 catch (Exception e) { if (System.Runtime.Fx.IsFatal(e)) throw; unhandledException = e; } if (unhandledException != null) { // // Complete the request in failure // typedResult.Complete(null, result.CompletedSynchronously, unhandledException); } } /// <summary> /// The callback that is invoked on the completion of the BeginGetOutputSubjects call. /// </summary> /// <param name="result">The async result.</param> /// <exception cref="ArgumentNullException">When the given async result is null.</exception> void OnGetOutputClaimsIdentityComplete(IAsyncResult result) { if (null == result) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("result"); } FederatedAsyncState state = result.AsyncState as FederatedAsyncState; if (state == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID2001))); } SecurityTokenHandler securityTokenHandler = state.SecurityTokenHandler; if (securityTokenHandler == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID2016))); } Exception unhandledException = null; RST request = state.Request; RSTR response = null; TypedAsyncResult<RSTR> typedResult = state.Result as TypedAsyncResult<RSTR>; if (typedResult == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID2004, typeof(TypedAsyncResult<RSTR>), state.Result.GetType()))); } try { // // get token descriptor // if (_tokenDescriptor == null) { throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID2003)); } // Step 7: Retrieve the output claims to be included in the issued-token _tokenDescriptor.Subject = EndGetOutputClaimsIdentity(result); // // Use the retrieved securityTokenHandler to create and setup the issued token information on the tokenDescriptor // (actual issued token, AttachedReference and UnattachedReference) // TokenType is preserved from the request if possible if (!string.IsNullOrEmpty(request.TokenType)) { _tokenDescriptor.TokenType = request.TokenType; } else { string[] identifiers = securityTokenHandler.GetTokenTypeIdentifiers(); if (identifiers == null || identifiers.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4264, request.TokenType))); } _tokenDescriptor.TokenType = identifiers[0]; } _tokenDescriptor.Token = securityTokenHandler.CreateToken(_tokenDescriptor); _tokenDescriptor.AttachedReference = securityTokenHandler.CreateSecurityTokenReference(_tokenDescriptor.Token, true); _tokenDescriptor.UnattachedReference = securityTokenHandler.CreateSecurityTokenReference(_tokenDescriptor.Token, false); // 9. Create the RSTR response = GetResponse(request, _tokenDescriptor); } #pragma warning suppress 56500 catch (Exception e) { if (System.Runtime.Fx.IsFatal(e)) throw; unhandledException = e; } typedResult.Complete(response, typedResult.CompletedSynchronously, unhandledException); } /// <summary> /// Gets the Owner configuration instance. /// </summary> public SecurityTokenServiceConfiguration SecurityTokenServiceConfiguration { get { return _securityTokenServiceConfiguration; } } /// <summary> /// Gets or sets the ClaimsPrincipal associated with the current instance. /// </summary> public ClaimsPrincipal Principal { get { return _principal; } set { _principal = value; } } /// <summary> /// Gets or sets the RequestSecurityToken associated with the current instance. /// </summary> public RequestSecurityToken Request { get { return _request; } set { _request = value; } } /// <summary> /// Gets or sets the Scope associated with the current instance. /// </summary> public Scope Scope { get; set; } /// <summary> /// Gets or sets the SecurityTokenDescriptor associated with the current instance. /// </summary> protected SecurityTokenDescriptor SecurityTokenDescriptor { get { return _tokenDescriptor; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } _tokenDescriptor = value; } } /// <summary> /// Renew. /// </summary> /// <param name="principal">The <see cref="ClaimsPrincipal"/> to renew.</param> /// <param name="request">The request.</param> /// <returns>The response.</returns> public virtual RSTR Renew(ClaimsPrincipal principal, RST request) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID3141, (request != null && request.RequestType != null ? request.RequestType : "Renew")))); } /// <summary> /// Validate. /// </summary> /// <param name="principal">The <see cref="ClaimsPrincipal"/> to validate.</param> /// <param name="request">The request.</param> /// <returns>The response.</returns> public virtual RSTR Validate(ClaimsPrincipal principal, RST request) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID3141, (request != null && request.RequestType != null ? request.RequestType : "Validate")))); } /// <summary> /// Validates the RequestSecurityToken encapsulated by this SecurityTokenService instance. /// </summary> protected virtual void ValidateRequest(RST request) { // currently we only support RST/RSTR pattern if (request == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID2051))); } // STS only support Issue for now if (request.RequestType != null && request.RequestType != RequestTypes.Issue) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID2052))); } // key type must be one of the known types if (request.KeyType != null && !IsKnownType(request.KeyType)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID2053))); } // if key type is bearer key, we should fault if the KeySize element is present and its value is not equal to zero. if (StringComparer.Ordinal.Equals(request.KeyType, KeyTypes.Bearer) && request.KeySizeInBits.HasValue && (request.KeySizeInBits.Value != 0)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID2050))); } // token type must be supported for this STS if (GetSecurityTokenHandler(request.TokenType) == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new UnsupportedTokenTypeBadRequestException(request.TokenType)); } request.KeyType = (string.IsNullOrEmpty(request.KeyType)) ? KeyTypes.Symmetric : request.KeyType; if (StringComparer.Ordinal.Equals(request.KeyType, KeyTypes.Symmetric)) { // // Check if the key size is within certain limit to prevent Dos attack // if (request.KeySizeInBits.HasValue) { if (request.KeySizeInBits.Value > _securityTokenServiceConfiguration.DefaultMaxSymmetricKeySizeInBits) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID2056, request.KeySizeInBits.Value, _securityTokenServiceConfiguration.DefaultMaxSymmetricKeySizeInBits))); } } else { request.KeySizeInBits = _securityTokenServiceConfiguration.DefaultSymmetricKeySizeInBits; } } } static bool IsKnownType(string keyType) { return (StringComparer.Ordinal.Equals(keyType, KeyTypes.Symmetric) || StringComparer.Ordinal.Equals(keyType, KeyTypes.Asymmetric) || StringComparer.Ordinal.Equals(keyType, KeyTypes.Bearer)); } } }
/*************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. This code is licensed under the Visual Studio SDK license terms. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ***************************************************************************/ using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; using System.Text; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.Project { internal static class NativeMethods { // IIDS public static readonly Guid IID_IUnknown = new Guid("{00000000-0000-0000-C000-000000000046}"); public const int CLSCTX_INPROC_SERVER = 0x1; public const int S_FALSE = 0x00000001, S_OK = 0x00000000, IDOK = 1, IDCANCEL = 2, IDABORT = 3, IDRETRY = 4, IDIGNORE = 5, IDYES = 6, IDNO = 7, IDCLOSE = 8, IDHELP = 9, IDTRYAGAIN = 10, IDCONTINUE = 11, OLECMDERR_E_NOTSUPPORTED = unchecked((int)0x80040100), OLECMDERR_E_UNKNOWNGROUP = unchecked((int)0x80040104), UNDO_E_CLIENTABORT = unchecked((int)0x80044001), E_OUTOFMEMORY = unchecked((int)0x8007000E), E_INVALIDARG = unchecked((int)0x80070057), E_FAIL = unchecked((int)0x80004005), E_NOINTERFACE = unchecked((int)0x80004002), E_POINTER = unchecked((int)0x80004003), E_NOTIMPL = unchecked((int)0x80004001), E_UNEXPECTED = unchecked((int)0x8000FFFF), E_HANDLE = unchecked((int)0x80070006), E_ABORT = unchecked((int)0x80004004), E_ACCESSDENIED = unchecked((int)0x80070005), E_PENDING = unchecked((int)0x8000000A); public const int OLECLOSE_SAVEIFDIRTY = 0, OLECLOSE_NOSAVE = 1, OLECLOSE_PROMPTSAVE = 2; public const int OLEIVERB_PRIMARY = 0, OLEIVERB_SHOW = -1, OLEIVERB_OPEN = -2, OLEIVERB_HIDE = -3, OLEIVERB_UIACTIVATE = -4, OLEIVERB_INPLACEACTIVATE = -5, OLEIVERB_DISCARDUNDOSTATE = -6, OLEIVERB_PROPERTIES = -7; public const int OFN_READONLY = unchecked((int)0x00000001), OFN_OVERWRITEPROMPT = unchecked((int)0x00000002), OFN_HIDEREADONLY = unchecked((int)0x00000004), OFN_NOCHANGEDIR = unchecked((int)0x00000008), OFN_SHOWHELP = unchecked((int)0x00000010), OFN_ENABLEHOOK = unchecked((int)0x00000020), OFN_ENABLETEMPLATE = unchecked((int)0x00000040), OFN_ENABLETEMPLATEHANDLE = unchecked((int)0x00000080), OFN_NOVALIDATE = unchecked((int)0x00000100), OFN_ALLOWMULTISELECT = unchecked((int)0x00000200), OFN_EXTENSIONDIFFERENT = unchecked((int)0x00000400), OFN_PATHMUSTEXIST = unchecked((int)0x00000800), OFN_FILEMUSTEXIST = unchecked((int)0x00001000), OFN_CREATEPROMPT = unchecked((int)0x00002000), OFN_SHAREAWARE = unchecked((int)0x00004000), OFN_NOREADONLYRETURN = unchecked((int)0x00008000), OFN_NOTESTFILECREATE = unchecked((int)0x00010000), OFN_NONETWORKBUTTON = unchecked((int)0x00020000), OFN_NOLONGNAMES = unchecked((int)0x00040000), OFN_EXPLORER = unchecked((int)0x00080000), OFN_NODEREFERENCELINKS = unchecked((int)0x00100000), OFN_LONGNAMES = unchecked((int)0x00200000), OFN_ENABLEINCLUDENOTIFY = unchecked((int)0x00400000), OFN_ENABLESIZING = unchecked((int)0x00800000), OFN_USESHELLITEM = unchecked((int)0x01000000), OFN_DONTADDTORECENT = unchecked((int)0x02000000), OFN_FORCESHOWHIDDEN = unchecked((int)0x10000000); // for READONLYSTATUS public const int ROSTATUS_NotReadOnly = 0x0, ROSTATUS_ReadOnly = 0x1, ROSTATUS_Unknown = unchecked((int)0xFFFFFFFF); public const int IEI_DoNotLoadDocData = 0x10000000; public const int CB_SETDROPPEDWIDTH = 0x0160, GWL_STYLE = (-16), GWL_EXSTYLE = (-20), DWL_MSGRESULT = 0, SW_SHOWNORMAL = 1, HTMENU = 5, WS_POPUP = unchecked((int)0x80000000), WS_CHILD = 0x40000000, WS_MINIMIZE = 0x20000000, WS_VISIBLE = 0x10000000, WS_DISABLED = 0x08000000, WS_CLIPSIBLINGS = 0x04000000, WS_CLIPCHILDREN = 0x02000000, WS_MAXIMIZE = 0x01000000, WS_CAPTION = 0x00C00000, WS_BORDER = 0x00800000, WS_DLGFRAME = 0x00400000, WS_VSCROLL = 0x00200000, WS_HSCROLL = 0x00100000, WS_SYSMENU = 0x00080000, WS_THICKFRAME = 0x00040000, WS_TABSTOP = 0x00010000, WS_MINIMIZEBOX = 0x00020000, WS_MAXIMIZEBOX = 0x00010000, WS_EX_DLGMODALFRAME = 0x00000001, WS_EX_MDICHILD = 0x00000040, WS_EX_TOOLWINDOW = 0x00000080, WS_EX_CLIENTEDGE = 0x00000200, WS_EX_CONTEXTHELP = 0x00000400, WS_EX_RIGHT = 0x00001000, WS_EX_LEFT = 0x00000000, WS_EX_RTLREADING = 0x00002000, WS_EX_LEFTSCROLLBAR = 0x00004000, WS_EX_CONTROLPARENT = 0x00010000, WS_EX_STATICEDGE = 0x00020000, WS_EX_APPWINDOW = 0x00040000, WS_EX_LAYERED = 0x00080000, WS_EX_TOPMOST = 0x00000008, WS_EX_NOPARENTNOTIFY = 0x00000004, LVM_SETEXTENDEDLISTVIEWSTYLE = (0x1000 + 54), LVS_EX_LABELTIP = 0x00004000, // winuser.h WH_JOURNALPLAYBACK = 1, WH_GETMESSAGE = 3, WH_MOUSE = 7, WSF_VISIBLE = 0x0001, WM_NULL = 0x0000, WM_CREATE = 0x0001, WM_DELETEITEM = 0x002D, WM_DESTROY = 0x0002, WM_MOVE = 0x0003, WM_SIZE = 0x0005, WM_ACTIVATE = 0x0006, WA_INACTIVE = 0, WA_ACTIVE = 1, WA_CLICKACTIVE = 2, WM_SETFOCUS = 0x0007, WM_KILLFOCUS = 0x0008, WM_ENABLE = 0x000A, WM_SETREDRAW = 0x000B, WM_SETTEXT = 0x000C, WM_GETTEXT = 0x000D, WM_GETTEXTLENGTH = 0x000E, WM_PAINT = 0x000F, WM_CLOSE = 0x0010, WM_QUERYENDSESSION = 0x0011, WM_QUIT = 0x0012, WM_QUERYOPEN = 0x0013, WM_ERASEBKGND = 0x0014, WM_SYSCOLORCHANGE = 0x0015, WM_ENDSESSION = 0x0016, WM_SHOWWINDOW = 0x0018, WM_WININICHANGE = 0x001A, WM_SETTINGCHANGE = 0x001A, WM_DEVMODECHANGE = 0x001B, WM_ACTIVATEAPP = 0x001C, WM_FONTCHANGE = 0x001D, WM_TIMECHANGE = 0x001E, WM_CANCELMODE = 0x001F, WM_SETCURSOR = 0x0020, WM_MOUSEACTIVATE = 0x0021, WM_CHILDACTIVATE = 0x0022, WM_QUEUESYNC = 0x0023, WM_GETMINMAXINFO = 0x0024, WM_PAINTICON = 0x0026, WM_ICONERASEBKGND = 0x0027, WM_NEXTDLGCTL = 0x0028, WM_SPOOLERSTATUS = 0x002A, WM_DRAWITEM = 0x002B, WM_MEASUREITEM = 0x002C, WM_VKEYTOITEM = 0x002E, WM_CHARTOITEM = 0x002F, WM_SETFONT = 0x0030, WM_GETFONT = 0x0031, WM_SETHOTKEY = 0x0032, WM_GETHOTKEY = 0x0033, WM_QUERYDRAGICON = 0x0037, WM_COMPAREITEM = 0x0039, WM_GETOBJECT = 0x003D, WM_COMPACTING = 0x0041, WM_COMMNOTIFY = 0x0044, WM_WINDOWPOSCHANGING = 0x0046, WM_WINDOWPOSCHANGED = 0x0047, WM_POWER = 0x0048, WM_COPYDATA = 0x004A, WM_CANCELJOURNAL = 0x004B, WM_NOTIFY = 0x004E, WM_INPUTLANGCHANGEREQUEST = 0x0050, WM_INPUTLANGCHANGE = 0x0051, WM_TCARD = 0x0052, WM_HELP = 0x0053, WM_USERCHANGED = 0x0054, WM_NOTIFYFORMAT = 0x0055, WM_CONTEXTMENU = 0x007B, WM_STYLECHANGING = 0x007C, WM_STYLECHANGED = 0x007D, WM_DISPLAYCHANGE = 0x007E, WM_GETICON = 0x007F, WM_SETICON = 0x0080, WM_NCCREATE = 0x0081, WM_NCDESTROY = 0x0082, WM_NCCALCSIZE = 0x0083, WM_NCHITTEST = 0x0084, WM_NCPAINT = 0x0085, WM_NCACTIVATE = 0x0086, WM_GETDLGCODE = 0x0087, WM_NCMOUSEMOVE = 0x00A0, WM_NCLBUTTONDOWN = 0x00A1, WM_NCLBUTTONUP = 0x00A2, WM_NCLBUTTONDBLCLK = 0x00A3, WM_NCRBUTTONDOWN = 0x00A4, WM_NCRBUTTONUP = 0x00A5, WM_NCRBUTTONDBLCLK = 0x00A6, WM_NCMBUTTONDOWN = 0x00A7, WM_NCMBUTTONUP = 0x00A8, WM_NCMBUTTONDBLCLK = 0x00A9, WM_NCXBUTTONDOWN = 0x00AB, WM_NCXBUTTONUP = 0x00AC, WM_NCXBUTTONDBLCLK = 0x00AD, WM_KEYFIRST = 0x0100, WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101, WM_CHAR = 0x0102, WM_DEADCHAR = 0x0103, WM_CTLCOLOR = 0x0019, WM_SYSKEYDOWN = 0x0104, WM_SYSKEYUP = 0x0105, WM_SYSCHAR = 0x0106, WM_SYSDEADCHAR = 0x0107, WM_KEYLAST = 0x0108, WM_IME_STARTCOMPOSITION = 0x010D, WM_IME_ENDCOMPOSITION = 0x010E, WM_IME_COMPOSITION = 0x010F, WM_IME_KEYLAST = 0x010F, WM_INITDIALOG = 0x0110, WM_COMMAND = 0x0111, WM_SYSCOMMAND = 0x0112, WM_TIMER = 0x0113, WM_HSCROLL = 0x0114, WM_VSCROLL = 0x0115, WM_INITMENU = 0x0116, WM_INITMENUPOPUP = 0x0117, WM_MENUSELECT = 0x011F, WM_MENUCHAR = 0x0120, WM_ENTERIDLE = 0x0121, WM_CHANGEUISTATE = 0x0127, WM_UPDATEUISTATE = 0x0128, WM_QUERYUISTATE = 0x0129, WM_CTLCOLORMSGBOX = 0x0132, WM_CTLCOLOREDIT = 0x0133, WM_CTLCOLORLISTBOX = 0x0134, WM_CTLCOLORBTN = 0x0135, WM_CTLCOLORDLG = 0x0136, WM_CTLCOLORSCROLLBAR = 0x0137, WM_CTLCOLORSTATIC = 0x0138, WM_MOUSEFIRST = 0x0200, WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202, WM_LBUTTONDBLCLK = 0x0203, WM_RBUTTONDOWN = 0x0204, WM_RBUTTONUP = 0x0205, WM_RBUTTONDBLCLK = 0x0206, WM_MBUTTONDOWN = 0x0207, WM_MBUTTONUP = 0x0208, WM_MBUTTONDBLCLK = 0x0209, WM_XBUTTONDOWN = 0x020B, WM_XBUTTONUP = 0x020C, WM_XBUTTONDBLCLK = 0x020D, WM_MOUSEWHEEL = 0x020A, WM_MOUSELAST = 0x020A, WM_PARENTNOTIFY = 0x0210, WM_ENTERMENULOOP = 0x0211, WM_EXITMENULOOP = 0x0212, WM_NEXTMENU = 0x0213, WM_SIZING = 0x0214, WM_CAPTURECHANGED = 0x0215, WM_MOVING = 0x0216, WM_POWERBROADCAST = 0x0218, WM_DEVICECHANGE = 0x0219, WM_IME_SETCONTEXT = 0x0281, WM_IME_NOTIFY = 0x0282, WM_IME_CONTROL = 0x0283, WM_IME_COMPOSITIONFULL = 0x0284, WM_IME_SELECT = 0x0285, WM_IME_CHAR = 0x0286, WM_IME_KEYDOWN = 0x0290, WM_IME_KEYUP = 0x0291, WM_MDICREATE = 0x0220, WM_MDIDESTROY = 0x0221, WM_MDIACTIVATE = 0x0222, WM_MDIRESTORE = 0x0223, WM_MDINEXT = 0x0224, WM_MDIMAXIMIZE = 0x0225, WM_MDITILE = 0x0226, WM_MDICASCADE = 0x0227, WM_MDIICONARRANGE = 0x0228, WM_MDIGETACTIVE = 0x0229, WM_MDISETMENU = 0x0230, WM_ENTERSIZEMOVE = 0x0231, WM_EXITSIZEMOVE = 0x0232, WM_DROPFILES = 0x0233, WM_MDIREFRESHMENU = 0x0234, WM_MOUSEHOVER = 0x02A1, WM_MOUSELEAVE = 0x02A3, WM_CUT = 0x0300, WM_COPY = 0x0301, WM_PASTE = 0x0302, WM_CLEAR = 0x0303, WM_UNDO = 0x0304, WM_RENDERFORMAT = 0x0305, WM_RENDERALLFORMATS = 0x0306, WM_DESTROYCLIPBOARD = 0x0307, WM_DRAWCLIPBOARD = 0x0308, WM_PAINTCLIPBOARD = 0x0309, WM_VSCROLLCLIPBOARD = 0x030A, WM_SIZECLIPBOARD = 0x030B, WM_ASKCBFORMATNAME = 0x030C, WM_CHANGECBCHAIN = 0x030D, WM_HSCROLLCLIPBOARD = 0x030E, WM_QUERYNEWPALETTE = 0x030F, WM_PALETTEISCHANGING = 0x0310, WM_PALETTECHANGED = 0x0311, WM_HOTKEY = 0x0312, WM_PRINT = 0x0317, WM_PRINTCLIENT = 0x0318, WM_HANDHELDFIRST = 0x0358, WM_HANDHELDLAST = 0x035F, WM_AFXFIRST = 0x0360, WM_AFXLAST = 0x037F, WM_PENWINFIRST = 0x0380, WM_PENWINLAST = 0x038F, WM_APP = unchecked((int)0x8000), WM_USER = 0x0400, WM_REFLECT = WM_USER + 0x1C00, WS_OVERLAPPED = 0x00000000, WPF_SETMINPOSITION = 0x0001, WM_CHOOSEFONT_GETLOGFONT = (0x0400 + 1), WHEEL_DELTA = 120, DWLP_MSGRESULT = 0, PSNRET_NOERROR = 0, PSNRET_INVALID = 1, PSNRET_INVALID_NOCHANGEPAGE = 2; public const int PSN_APPLY = ((0 - 200) - 2), PSN_KILLACTIVE = ((0 - 200) - 1), PSN_RESET = ((0 - 200) - 3), PSN_SETACTIVE = ((0 - 200) - 0); public const int GMEM_MOVEABLE = 0x0002, GMEM_ZEROINIT = 0x0040, GMEM_DDESHARE = 0x2000; public const int SWP_NOACTIVATE = 0x0010, SWP_NOZORDER = 0x0004, SWP_NOSIZE = 0x0001, SWP_NOMOVE = 0x0002, SWP_FRAMECHANGED = 0x0020; public const int TVM_SETINSERTMARK = (0x1100 + 26), TVM_GETEDITCONTROL = (0x1100 + 15); public const int FILE_ATTRIBUTE_READONLY = 0x00000001; public const int PSP_DEFAULT = 0x00000000, PSP_DLGINDIRECT = 0x00000001, PSP_USEHICON = 0x00000002, PSP_USEICONID = 0x00000004, PSP_USETITLE = 0x00000008, PSP_RTLREADING = 0x00000010, PSP_HASHELP = 0x00000020, PSP_USEREFPARENT = 0x00000040, PSP_USECALLBACK = 0x00000080, PSP_PREMATURE = 0x00000400, PSP_HIDEHEADER = 0x00000800, PSP_USEHEADERTITLE = 0x00001000, PSP_USEHEADERSUBTITLE = 0x00002000; public const int PSH_DEFAULT = 0x00000000, PSH_PROPTITLE = 0x00000001, PSH_USEHICON = 0x00000002, PSH_USEICONID = 0x00000004, PSH_PROPSHEETPAGE = 0x00000008, PSH_WIZARDHASFINISH = 0x00000010, PSH_WIZARD = 0x00000020, PSH_USEPSTARTPAGE = 0x00000040, PSH_NOAPPLYNOW = 0x00000080, PSH_USECALLBACK = 0x00000100, PSH_HASHELP = 0x00000200, PSH_MODELESS = 0x00000400, PSH_RTLREADING = 0x00000800, PSH_WIZARDCONTEXTHELP = 0x00001000, PSH_WATERMARK = 0x00008000, PSH_USEHBMWATERMARK = 0x00010000, // user pass in a hbmWatermark instead of pszbmWatermark PSH_USEHPLWATERMARK = 0x00020000, // PSH_STRETCHWATERMARK = 0x00040000, // stretchwatermark also applies for the header PSH_HEADER = 0x00080000, PSH_USEHBMHEADER = 0x00100000, PSH_USEPAGELANG = 0x00200000, // use frame dialog template matched to page PSH_WIZARD_LITE = 0x00400000, PSH_NOCONTEXTHELP = 0x02000000; public const int PSBTN_BACK = 0, PSBTN_NEXT = 1, PSBTN_FINISH = 2, PSBTN_OK = 3, PSBTN_APPLYNOW = 4, PSBTN_CANCEL = 5, PSBTN_HELP = 6, PSBTN_MAX = 6; public const int TRANSPARENT = 1, OPAQUE = 2, FW_BOLD = 700; [StructLayout(LayoutKind.Sequential)] public struct NMHDR { public IntPtr hwndFrom; public int idFrom; public int code; } /// <devdoc> /// Helper class for setting the text parameters to OLECMDTEXT structures. /// </devdoc> public static class OLECMDTEXT { /// <summary> /// Flags for the OLE command text /// </summary> public enum OLECMDTEXTF { /// <summary>No flag</summary> OLECMDTEXTF_NONE = 0, /// <summary>The name of the command is required.</summary> OLECMDTEXTF_NAME = 1, /// <summary>A description of the status is required.</summary> OLECMDTEXTF_STATUS = 2 } } /// <devdoc> /// OLECMDF enums for IOleCommandTarget /// </devdoc> public enum tagOLECMDF { OLECMDF_SUPPORTED = 1, OLECMDF_ENABLED = 2, OLECMDF_LATCHED = 4, OLECMDF_NINCHED = 8, OLECMDF_INVISIBLE = 16 } /// <devdoc> /// This method takes a file URL and converts it to an absolute path. The trick here is that /// if there is a '#' in the path, everything after this is treated as a fragment. So /// we need to append the fragment to the end of the path. /// </devdoc> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static string GetAbsolutePath(string fileName) { System.Diagnostics.Debug.Assert(fileName != null && fileName.Length > 0, "Cannot get absolute path, fileName is not valid"); Uri uri = new Uri(fileName); return uri.LocalPath + uri.Fragment; } /// <devdoc> /// Please use this "approved" method to compare file names. /// </devdoc> public static bool IsSamePath(string file1, string file2) { if(file1 == null || file1.Length == 0) { return (file2 == null || file2.Length == 0); } Uri uri1 = null; Uri uri2 = null; try { if(!Uri.TryCreate(file1, UriKind.Absolute, out uri1) || !Uri.TryCreate(file2, UriKind.Absolute, out uri2)) { return false; } if(uri1 != null && uri1.IsFile && uri2 != null && uri2.IsFile) { return 0 == String.Compare(uri1.LocalPath, uri2.LocalPath, StringComparison.OrdinalIgnoreCase); } return file1 == file2; } catch(UriFormatException e) { Trace.WriteLine("Exception " + e.Message); } return false; } [ComImport(), Guid("9BDA66AE-CA28-4e22-AA27-8A7218A0E3FA"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] public interface IEventHandler { // converts the underlying codefunction into an event handler for the given event // if the given event is NULL, then the function will handle no events [PreserveSig] int AddHandler(string bstrEventName); [PreserveSig] int RemoveHandler(string bstrEventName); IVsEnumBSTR GetHandledEvents(); bool HandlesEvent(string bstrEventName); } [ComImport(), Guid("A55CCBCC-7031-432d-B30A-A68DE7BDAD75"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] public interface IParameterKind { void SetParameterPassingMode(PARAMETER_PASSING_MODE ParamPassingMode); void SetParameterArrayDimensions(int uDimensions); int GetParameterArrayCount(); int GetParameterArrayDimensions(int uIndex); int GetParameterPassingMode(); } public enum PARAMETER_PASSING_MODE { cmParameterTypeIn = 1, cmParameterTypeOut = 2, cmParameterTypeInOut = 3 } [ ComImport, ComVisible(true), Guid("3E596484-D2E4-461a-A876-254C4F097EBB"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown) ] public interface IMethodXML { // Generate XML describing the contents of this function's body. void GetXML(ref string pbstrXML); // Parse the incoming XML with respect to the CodeModel XML schema and // use the result to regenerate the body of the function. /// <include file='doc\NativeMethods.uex' path='docs/doc[@for="IMethodXML.SetXML"]/*' /> [PreserveSig] int SetXML(string pszXML); // This is really a textpoint [PreserveSig] int GetBodyPoint([MarshalAs(UnmanagedType.Interface)]out object bodyPoint); } [ComImport(), Guid("EA1A87AD-7BC5-4349-B3BE-CADC301F17A3"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] public interface IVBFileCodeModelEvents { [PreserveSig] int StartEdit(); [PreserveSig] int EndEdit(); } ///-------------------------------------------------------------------------- /// ICodeClassBase: ///-------------------------------------------------------------------------- [GuidAttribute("23BBD58A-7C59-449b-A93C-43E59EFC080C")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport()] public interface ICodeClassBase { [PreserveSig()] int GetBaseName(out string pBaseName); } public const ushort CF_HDROP = 15; // winuser.h public const uint MK_CONTROL = 0x0008; //winuser.h public const uint MK_SHIFT = 0x0004; public const int MAX_PATH = 260; // windef.h /// <summary> /// Specifies options for a bitmap image associated with a task item. /// </summary> public enum VSTASKBITMAP { BMP_COMPILE = -1, BMP_SQUIGGLE = -2, BMP_COMMENT = -3, BMP_SHORTCUT = -4, BMP_USER = -5 }; public const int ILD_NORMAL = 0x0000, ILD_TRANSPARENT = 0x0001, ILD_MASK = 0x0010, ILD_ROP = 0x0040; /// <summary> /// Defines the values that are not supported by the System.Environment.SpecialFolder enumeration /// </summary> [ComVisible(true)] public enum ExtendedSpecialFolder { /// <summary> /// Identical to CSIDL_COMMON_STARTUP /// </summary> CommonStartup = 0x0018, /// <summary> /// Identical to CSIDL_WINDOWS /// </summary> Windows = 0x0024, } // APIS /// <summary> /// Changes the parent window of the specified child window. /// </summary> /// <param name="hWnd">Handle to the child window.</param> /// <param name="hWndParent">Handle to the new parent window. If this parameter is NULL, the desktop window becomes the new parent window.</param> /// <returns>A handle to the previous parent window indicates success. NULL indicates failure.</returns> [DllImport("User32", ExactSpelling = true, CharSet = CharSet.Auto)] public static extern IntPtr SetParent(IntPtr hWnd, IntPtr hWndParent); [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)] public static extern bool DestroyIcon(IntPtr handle); [DllImport("user32.dll", EntryPoint = "IsDialogMessageA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool IsDialogMessageA(IntPtr hDlg, ref MSG msg); /// <summary> /// Indicates whether the file type is binary or not /// </summary> /// <param name="lpApplicationName">Full path to the file to check</param> /// <param name="lpBinaryType">If file isbianry the bitness of the app is indicated by lpBinaryType value.</param> /// <returns>True if the file is binary false otherwise</returns> [DllImport("kernel32.dll")] public static extern bool GetBinaryType([MarshalAs(UnmanagedType.LPWStr)]string lpApplicationName, out uint lpBinaryType); } }
using System; using System.Collections.Generic; using System.IO; using UnityEngine; using XInputDotNetPure; public class vib { public static VIB_TRACK_DEF VIB_TRACK_PTR(VIB_DEF vibPtr, Int32 ndx, BinaryReader reader = null) { if (reader != null) { reader.BaseStream.Seek((Int64)((Int32)vibPtr.trackOffset + ndx), SeekOrigin.Begin); } return vib.Parms.tracks[ndx]; } public static void VIB_TRACK_HEAD(VIB_DEF vibPtr, Int32 ndx, BinaryReader reader = null) { vib.VIB_TRACK_PTR(vibPtr, 0, reader); } public static void LoadVibData(String vibrationFileName) { vib.Parms.vibPtr = null; if (vib.vibList.Contains(vibrationFileName)) { String[] vibInfo; Byte[] binAsset = AssetManager.LoadBytes("CommonAsset/VibrationData/" + vibrationFileName, out vibInfo, true); MemoryStream memoryStream = new MemoryStream(binAsset); BinaryReader binaryReader = new BinaryReader(memoryStream); vib.VIB_init(binaryReader); binaryReader.Close(); memoryStream.Close(); } } public static void VIB_init(BinaryReader reader) { try { VIB_DEF value = default(VIB_DEF); value.magic = (UInt16)reader.ReadInt16(); value.fps = (UInt16)reader.ReadInt16(); value.trackCount = (UInt16)reader.ReadInt16(); value.trackOffset = (UInt16)reader.ReadInt16(); Int32 trackCount = (Int32)value.trackCount; VIB_TRACK_DEF[] array = new VIB_TRACK_DEF[trackCount]; for (Int32 i = 0; i < trackCount; i++) { reader.BaseStream.Seek((Int64)((Int32)value.trackOffset + i * 12), SeekOrigin.Begin); array[i] = default(VIB_TRACK_DEF); array[i].sampleFlags = new UInt16[2]; array[i].sampleCount = new UInt16[2]; array[i].sampleOffset = new UInt16[2]; array[i].sampleFlags[0] = (UInt16)reader.ReadInt16(); array[i].sampleFlags[1] = (UInt16)reader.ReadInt16(); array[i].sampleCount[0] = (UInt16)reader.ReadInt16(); array[i].sampleCount[1] = (UInt16)reader.ReadInt16(); array[i].sampleOffset[0] = (UInt16)reader.ReadInt16(); array[i].sampleOffset[1] = (UInt16)reader.ReadInt16(); } Byte[][][] array2 = new Byte[trackCount][][]; for (Int32 j = 0; j < trackCount; j++) { VIB_TRACK_DEF vib_TRACK_DEF = array[j]; array2[j] = new Byte[2][]; Int32 count = (Int32)vib_TRACK_DEF.sampleCount[(Int32)vib.VIB_SAMPLE_LO]; Int32 num = (Int32)vib_TRACK_DEF.sampleOffset[(Int32)vib.VIB_SAMPLE_LO]; reader.BaseStream.Seek((Int64)num, SeekOrigin.Begin); array2[j][0] = reader.ReadBytes(count); count = (Int32)vib_TRACK_DEF.sampleCount[(Int32)vib.VIB_SAMPLE_HI]; num = (Int32)vib_TRACK_DEF.sampleOffset[(Int32)vib.VIB_SAMPLE_HI]; reader.BaseStream.Seek((Int64)num, SeekOrigin.Begin); array2[j][1] = reader.ReadBytes(count); } vib.Parms.vibPtr = new VIB_DEF?(value); vib.Parms.tracks = array; vib.Parms.frameData = array2; } catch (Exception message) { global::Debug.LogError(message); } finally { reader.Close(); } vib.Parms.statusFlags = (UInt16)vib.VIB_STATUS_INIT; vib.Parms.frameRate = 256; vib.Parms.frameNdx = 0; vib.Parms.frameStart = 0; UInt32 num2 = vib.VIB_computeFrameCount(); vib.Parms.frameStop = (Int16)(num2 - 1u); vib.VIB_initSamples(); } private static void VIB_initSamples() { Int32 trackCount = (Int32)vib.Parms.vibPtr.Value.trackCount; for (Int32 i = 0; i < trackCount; i++) { vib.VIB_setTrackActive(i, 0, false); vib.VIB_setTrackActive(i, 1, false); } vib.VIB_setTrackActive(0, 0, true); vib.VIB_setTrackActive(0, 1, true); } private static UInt32 VIB_computeFrameCount() { UInt32 num = 0u; for (Int32 i = 0; i < (Int32)vib.Parms.vibPtr.Value.trackCount; i++) { VIB_TRACK_DEF vib_TRACK_DEF = vib.Parms.tracks[i]; if ((UInt32)vib_TRACK_DEF.sampleCount[(Int32)vib.VIB_SAMPLE_LO] > num) { num = (UInt32)vib_TRACK_DEF.sampleCount[(Int32)vib.VIB_SAMPLE_LO]; } if ((UInt32)vib_TRACK_DEF.sampleCount[(Int32)vib.VIB_SAMPLE_HI] > num) { num = (UInt32)vib_TRACK_DEF.sampleCount[(Int32)vib.VIB_SAMPLE_HI]; } } return num; } public static void VIB_service() { if ((vib.Parms.statusFlags & (UInt16)vib.VIB_STATUS_INIT) == 0) { return; } if (PersistenSingleton<UIManager>.Instance.IsPause) { return; } VIB_DEF? vibPtr = vib.Parms.vibPtr; if (vibPtr == null) { return; } if ((vib.Parms.statusFlags & (UInt16)vib.VIB_STATUS_ACTIVE) != 0 && (vib.Parms.statusFlags & (UInt16)(vib.VIB_STATUS_LOOP | vib.VIB_STATUS_PLAY_SET)) != 0) { VIB_DEF value = vib.Parms.vibPtr.Value; Int32 num = 0; Int32 num2 = 0; Int32 num3 = vib.Parms.frameNdx >> 8; for (Int32 i = 0; i < (Int32)value.trackCount; i++) { VIB_TRACK_DEF vib_TRACK_DEF = vib.Parms.tracks[i]; if ((vib_TRACK_DEF.sampleFlags[(Int32)vib.VIB_SAMPLE_LO] & (UInt16)vib.VIB_SAMPLE_ACTIVE) != 0 && num3 < (Int32)vib_TRACK_DEF.sampleCount[(Int32)vib.VIB_SAMPLE_LO]) { num += (Int32)vib.Parms.frameData[i][(Int32)vib.VIB_SAMPLE_LO][num3]; } if ((vib_TRACK_DEF.sampleFlags[(Int32)vib.VIB_SAMPLE_HI] & (UInt16)vib.VIB_SAMPLE_ACTIVE) != 0 && num3 < (Int32)vib_TRACK_DEF.sampleCount[(Int32)vib.VIB_SAMPLE_HI]) { num2 += (Int32)vib.Parms.frameData[i][(Int32)vib.VIB_SAMPLE_HI][num3]; } } if (num > 255) { num = 255; } if (num2 > 127) { num2 = 1; } if ((FF9StateSystem.Settings.cfg.vibe == (UInt64)FF9CFG.FF9CFG_VIBE_ON || PersistenSingleton<FF9StateSystem>.Instance.mode == 5) && (num > 0 || num2 > 0)) { vib.VIB_actuatorSet(0, (Single)num2 / 255f, (Single)num / 255f); if (PersistenSingleton<FF9StateSystem>.Instance.mode == 2) { vib.VIB_actuatorSet(1, (Single)num2 / 255f, (Single)num / 255f); } } vib.Parms.frameNdx = vib.Parms.frameNdx + (Int32)vib.Parms.frameRate; if (vib.Parms.frameNdx >> 8 > (Int32)vib.Parms.frameStop) { if ((vib.Parms.statusFlags & (UInt16)vib.VIB_STATUS_WRAP) != 0) { vib.Parms.frameNdx = (Int32)vib.Parms.frameStop << 8; vib.VIB_setFrameRate((Int16)(-vib.Parms.frameRate)); } else { vib.Parms.frameNdx = (Int32)vib.Parms.frameStart << 8; } vib.Parms.statusFlags = (UInt16)(vib.Parms.statusFlags & (UInt16)(~(UInt16)vib.VIB_STATUS_PLAY_SET)); if ((vib.Parms.statusFlags & (UInt16)vib.VIB_STATUS_LOOP) == 0) { vib.VIB_actuatorReset(0); vib.VIB_actuatorReset(1); vib.Parms.statusFlags = (UInt16)(vib.Parms.statusFlags & (UInt16)(~(UInt16)vib.VIB_STATUS_ACTIVE)); } } if (vib.Parms.frameNdx >> 8 < (Int32)vib.Parms.frameStart) { if ((vib.Parms.statusFlags & (UInt16)vib.VIB_STATUS_WRAP) != 0) { vib.Parms.frameNdx = (Int32)vib.Parms.frameStart << 8; vib.VIB_setFrameRate((Int16)(-vib.Parms.frameRate)); } else { vib.Parms.frameNdx = (Int32)vib.Parms.frameStop << 8; } vib.Parms.statusFlags = (UInt16)(vib.Parms.statusFlags & (UInt16)(~(UInt16)vib.VIB_STATUS_PLAY_SET)); if ((vib.Parms.statusFlags & (UInt16)vib.VIB_STATUS_LOOP) == 0) { vib.VIB_actuatorReset(0); vib.VIB_actuatorReset(1); vib.Parms.statusFlags = (UInt16)(vib.Parms.statusFlags & (UInt16)(~(UInt16)vib.VIB_STATUS_ACTIVE)); } } } } public static void VIB_purge() { vib.VIB_actuatorReset(0); vib.VIB_actuatorReset(1); vib.Parms.statusFlags = (UInt16)vib.VIB_STATUS_NONE; vib.Parms.frameStart = 0; vib.Parms.frameStop = 0; vib.Parms.vibPtr = null; } public static void VIB_vibrate(Int16 frameNdx) { vib.Parms.statusFlags = (UInt16)(vib.Parms.statusFlags | (UInt16)(vib.VIB_STATUS_ACTIVE | vib.VIB_STATUS_PLAY_SET)); vib.Parms.frameStart = frameNdx; vib.Parms.frameNdx = (Int32)((Int16)(frameNdx << 8)); } public static void VIB_setActive(Boolean isActive) { if (isActive) { vib.Parms.statusFlags = (UInt16)(vib.Parms.statusFlags | (UInt16)(vib.VIB_STATUS_ACTIVE | vib.VIB_STATUS_PLAY_SET)); if (vib.Parms.frameNdx >> 8 < (Int32)vib.Parms.frameStart || vib.Parms.frameNdx >> 8 > (Int32)vib.Parms.frameStop) { vib.Parms.frameNdx = (Int32)vib.Parms.frameStart << 8; } } else { vib.VIB_actuatorReset(0); vib.VIB_actuatorReset(1); vib.Parms.statusFlags = (UInt16)(vib.Parms.statusFlags & (UInt16)(~(UInt16)(vib.VIB_STATUS_ACTIVE | vib.VIB_STATUS_PLAY_SET))); } } public static void VIB_setTrackActive(Int32 trackNdx, Int32 sampleNdx, Boolean isActive) { VIB_TRACK_DEF vib_TRACK_DEF; for (Int32 i = 0; i < (Int32)vib.Parms.vibPtr.Value.trackCount; i++) { vib_TRACK_DEF = vib.Parms.tracks[i]; UInt16[] sampleFlags = vib_TRACK_DEF.sampleFlags; sampleFlags[sampleNdx] = (UInt16)(sampleFlags[sampleNdx] & (UInt16)(~(UInt16)vib.VIB_SAMPLE_ACTIVE)); } vib_TRACK_DEF = vib.VIB_TRACK_PTR(vib.Parms.vibPtr.Value, trackNdx, (BinaryReader)null); if (isActive) { UInt16[] sampleFlags2 = vib_TRACK_DEF.sampleFlags; sampleFlags2[sampleNdx] = (UInt16)(sampleFlags2[sampleNdx] | (UInt16)vib.VIB_SAMPLE_ACTIVE); vib.VIB_actuatorReset(0); vib.VIB_actuatorReset(1); vib.Parms.statusFlags = (UInt16)(vib.Parms.statusFlags & (UInt16)(~(UInt16)(vib.VIB_STATUS_ACTIVE | vib.VIB_STATUS_PLAY_SET))); vib.Parms.frameNdx = (Int32)vib.Parms.frameStart << 8; } else { UInt16[] sampleFlags3 = vib_TRACK_DEF.sampleFlags; sampleFlags3[sampleNdx] = (UInt16)(sampleFlags3[sampleNdx] & (UInt16)(~(UInt16)vib.VIB_SAMPLE_ACTIVE)); } } public static void VIB_setTrackToModulate(UInt32 trackNdx, UInt32 sampleNdx, Boolean isActive) { VIB_TRACK_DEF vib_TRACK_DEF = vib.VIB_TRACK_PTR(vib.Parms.vibPtr.Value, (Int32)trackNdx, (BinaryReader)null); if (isActive) { UInt16[] sampleFlags = vib_TRACK_DEF.sampleFlags; UIntPtr uintPtr = (UIntPtr)sampleNdx; sampleFlags[(Int32)uintPtr] = (UInt16)(sampleFlags[(Int32)uintPtr] | (UInt16)vib.VIB_SAMPLE_ACTIVE); } else { UInt16[] sampleFlags2 = vib_TRACK_DEF.sampleFlags; UIntPtr uintPtr2 = (UIntPtr)sampleNdx; sampleFlags2[(Int32)uintPtr2] = (UInt16)(sampleFlags2[(Int32)uintPtr2] & (UInt16)(~(UInt16)vib.VIB_SAMPLE_ACTIVE)); } } public static void VIB_setFrameRate(Int16 frameRate) { vib.Parms.frameRate = frameRate; } public static void VIB_setFlags(Int16 flags) { vib.Parms.statusFlags = (UInt16)(vib.Parms.statusFlags & (UInt16)(~(UInt16)(vib.VIB_STATUS_LOOP | vib.VIB_STATUS_WRAP))); vib.Parms.statusFlags = (UInt16)(vib.Parms.statusFlags | (UInt16)(flags & (Int16)(vib.VIB_STATUS_LOOP | vib.VIB_STATUS_WRAP))); } public static void VIB_setPlayRange(Int16 frameStart, Int16 frameStop) { if (frameStart >= 0) { vib.Parms.frameStart = frameStart; } if (frameStop >= 0) { vib.Parms.frameStop = frameStop; } } public static UInt32 VIB_getStatusFlags() { return (UInt32)vib.Parms.statusFlags; } public static Boolean VIB_getTrackActive(Int32 trackNdx, Int32 sampleNdx) { return (vib.VIB_TRACK_PTR(vib.Parms.vibPtr.Value, trackNdx, (BinaryReader)null).sampleFlags[sampleNdx] & (UInt16)vib.VIB_SAMPLE_ACTIVE) != 0; } public static VIB_DEF VIB_getVIBPtr() { return vib.Parms.vibPtr.Value; } public static void VIB_getPlayRange(ref UInt32 frameStart, ref UInt32 frameStop) { frameStart = (UInt32)vib.Parms.frameStart; frameStop = (UInt32)vib.Parms.frameStop; } public static Int16 VIB_getFrameRate() { return vib.Parms.frameRate; } public static UInt32 VIB_getFrame() { return (UInt32)(vib.Parms.frameNdx >> 8); } public static void VIB_actuatorReset(Int32 index) { vib.VIB_actuatorSet(index, 0f, 0f); } public static void VIB_actuatorSet(Int32 index, Single left, Single right) { vib.CurrentVibrateLeft = left; vib.CurrentVibrateRight = right; if (global::GamePad.GetState((PlayerIndex)index).IsConnected) { global::GamePad.SetVibration((PlayerIndex)index, left, right); } } public static Byte VIB_STATUS_NONE = 0; public static Byte VIB_STATUS_INIT = 1; public static Byte VIB_STATUS_ACTIVE = 2; public static Byte VIB_STATUS_PLAY_SET = 4; public static Byte VIB_STATUS_LOOP = 8; public static Byte VIB_STATUS_WRAP = 16; public static Byte VIB_SAMPLE_LO = 0; public static Byte VIB_SAMPLE_HI = 1; public static Byte VIB_SAMPLE_ACTIVE = 1; public static Single CurrentVibrateLeft = 0f; public static Single CurrentVibrateRight = 0f; private static VIB_PARMS_DEF Parms; private static readonly List<String> vibList = new List<String> { "EVT_ALEX1_AC_H2F", "EVT_ALEX1_AT_ROOF", "EVT_ALEX1_AT_SENTOU", "EVT_ALEX1_AT_STREET_A", "EVT_ALEX1_TS_CARGO_0", "EVT_ALEX1_TS_COCKPIT", "EVT_ALEX1_TS_ENGIN", "EVT_ALEX1_TS_ORCHE", "EVT_ALEX2_AC_PRISON_A", "EVT_ALEX2_AC_QUEEN", "EVT_ALEX2_AC_R_HALL", "EVT_ALEX2_AC_S_ROOM", "EVT_ALEX3_AC_ENT_2F", "EVT_ALEX3_AT_PUB", "EVT_ALEX4_AC_HILDA2_A", "EVT_ALEX4_AC_SAI_E", "EVT_ALEX4_AC_SAI_F", "EVT_ALEX4_AC_SAI_G", "EVT_BAL_BB_FGT_0", "EVT_BAL_BB_SQR_0", "EVT_BURMECIA_HOUSE_1", "EVT_BURMECIA_PATIO_1", "EVT_CARGO_CA_COP_1", "EVT_CARGO_CA_DCK_0", "EVT_CARGO_CA_DCK_W", "EVT_CARGO_FN_DCK_0", "EVT_CLEYRA2_CATHE_2", "EVT_DALI_A_AP_AIR_0", "EVT_DALI_F_UF_BLK_1", "EVT_DOWNSHIP_BT_CCR_0", "EVT_EFOREST1_EF_DEP_0", "EVT_EVA1_IF_ENT_0", "EVT_EVA1_IF_MKJ_1", "EVT_EVA2_IU_SDV_0", "EVT_EVA2_IU_SDV_1", "EVT_FOSSIL_FR_DN3_0", "EVT_FOSSIL_FR_ENT_0", "EVT_FOSSIL_FR_TRP_0", "EVT_GARGAN_GR_GGT_0", "EVT_GARGAN_GR_GGT_1", "EVT_GATE_S_SG_ALX_4", "EVT_GATE_S_SG_TRN_0", "EVT_GATE_S_SG_TRN_2", "EVT_GIZ_BELL_1", "EVT_ICE_DL_VIW_0", "EVT_ICE_IC_STA_0", "EVT_INV_RR_BRG_1", "EVT_IPSEN_IP_ST1_0", "EVT_LIND1_CS_LB_CTM_0", "EVT_LIND1_CS_LB_EXB_0", "EVT_LIND1_CS_LB_LFT_0", "EVT_LIND1_CS_LB_LLP_0", "EVT_LIND1_CS_LB_MET_0", "EVT_LIND1_CS_LB_PLA_0", "EVT_LIND1_TN_LB_CAG_0", "EVT_LIND1_TN_LB_FTM_0", "EVT_LIND1_TN_LB_MTM_0", "EVT_LIND1_TN_LB_STN_0", "EVT_LIND2_CS_LB_CTM_0", "EVT_LIND2_CS_LB_EXB_0", "EVT_LIND2_CS_LB_LLP_0", "EVT_LIND2_CS_LB_PLA_0", "EVT_LIND2_TN_LB_MTM_0", "EVT_LIND2_TN_LB_STN_0", "EVT_LIND3_CS_LB_CTM_0", "EVT_LIND3_CS_LB_EXB_0", "EVT_LIND3_CS_LB_LLP_0", "EVT_LIND3_CS_LB_PLA_0", "EVT_LIND3_TN_LB_MTM_0", "EVT_LIND3_TN_LB_STN_0", "EVT_OEIL_UV_FDP_0", "EVT_PANDEMO_PD_AOS_0", "EVT_PANDEMO_PD_BWR_0", "EVT_PANDEMO_PD_RTB_0", "EVT_PANDEMO_PD_RTB_1", "EVT_PATA_M_CM_MP0_0", "EVT_PATA_M_CM_MP5_0", "EVT_SARI1_MS_MRR_2", "EVT_SARI1_MS_PMR_0", "EVT_SHRINE_ES_TRP_0", "EVT_SUNA_SP_KDR_0", "EVT_SUNA_SP_RFG_0", "EVT_SUNA_SP_RRO_0", "EVT_TRENO1_TR_KHM_0", "EVT_TRENO2_TR_KHM_0", "EVT_TRENO2_TR_KHM_1", "EVT_TRENO2_TR_KHM_2" }; }
// 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.Runtime; using System.Runtime.Diagnostics; using System.ServiceModel.Diagnostics; using System.ServiceModel.Security; using System.Threading; using System.Threading.Tasks; namespace System.ServiceModel.Channels { public abstract class TransportDuplexSessionChannel : TransportOutputChannel, IDuplexSessionChannel, IAsyncDuplexSessionChannel { private bool _isInputSessionClosed; private bool _isOutputSessionClosed; private Uri _localVia; private static Action<object> s_onWriteComplete = new Action<object>(OnWriteComplete); protected TransportDuplexSessionChannel( ChannelManagerBase manager, ITransportFactorySettings settings, EndpointAddress localAddress, Uri localVia, EndpointAddress remoteAddress, Uri via) : base(manager, remoteAddress, via, settings.ManualAddressing, settings.MessageVersion) { LocalAddress = localAddress; _localVia = localVia; BufferManager = settings.BufferManager; SendLock = new SemaphoreSlim(1); MessageEncoder = settings.MessageEncoderFactory.CreateSessionEncoder(); Session = new ConnectionDuplexSession(this); } public EndpointAddress LocalAddress { get; } public SecurityMessageProperty RemoteSecurity { get; protected set; } public IDuplexSession Session { get; protected set; } protected SemaphoreSlim SendLock { get; } protected BufferManager BufferManager { get; } protected MessageEncoder MessageEncoder { get; set; } internal SynchronizedMessageSource MessageSource { get; private set; } protected abstract bool IsStreamedOutput { get; } IAsyncDuplexSession ISessionChannel<IAsyncDuplexSession>.Session => Session as IAsyncDuplexSession; public Message Receive() { return Receive(DefaultReceiveTimeout); } public Message Receive(TimeSpan timeout) { Message message = null; if (DoneReceivingInCurrentState()) { return null; } bool shouldFault = true; try { message = MessageSource.Receive(timeout); OnReceiveMessage(message); shouldFault = false; return message; } finally { if (shouldFault) { if (message != null) { message.Close(); message = null; } Fault(); } } } public Task<Message> ReceiveAsync() { return ReceiveAsync(DefaultReceiveTimeout); } public async Task<Message> ReceiveAsync(TimeSpan timeout) { Message message = null; if (DoneReceivingInCurrentState()) { return null; } bool shouldFault = true; try { message = await MessageSource.ReceiveAsync(timeout); OnReceiveMessage(message); shouldFault = false; return message; } finally { if (shouldFault) { if (message != null) { message.Close(); } Fault(); } } } public IAsyncResult BeginReceive(AsyncCallback callback, object state) { return BeginReceive(DefaultReceiveTimeout, callback, state); } public IAsyncResult BeginReceive(TimeSpan timeout, AsyncCallback callback, object state) { return ReceiveAsync(timeout).ToApm(callback, state); } public Message EndReceive(IAsyncResult result) { return result.ToApmEnd<Message>(); } public IAsyncResult BeginTryReceive(TimeSpan timeout, AsyncCallback callback, object state) { return ReceiveAsync(timeout).ToApm(callback, state); } public bool EndTryReceive(IAsyncResult result, out Message message) { try { message = result.ToApmEnd<Message>(); return true; } catch (TimeoutException e) { if (WcfEventSource.Instance.ReceiveTimeoutIsEnabled()) { WcfEventSource.Instance.ReceiveTimeout(e.Message); } message = null; return false; } } public async Task<(bool, Message)> TryReceiveAsync(TimeSpan timeout) { try { return (true, await ReceiveAsync(timeout)); } catch(TimeoutException e) { if (WcfEventSource.Instance.ReceiveTimeoutIsEnabled()) { WcfEventSource.Instance.ReceiveTimeout(e.Message); } return (false, null); } } public bool TryReceive(TimeSpan timeout, out Message message) { try { message = Receive(timeout); return true; } catch (TimeoutException e) { if (WcfEventSource.Instance.ReceiveTimeoutIsEnabled()) { WcfEventSource.Instance.ReceiveTimeout(e.Message); } message = null; return false; } } public async Task<bool> WaitForMessageAsync(TimeSpan timeout) { if (DoneReceivingInCurrentState()) { return true; } bool shouldFault = true; try { bool success = await MessageSource.WaitForMessageAsync(timeout); shouldFault = !success; // need to fault if we've timed out because we're now toast return success; } finally { if (shouldFault) { Fault(); } } } public bool WaitForMessage(TimeSpan timeout) { if (DoneReceivingInCurrentState()) { return true; } bool shouldFault = true; try { bool success = MessageSource.WaitForMessage(timeout); shouldFault = !success; // need to fault if we've timed out because we're now toast return success; } finally { if (shouldFault) { Fault(); } } } public IAsyncResult BeginWaitForMessage(TimeSpan timeout, AsyncCallback callback, object state) { return WaitForMessageAsync(timeout).ToApm(callback, state); } public bool EndWaitForMessage(IAsyncResult result) { return result.ToApmEnd<bool>(); } protected void SetMessageSource(IMessageSource messageSource) { MessageSource = new SynchronizedMessageSource(messageSource); } protected abstract Task CloseOutputSessionCoreAsync(TimeSpan timeout); protected abstract void CloseOutputSessionCore(TimeSpan timeout); protected async Task CloseOutputSessionAsync(TimeSpan timeout) { ThrowIfNotOpened(); ThrowIfFaulted(); TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); // If timeout == TimeSpan.MaxValue, then we want to pass Timeout.Infinite as // SemaphoreSlim doesn't accept timeouts > Int32.MaxValue. // Using TimeoutHelper.RemainingTime() would yield a value less than TimeSpan.MaxValue // and would result in the value Int32.MaxValue so we must use the original timeout specified. if (!await SendLock.WaitAsync(TimeoutHelper.ToMilliseconds(timeout))) { if (WcfEventSource.Instance.CloseTimeoutIsEnabled()) { WcfEventSource.Instance.CloseTimeout(SR.Format(SR.CloseTimedOut, timeout)); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException( SR.Format(SR.CloseTimedOut, timeout), TimeoutHelper.CreateEnterTimedOutException(timeout))); } try { // check again in case the previous send faulted while we were waiting for the lock ThrowIfFaulted(); // we're synchronized by sendLock here if (_isOutputSessionClosed) { return; } _isOutputSessionClosed = true; bool shouldFault = true; try { await CloseOutputSessionCoreAsync(timeout); OnOutputSessionClosed(ref timeoutHelper); shouldFault = false; } finally { if (shouldFault) { Fault(); } } } finally { SendLock.Release(); } } protected void CloseOutputSession(TimeSpan timeout) { ThrowIfNotOpened(); ThrowIfFaulted(); TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); // If timeout == TimeSpan.MaxValue, then we want to pass Timeout.Infinite as // SemaphoreSlim doesn't accept timeouts > Int32.MaxValue. // Using TimeoutHelper.RemainingTime() would yield a value less than TimeSpan.MaxValue // and would result in the value Int32.MaxValue so we must use the original timeout specified. if (!SendLock.Wait(TimeoutHelper.ToMilliseconds(timeout))) { if (WcfEventSource.Instance.CloseTimeoutIsEnabled()) { WcfEventSource.Instance.CloseTimeout(SR.Format(SR.CloseTimedOut, timeout)); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException( SR.Format(SR.CloseTimedOut, timeout), TimeoutHelper.CreateEnterTimedOutException(timeout))); } try { // check again in case the previous send faulted while we were waiting for the lock ThrowIfFaulted(); // we're synchronized by sendLock here if (_isOutputSessionClosed) { return; } _isOutputSessionClosed = true; bool shouldFault = true; try { CloseOutputSessionCore(timeout); OnOutputSessionClosed(ref timeoutHelper); shouldFault = false; } finally { if (shouldFault) { Fault(); } } } finally { SendLock.Release(); } } // used to return cached connection to the pool/reader pool protected abstract void ReturnConnectionIfNecessary(bool abort, TimeSpan timeout); protected override void OnAbort() { ReturnConnectionIfNecessary(true, TimeSpan.Zero); } protected override void OnFaulted() { base.OnFaulted(); ReturnConnectionIfNecessary(true, TimeSpan.Zero); } protected internal override async Task OnCloseAsync(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); await CloseOutputSessionAsync(timeoutHelper.RemainingTime()); // close input session if necessary if (!_isInputSessionClosed) { await EnsureInputClosedAsync(timeoutHelper.RemainingTime()); OnInputSessionClosed(); } CompleteClose(timeoutHelper.RemainingTime()); } protected override void OnClose(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); CloseOutputSession(timeoutHelper.RemainingTime()); // close input session if necessary if (!_isInputSessionClosed) { EnsureInputClosed(timeoutHelper.RemainingTime()); OnInputSessionClosed(); } CompleteClose(timeoutHelper.RemainingTime()); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return OnCloseAsync(timeout).ToApm(callback, state); } protected override void OnEndClose(IAsyncResult result) { result.ToApmEnd(); } protected override void OnClosed() { base.OnClosed(); // clean up the CBT after transitioning to the closed state //ChannelBindingUtility.Dispose(ref this.channelBindingToken); } protected virtual void OnReceiveMessage(Message message) { if (message == null) { OnInputSessionClosed(); } else { PrepareMessage(message); } } protected void ApplyChannelBinding(Message message) { //ChannelBindingUtility.TryAddToMessage(this.channelBindingToken, message, false); } protected virtual void PrepareMessage(Message message) { message.Properties.Via = _localVia; ApplyChannelBinding(message); if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled) { EventTraceActivity eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message); Guid relatedActivityId = EventTraceActivity.GetActivityIdFromThread(); if (eventTraceActivity == null) { eventTraceActivity = EventTraceActivity.GetFromThreadOrCreate(); EventTraceActivityHelper.TryAttachActivity(message, eventTraceActivity); } if (WcfEventSource.Instance.MessageReceivedByTransportIsEnabled()) { WcfEventSource.Instance.MessageReceivedByTransport( eventTraceActivity, LocalAddress != null && LocalAddress.Uri != null ? LocalAddress.Uri.AbsoluteUri : string.Empty, relatedActivityId); } } } protected abstract AsyncCompletionResult StartWritingBufferedMessage(Message message, ArraySegment<byte> messageData, bool allowOutputBatching, TimeSpan timeout, Action<object> callback, object state); protected abstract AsyncCompletionResult BeginCloseOutput(TimeSpan timeout, Action<object> callback, object state); protected virtual void FinishWritingMessage() { } protected abstract ArraySegment<byte> EncodeMessage(Message message); protected abstract void OnSendCore(Message message, TimeSpan timeout); protected abstract AsyncCompletionResult StartWritingStreamedMessage(Message message, TimeSpan timeout, Action<object> callback, object state); protected override async Task OnSendAsync(Message message, TimeSpan timeout) { ThrowIfDisposedOrNotOpen(); TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); // If timeout == TimeSpan.MaxValue, then we want to pass Timeout.Infinite as // SemaphoreSlim doesn't accept timeouts > Int32.MaxValue. // Using TimeoutHelper.RemainingTime() would yield a value less than TimeSpan.MaxValue // and would result in the value Int32.MaxValue so we must use the original timeout specified. if (!await SendLock.WaitAsync(TimeoutHelper.ToMilliseconds(timeout))) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException( SR.Format(SR.SendToViaTimedOut, Via, timeout), TimeoutHelper.CreateEnterTimedOutException(timeout))); } byte[] buffer = null; try { // check again in case the previous send faulted while we were waiting for the lock ThrowIfDisposedOrNotOpen(); ThrowIfOutputSessionClosed(); bool success = false; try { ApplyChannelBinding(message); var tcs = new TaskCompletionSource<bool>(this); AsyncCompletionResult completionResult; if (IsStreamedOutput) { completionResult = StartWritingStreamedMessage(message, timeoutHelper.RemainingTime(), s_onWriteComplete, tcs); } else { bool allowOutputBatching; ArraySegment<byte> messageData; allowOutputBatching = message.Properties.AllowOutputBatching; messageData = EncodeMessage(message); buffer = messageData.Array; completionResult = StartWritingBufferedMessage( message, messageData, allowOutputBatching, timeoutHelper.RemainingTime(), s_onWriteComplete, tcs); } if (completionResult == AsyncCompletionResult.Completed) { tcs.TrySetResult(true); } await tcs.Task; FinishWritingMessage(); success = true; if (WcfEventSource.Instance.MessageSentByTransportIsEnabled()) { EventTraceActivity eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message); WcfEventSource.Instance.MessageSentByTransport(eventTraceActivity, RemoteAddress.Uri.AbsoluteUri); } } finally { if (!success) { Fault(); } } } finally { SendLock.Release(); } if (buffer != null) { BufferManager.ReturnBuffer(buffer); } } private static void OnWriteComplete(object state) { if (state == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(state)); } var tcs = state as TaskCompletionSource<bool>; if (tcs == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("state", SR.SPS_InvalidAsyncResult); } tcs.TrySetResult(true); } protected override void OnSend(Message message, TimeSpan timeout) { ThrowIfDisposedOrNotOpen(); TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); // If timeout == TimeSpan.MaxValue, then we want to pass Timeout.Infinite as // SemaphoreSlim doesn't accept timeouts > Int32.MaxValue. // Using TimeoutHelper.RemainingTime() would yield a value less than TimeSpan.MaxValue // and would result in the value Int32.MaxValue so we must use the original timeout specified. if (!SendLock.Wait(TimeoutHelper.ToMilliseconds(timeout))) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException( SR.Format(SR.SendToViaTimedOut, Via, timeout), TimeoutHelper.CreateEnterTimedOutException(timeout))); } try { // check again in case the previous send faulted while we were waiting for the lock ThrowIfDisposedOrNotOpen(); ThrowIfOutputSessionClosed(); bool success = false; try { ApplyChannelBinding(message); OnSendCore(message, timeoutHelper.RemainingTime()); success = true; if (WcfEventSource.Instance.MessageSentByTransportIsEnabled()) { EventTraceActivity eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message); WcfEventSource.Instance.MessageSentByTransport(eventTraceActivity, RemoteAddress.Uri.AbsoluteUri); } } finally { if (!success) { Fault(); } } } finally { SendLock.Release(); } } // cleanup after the framing handshake has completed protected abstract void CompleteClose(TimeSpan timeout); // must be called under sendLock private void ThrowIfOutputSessionClosed() { if (_isOutputSessionClosed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SendCannotBeCalledAfterCloseOutputSession)); } } private async Task EnsureInputClosedAsync(TimeSpan timeout) { Message message = await MessageSource.ReceiveAsync(timeout); if (message != null) { using (message) { ProtocolException error = ProtocolException.ReceiveShutdownReturnedNonNull(message); throw TraceUtility.ThrowHelperError(error, message); } } } private void EnsureInputClosed(TimeSpan timeout) { Message message = MessageSource.Receive(timeout); if (message != null) { using (message) { ProtocolException error = ProtocolException.ReceiveShutdownReturnedNonNull(message); throw TraceUtility.ThrowHelperError(error, message); } } } private void OnInputSessionClosed() { lock (ThisLock) { if (_isInputSessionClosed) { return; } _isInputSessionClosed = true; } } private void OnOutputSessionClosed(ref TimeoutHelper timeoutHelper) { bool releaseConnection = false; lock (ThisLock) { if (_isInputSessionClosed) { // we're all done, release the connection releaseConnection = true; } } if (releaseConnection) { ReturnConnectionIfNecessary(false, timeoutHelper.RemainingTime()); } } public class ConnectionDuplexSession : IDuplexSession, IAsyncDuplexSession { private static UriGenerator s_uriGenerator; private string _id; public ConnectionDuplexSession(TransportDuplexSessionChannel channel) : base() { Channel = channel; } public string Id { get { if (_id == null) { lock (Channel) { if (_id == null) { _id = UriGenerator.Next(); } } } return _id; } } public TransportDuplexSessionChannel Channel { get; } private static UriGenerator UriGenerator { get { if (s_uriGenerator == null) { s_uriGenerator = new UriGenerator(); } return s_uriGenerator; } } public IAsyncResult BeginCloseOutputSession(AsyncCallback callback, object state) { return BeginCloseOutputSession(Channel.DefaultCloseTimeout, callback, state); } public IAsyncResult BeginCloseOutputSession(TimeSpan timeout, AsyncCallback callback, object state) { return Channel.CloseOutputSessionAsync(timeout).ToApm(callback, state); } public void EndCloseOutputSession(IAsyncResult result) { result.ToApmEnd(); } public void CloseOutputSession() { CloseOutputSession(Channel.DefaultCloseTimeout); } public void CloseOutputSession(TimeSpan timeout) { Channel.CloseOutputSession(timeout); } public Task CloseOutputSessionAsync() { return CloseOutputSessionAsync(Channel.DefaultCloseTimeout); } public Task CloseOutputSessionAsync(TimeSpan timeout) { return Channel.CloseOutputSessionAsync(timeout); } } } }
using System; using System.Collections.ObjectModel; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Content; using FlatRedBall.Math; using FlatRedBall.Graphics; using System.Diagnostics; using FlatRedBall.Math.Geometry; namespace FlatRedBall { public partial class Camera { #region Fields public Vector3 UpVector = new Vector3(0, 1, 0); static int sCreatedCount = 0; float mFarClipPlane; float mNearClipPlane; Matrix mView; Matrix mViewRelative; Matrix mProjection; Matrix mViewProjection; float mMinimumX; float mMinimumY; float mMaximumX; float mMaximumY; float mBaseZ; float mBaseMinimumX; float mBaseMinimumY; float mBaseMaximumX; float mBaseMaximumY; #if SUPPORTS_POST_PROCESSING ShadowMap mShadow = null; internal PostProcessingEffectCollection mPostProcessing; #region XML Docs /// <summary> /// Defines the rendering order for this camera /// </summary> #endregion public List<RenderMode> RenderOrder; #region XML Docs /// <summary> /// List of rendered textures (during render pass) /// </summary> #endregion internal Dictionary<int, RenderTargetTexture> mRenderTargetTextures; #region XML Docs /// <summary> /// The final render for this camera (after post-processing) /// </summary> #endregion internal RenderTargetTexture mRenderTargetTexture; #region XML Docs /// <summary> /// Whether or not this camera should be drawn to the screen /// </summary> #endregion public bool DrawToScreen = true; bool mClearsTargetDefaultRenderMode = true; #endif BoundingFrustum mBoundingFrustum; CameraCullMode mCameraCullMode; CameraModelCullMode mCameraModelCullMode; #region Viewport settings //internal int mTargetWidth; //internal int mTargetHeight; public Color BackgroundColor = #if FRB_MDX Color.FromArgb(0, 0, 0, 0); #else //Color.Black; new Color(0,0,0,0); #endif SplitScreenViewport splitScreenViewport; bool mUsesSplitScreenViewport = false; #endregion List<Layer> mLayers = new List<Layer>(); ReadOnlyCollection<Layer> mLayersReadOnly; internal SpriteList mSpritesToBillBoard = new SpriteList(); string mContentManager; #region XML Docs /// <summary> /// Whether or not lighting is enabled for this camera /// </summary> #endregion internal bool mLightingEnabled = false; #endregion #region Properties /// <summary> /// Sets whether the Camera will prevent viewports from being larger than the resolution. This value defaults to true. /// </summary> /// <remarks> /// The purpose of this value is to prevent cameras from attempting to draw outside of the window's client bounds. A camera /// which has a viewport larger than the window client bounds will throw an exception. However, cameras (and layers) which render /// to a render target which is larger than the current window should be able to render to the full render target even if it is larger /// than the current window. Therefore, this value should be set to false if rendering to large render targets. /// </remarks> public bool ShouldRestrictViewportToResolution { get; set; } public Matrix View { get { return mView; }// GetLookAtMatrix(false); } } public Matrix Projection { get { return mProjection; }// GetProjectionMatrix(); } } #if FRB_XNA public BoundingFrustum BoundingFrustum { get { return mBoundingFrustum; } } #endif public CameraCullMode CameraCullMode { get { return mCameraCullMode; } set { mCameraCullMode = value; } } public CameraModelCullMode CameraModelCullMode { get { return mCameraModelCullMode; } set { mCameraModelCullMode = value; } } /// <summary> /// The Y field of view of the camera in radians. Field of view represents the /// Y angle from the bottom of the screen to the top. /// </summary> /// <remarks> /// This modifies the xEdge and yEdge properties. Default value is (float)Math.PI / 4.0f; /// </remarks> public virtual float FieldOfView { get { return mFieldOfView; } set { #if DEBUG if (value >= (float)System.Math.PI) { throw new ArgumentException("FieldOfView must be smaller than PI."); } if (value <= 0) { throw new ArgumentException("FieldOfView must be greater than 0."); } #endif mFieldOfView = value; mYEdge = (float)(100 * System.Math.Tan(mFieldOfView / 2.0)); mXEdge = mYEdge * mAspectRatio; #if !SILVERLIGHT UpdateViewProjectionMatrix(); #endif } } #region XML Docs /// <summary> /// A Camera-specific layer. Objects on this layer will not appear /// in any other cameras. /// </summary> /// <remarks> /// This instance is automatically created when the Camera is instantiated. /// </remarks> #endregion public Layer Layer { get { return mLayers[0]; } } public ReadOnlyCollection<Layer> Layers { get { return mLayersReadOnly; } } public float MinimumX { get { return mMinimumX; } set { mMinimumX = value; } } public float MinimumY { get { return mMinimumY; } set { mMinimumY = value; } } public float MaximumX { get { return mMaximumX; } set { mMaximumX = value; } } public float MaximumY { get { return mMaximumY; } set { mMaximumY = value; } } public float NearClipPlane { get { return mNearClipPlane; } set { mNearClipPlane = value; } } public float FarClipPlane { get { return mFarClipPlane; } set { mFarClipPlane = value; } } public float XEdge { get { return mXEdge; } } public float YEdge { get { return mYEdge; } } public float TopDestinationVelocity { get { return mTopDestinationVelocity; } set { mTopDestinationVelocity = value; } } public float BottomDestinationVelocity { get { return mBottomDestinationVelocity; } set { mBottomDestinationVelocity = value; } } public float LeftDestinationVelocity { get { return mLeftDestinationVelocity; } set { mLeftDestinationVelocity = value; } } public float RightDestinationVelocity { get { return mRightDestinationVelocity; } set { mRightDestinationVelocity = value; } } #endregion public bool ShiftsHalfUnitForRendering { get { // This causes all kinds of jitteryness when attached to an object, so we should make sure // the camera is not attached to anything: return Parent == null && mOrthogonal && (this.mOrthogonalWidth / (float)this.DestinationRectangle.Width == 1); } } //public float RenderingShiftAmount //{ // get; // set; //} #region Methods #region Constructor public Camera () : this(null) { } public Camera(string contentManagerName) : this( contentManagerName, FlatRedBallServices.ClientWidth, FlatRedBallServices.ClientHeight) { SetSplitScreenViewport(SplitScreenViewport.FullScreen); ShouldRestrictViewportToResolution = true; } public Camera(string contentManagerName, int width, int height) : base() { ShouldRestrictViewportToResolution = true; ClearsDepthBuffer = true; #if !FRB_MDX mContentManager = contentManagerName; #endif DrawsToScreen = true; ClearMinimumsAndMaximums(); // set the borders to float.NaN so they are not applied. ClearBorders(); mNearClipPlane = 1; mFarClipPlane = 1000; mOrthogonal = false; mOrthogonalWidth = width; mOrthogonalHeight = height; mAspectRatio = width / (float)height; #if FRB_XNA // Be sure to instantiate the frustum before setting the FieldOfView // since setting the FieldOfView sets the frustum: mBoundingFrustum = new BoundingFrustum(Matrix.Identity); #endif // use the Property rather than base value so that the mXEdge and mYEdge are set FieldOfView = (float)System.Math.PI / 4.0f; // Set up the default viewport DestinationRectangle = new Rectangle( 0, 0, width, height); mCameraCullMode = CameraCullMode.UnrotatedDownZ; Layer layer = new Layer(); layer.mCameraBelongingTo = this; layer.Name = "Camera Layer"; mLayers.Add(layer); mLayersReadOnly = new ReadOnlyCollection<Layer>(mLayers); Position.Z = -MathFunctions.ForwardVector3.Z * 40; #if SUPPORTS_POST_PROCESSING mPostProcessing = new PostProcessingEffectCollection(); if (Renderer.UseRenderTargets) { mPostProcessing.InitializeEffects(); } // Create the render order collection RenderOrder = new List<RenderMode>(); RenderOrder.Add(RenderMode.Default); RefreshTexture(); #endif } #endregion #region Public Methods public Layer AddLayer() { Layer layer = new Layer(); mLayers.Add(layer); layer.mCameraBelongingTo = this; return layer; } #region XML Docs /// <summary> /// Adds a layer to the Camera. This method does not remove layers that already /// exist in the SpriteManager. /// </summary> /// <param name="layerToAdd">The layer to add.</param> #endregion public void AddLayer(Layer layerToAdd) { if (layerToAdd.mCameraBelongingTo != null) { throw new System.InvalidOperationException("The argument layer already belongs to a Camera."); } else { // The layer doesn't belong to a camera so it can be added here. mLayers.Add(layerToAdd); layerToAdd.mCameraBelongingTo = this; } } public void MoveToBack(Layer layer) { mLayers.Remove(layer); mLayers.Insert(0, layer); } public void MoveToFront(Layer layer) { // Last layers appear on top (front) mLayers.Remove(layer); mLayers.Add(layer); } #region XmlDocs /// <summary> /// Supplied sprites are billboarded using the camera's RotationMatrix. /// Only the main Camera can billboard sprites. /// </summary> #endregion public void AddSpriteToBillboard(Sprite sprite) { // This only works on the main camera. Multi-camera games must implement their // own solutions: #if DEBUG if(this != Camera.Main) { throw new InvalidOperationException("Sprites can only be billboarded on the main camera"); } #endif this.mSpritesToBillBoard.Add(sprite); } /// <summary> /// Supplied Sprites are billboarded using the camera's RotationMatrix. /// Only the main Camera can billboard sprites. /// </summary> public void AddSpriteToBillboard(IEnumerable<Sprite> sprites) { // This only works on the main camera. Multi-camera games must implement their // own solutions: #if DEBUG if (this != Camera.Main) { throw new InvalidOperationException("Sprites can only be billboarded on the main camera"); } #endif this.mSpritesToBillBoard.AddRange(sprites); } #region XML Docs /// <summary> /// Removes all visibility borders. /// <seealso cref="FlatRedBall.Camera.SetBordersAtZ"/> /// </summary> #endregion public void ClearBorders() { mBaseZ = float.NaN; mBaseMinimumX = float.NaN; mBaseMinimumY = float.NaN; mBaseMaximumX = float.NaN; mBaseMaximumY = float.NaN; } public void ClearMinimumsAndMaximums() { mMinimumX = float.NegativeInfinity; mMinimumY = float.NegativeInfinity; mMaximumX = float.PositiveInfinity; mMaximumY = float.PositiveInfinity; } public void FixDestinationRectangleHeightConstant() { mDestinationRectangle.Width = (int)(mAspectRatio * mDestinationRectangle.Height); } public void FixDestinationRectangleWidthConstant() { mDestinationRectangle.Height = (int)(mDestinationRectangle.Width / mAspectRatio); } public override void ForceUpdateDependencies() { base.ForceUpdateDependencies(); // This will be done both in TimedUpdate as well as here X = System.Math.Min(X, mMaximumX); X = System.Math.Max(X, mMinimumX); Y = System.Math.Min(Y, mMaximumY); Y = System.Math.Max(Y, mMinimumY); if (!double.IsNaN(this.mBaseMaximumX)) { CalculateMaxAndMins(); } // This should happen AFTER mins and maxes are set UpdateViewProjectionMatrix(true); } public Matrix GetLookAtMatrix() { return GetLookAtMatrix(false); } public Matrix GetLookAtMatrix(bool relativeToCamera) { Vector3 positionVector; if (relativeToCamera) { positionVector = new Vector3(0, 0, 0); return Matrix.CreateLookAt(Vector3.Zero, -Vector3.UnitZ, Vector3.UnitY); } else { positionVector = Position; Vector3 cameraTarget = positionVector + mRotationMatrix.Forward; // FRB has historically had a lot of // jagged edges and rendering issues which // I think are caused by floating point inaccuracies. // Unfortunately these tend to happen most when objects // are positioned at whole numbers, which is very common. // Going to shift the camera by .5 units if the Camera is viewing // in 2D mode to try to reduce this if (ShiftsHalfUnitForRendering) { // This doesn't seem to fix // problems when the camera can // smooth scroll. I'm going to move // the camera to multiples of 5. //positionVector.X += .5f; //positionVector.Y -= .5f; //cameraTarget.X += .5f; //cameraTarget.Y -= .5f; // This also causes rendering issues, I think I'm going to do it in update dependencies //positionVector.X = (int)positionVector.X + .5f; //positionVector.Y = (int)positionVector.Y - .5f; //cameraTarget.X = (int)cameraTarget.X + .5f; //cameraTarget.Y = (int)cameraTarget.Y - .5f; // Math this is complicated. Without this // stuff that is attached to the Camera tends // to not be rendered properly :( So putting it back in positionVector.X += .5f; positionVector.Y -= .5f; cameraTarget.X += .5f; cameraTarget.Y -= .5f; } Matrix returnMatrix; Matrix.CreateLookAt( ref positionVector, // Position of the camera eye ref cameraTarget, // Point that the eye is looking at ref UpVector, out returnMatrix); return returnMatrix; } } public Matrix GetProjectionMatrix() { if (mOrthogonal == false) { //return Matrix.CreatePerspectiveFieldOfView( // mFieldOfView * 1.066667f, // mAspectRatio, // mNearClipPlane, // mFarClipPlane); return Matrix.CreatePerspectiveFieldOfView( mFieldOfView, mAspectRatio, mNearClipPlane, mFarClipPlane); } else { return Matrix.CreateOrthographic( mOrthogonalWidth, mOrthogonalHeight, mNearClipPlane, mFarClipPlane); } } public float GetRequiredAspectRatio(float desiredYEdge, float zValue) { float modifiedDesiredYEdge = 100 * desiredYEdge / (Position.Z - zValue); return (float)System.Math.Atan(modifiedDesiredYEdge / 100) * 2; } public Viewport GetViewport() { // Viewport is a struct, so we can start with the current viewport Viewport viewport = Renderer.GraphicsDevice.Viewport; viewport.X = DestinationRectangle.X; viewport.Y = DestinationRectangle.Y; viewport.Width = DestinationRectangle.Width; viewport.Height = DestinationRectangle.Height; if (ShouldRestrictViewportToResolution) { RestrictViewportToResolution(ref viewport); } return viewport; } public static void RestrictViewportToResolution(ref Viewport viewport) { // Renders can happen before the graphics device is reset // If so, we want to make sure we aren't rendering outside of the bounds: int maxWidthAllowed = Renderer.GraphicsDevice.PresentationParameters.BackBufferWidth - viewport.X; int maxHeightAllowed = Renderer.GraphicsDevice.PresentationParameters.BackBufferHeight - viewport.Y; viewport.Width = System.Math.Min(viewport.Width, maxWidthAllowed); viewport.Height = System.Math.Min(viewport.Height, maxHeightAllowed); } public Viewport GetViewport(LayerCameraSettings lcs) { Viewport viewport = Renderer.GraphicsDevice.Viewport; if (lcs == null || lcs.TopDestination < 0 || lcs.BottomDestination < 0 || lcs.LeftDestination < 0 || lcs.RightDestination < 0) { // Viewport is a struct, so we can start with the current viewport viewport.X = DestinationRectangle.X; viewport.Y = DestinationRectangle.Y; viewport.Width = DestinationRectangle.Width; viewport.Height = DestinationRectangle.Height; } else { viewport.X = (int)lcs.LeftDestination; viewport.Y = (int)lcs.TopDestination; viewport.Width = (int)(lcs.RightDestination - lcs.LeftDestination); viewport.Height = (int)(lcs.BottomDestination - lcs.TopDestination); } // Debug should *NEVER* be more tolerant of bad settings: //#if DEBUG if (ShouldRestrictViewportToResolution) { // September 24, 2012 // There is currently a // bug if the user starts // on a Screen with a 2D layer // in portrait mode. The game tells // Windows 8 that it wants to be in portrait // mode. When it does so, the game flips, but // it takes a second. FRB may still render during // that time and this code gets called. The resolutions // don't match up and we have issues. Not sure how to fix // this (yet). // Update August 25, 2013 // This code can throw an exception when resizing a window. // But the user didn't do anything wrong - the engine just hasn't // gotten a chance to reset the device yet. So we'll tolerate it: if (viewport.Y + viewport.Height > FlatRedBallServices.GraphicsOptions.ResolutionHeight) { //throw new Exception("The pixel height resolution of the display is " + // FlatRedBallServices.GraphicsOptions.ResolutionHeight + // " but the LayerCameraSettings' BottomDestination is " + (viewport.Y + viewport.Height)); int amountToSubtract = (viewport.Y + viewport.Height) - FlatRedBallServices.GraphicsOptions.ResolutionHeight; viewport.Height -= amountToSubtract; } if (viewport.X + viewport.Width > FlatRedBallServices.GraphicsOptions.ResolutionWidth) { //throw new Exception("The pixel width resolution of the display is " + // FlatRedBallServices.GraphicsOptions.ResolutionWidth + // " but the LayerCameraSettings' RightDestination is " + (viewport.X + viewport.Width)); int amountToSubtract = (viewport.X + viewport.Width) - FlatRedBallServices.GraphicsOptions.ResolutionWidth; viewport.Width -= amountToSubtract; } //#endif } return viewport; } #region Is object in view #endregion #region XML Docs /// <summary> /// Moves a Sprite so that it remains fully in the camera's view. /// </summary> /// <remarks> /// This method does not consider Sprite rotation, negative scale, or situations /// when the camera is not looking down the Z axis. /// </remarks> /// <param name="sprite">The Sprite to keep in view.</param> #endregion public void KeepSpriteInScreen(Sprite sprite) { // If the Sprite has a parent, then we need to force update so that its // position is what it will be when it's drawn. Be sure to do this before // storing off the oldPosition if (sprite.Parent != null) { sprite.ForceUpdateDependencies(); } Vector3 oldPosition = sprite.Position; float edgeCoef = (Z - sprite.Z) / 100.0f; if (sprite.X - sprite.ScaleX < X - edgeCoef * XEdge) sprite.X = X - edgeCoef * XEdge + sprite.ScaleX; if (sprite.X + sprite.ScaleX > X + edgeCoef * XEdge) sprite.X = X + edgeCoef * XEdge - sprite.ScaleX; if (sprite.Y - sprite.ScaleY < Y - edgeCoef * YEdge) sprite.Y = Y - edgeCoef * YEdge + sprite.ScaleY; if (sprite.Y + sprite.ScaleY > Y + edgeCoef * YEdge) sprite.Y = Y + edgeCoef * YEdge - sprite.ScaleY; if (sprite.Parent != null) { Vector3 shiftAmount = sprite.Position - oldPosition; sprite.TopParent.Position += shiftAmount; } } public override void Pause(FlatRedBall.Instructions.InstructionList instructions) { FlatRedBall.Instructions.Pause.CameraUnpauseInstruction instruction = new FlatRedBall.Instructions.Pause.CameraUnpauseInstruction(this); instruction.Stop(this); instructions.Add(instruction); // TODO: Need to pause the lights, but currently we don't know what type the lights are } #region XML Docs /// <summary> /// Positiones the argument positionable randomly in camera between the argument bounds. /// </summary> /// <remarks> /// Assumes the camera is viewing down the Z plane - it is unrotated. /// </remarks> /// <param name="positionable">The object to reposition.</param> /// <param name="minimumDistanceFromCamera">The closest possible distance from the camera.</param> /// <param name="maximumDistanceFromCamera">The furthest possible distance from the camera.</param> #endregion public void PositionRandomlyInView(IPositionable positionable, float minimumDistanceFromCamera, float maximumDistanceFromCamera) { // First get the distance from the camera. float distanceFromCamera = minimumDistanceFromCamera + (float)(FlatRedBallServices.Random.NextDouble() * (maximumDistanceFromCamera - minimumDistanceFromCamera)); positionable.Z = Z + (distanceFromCamera * FlatRedBall.Math.MathFunctions.ForwardVector3.Z); positionable.X = X - RelativeXEdgeAt(positionable.Z) + (float)( FlatRedBallServices.Random.NextDouble() * 2.0f * RelativeXEdgeAt(positionable.Z) ); positionable.Y = Y - RelativeYEdgeAt(positionable.Z) + (float)(FlatRedBallServices.Random.NextDouble() * 2.0f * RelativeYEdgeAt(positionable.Z)); } public void RefreshTexture() { #if SUPPORTS_POST_PROCESSING if (mRenderTargetTexture != null && mRenderTargetTexture.IsDisposed == false) { throw new InvalidOperationException("The old RenderTargetTexture must first be disposed"); } // Create the render textures collection mRenderTargetTextures = new Dictionary<int, RenderTargetTexture>(); mRenderTargetTexture = new RenderTargetTexture( SurfaceFormat.Color, DestinationRectangle.Width, DestinationRectangle.Height, true); FlatRedBallServices.AddDisposable("Render Target Texture" + sCreatedCount, mRenderTargetTexture, mContentManager); sCreatedCount++; #endif } public void SetRelativeYEdgeAt(float zDistance, float verticalDistance) { FieldOfView = (float)(2 * System.Math.Atan((double)((.5 * verticalDistance) / zDistance))); } public void ScaleDestinationRectangle(float scaleAmount) { float newWidth = DestinationRectangle.Width * scaleAmount; float newHeight = DestinationRectangle.Height * scaleAmount; float destinationCenterX = DestinationRectangle.Left + DestinationRectangle.Width / 2.0f; float destinationCenterY = DestinationRectangle.Top + DestinationRectangle.Height / 2.0f; DestinationRectangle = new Rectangle( (int)(destinationCenterX - newWidth / 2.0f), (int)(destinationCenterY - newHeight / 2.0f), (int)(newWidth), (int)(newHeight)); } #region XML Docs /// <summary> /// Removes the argument Layer from this Camera. Does not empty the layer or /// remove contained objects from their respective managers. /// </summary> /// <param name="layerToRemove">The layer to remove</param> #endregion public void RemoveLayer(Layer layerToRemove) { mLayers.Remove(layerToRemove); layerToRemove.mCameraBelongingTo = null; } #region XML Docs /// <summary> /// Sets the visible borders when the camera is looking down the Z axis. /// </summary> /// <remarks> /// This sets visibility ranges for the camera. That is, if the camera's maximumX is set to 100 at a zToSetAt of /// 0, the camera will never be able to see the point x = 101, z = 0. The camera imposes these limitations /// by calculating the actual minimum and maximum values according to the variables passed. Also, /// the camera keeps track of these visible limits and readjusts the mimimum and maximum values /// when the camera moves in the z direction. Therefore, it is only necessary to set these /// values once, and the camera will remeber that these are the visibility borders, regardless of /// its position. It is important to note that the visiblity borders can be violated if they are too /// close together - if a camera moves so far back that its viewable area at the set Z is greater than /// the set minimumX and maximumX range, the camera will show an area outside of this range. /// <seealso cref="FlatRedBall.Camera.ClearBorders"/> /// </remarks> /// <param name="minimumX">The minimum x value of the visiblity border.</param> /// <param name="minimumY">The minimum y value of the visiblity border.</param> /// <param name="maximumX">The maximum x value of the visiblity border.</param> /// <param name="maximumY">The maximum y value of the visiblity border.</param> /// <param name="zToSetAt">The z value of the plane to use for the visibility border.</param> #endregion public void SetBordersAtZ(float minimumX, float minimumY, float maximumX, float maximumY, float zToSetAt) { mBaseZ = zToSetAt; mBaseMinimumX = minimumX; mBaseMinimumY = minimumY; mBaseMaximumX = maximumX; mBaseMaximumY = maximumY; CalculateMaxAndMins(); X = System.Math.Min(X, mMaximumX); X = System.Math.Max(X, mMinimumX); Y = System.Math.Min(Y, mMaximumY); Y = System.Math.Max(Y, mMinimumY); } public void SetBordersAt(AxisAlignedRectangle visibleBounds) { SetBordersAtZ(visibleBounds.Left, visibleBounds.Bottom, visibleBounds.Right, visibleBounds.Top, visibleBounds.Z); } #region XML Docs /// <summary> /// Copies all fields from the argument to the camera instance. /// </summary> /// <remarks> /// This method will not copy the name, InstructionArray, or children PositionedObjects /// (objects attached to the cameraToSetTo). /// </remarks> /// <param name="cameraToSetTo">The camera to clone.</param> #endregion public void SetCameraTo(Camera cameraToSetTo) { this.mAspectRatio = cameraToSetTo.mAspectRatio; this.mBaseMaximumX = cameraToSetTo.mBaseMaximumX; this.mBaseMaximumY = cameraToSetTo.mBaseMaximumY; this.mBaseMinimumX = cameraToSetTo.mBaseMinimumX; this.mBaseMinimumY = cameraToSetTo.mBaseMinimumY; this.mBaseZ = cameraToSetTo.mBaseZ; // cannot set children, because any PO can only be attached to one other PO this.CameraCullMode = cameraToSetTo.CameraCullMode; this.mParent = cameraToSetTo.Parent; this.mDestinationRectangle = cameraToSetTo.mDestinationRectangle; this.mFieldOfView = cameraToSetTo.mFieldOfView; // not setting InstructionArray. May want to do this later this.MaximumX = cameraToSetTo.MaximumX; this.MaximumY = cameraToSetTo.MaximumY; this.MinimumX = cameraToSetTo.MinimumX; this.MinimumY = cameraToSetTo.MinimumY; // does not set name this.mOrthogonal = cameraToSetTo.mOrthogonal; this.mOrthogonalWidth = cameraToSetTo.mOrthogonalWidth; this.mOrthogonalHeight = cameraToSetTo.mOrthogonalHeight; this.RelativeX = cameraToSetTo.RelativeX; this.RelativeAcceleration = cameraToSetTo.RelativeAcceleration; this.RelativeXVelocity = cameraToSetTo.RelativeXVelocity; this.RelativeY = cameraToSetTo.RelativeY; this.RelativeYVelocity = cameraToSetTo.RelativeYVelocity; this.RelativeZ = cameraToSetTo.RelativeZ; this.RelativeZVelocity = cameraToSetTo.RelativeZVelocity; this.X = cameraToSetTo.X; this.XAcceleration = cameraToSetTo.XAcceleration; this.mXEdge = cameraToSetTo.mXEdge; this.XVelocity = cameraToSetTo.XVelocity; this.Y = cameraToSetTo.Y; this.YAcceleration = cameraToSetTo.YAcceleration; this.mYEdge = cameraToSetTo.mYEdge; this.YVelocity = cameraToSetTo.YVelocity; this.Z = cameraToSetTo.Z; this.ZAcceleration = cameraToSetTo.ZAcceleration; this.ZVelocity = cameraToSetTo.ZVelocity; this.mNearClipPlane = cameraToSetTo.mNearClipPlane; this.mFarClipPlane = cameraToSetTo.mFarClipPlane; } //#if FRB_XNA // public void LookAt(Vector3 forward, Vector3 right) // { // Matrix newRotationMatrix = Matrix.Identity; // newRotationMatrix.Forward = Vector3.Normalize(forward); // newRotationMatrix.Up = Vector3.Normalize(Vector3.Cross(right, forward)); // newRotationMatrix.Right = Vector3.Normalize(right); // RotationMatrix = newRotationMatrix; // } //#endif public void SetLookAtRotationMatrix(Vector3 LookAtPoint) { SetLookAtRotationMatrix(LookAtPoint, new Vector3(0, 1, 0)); } public void SetLookAtRotationMatrix(Vector3 LookAtPoint, Vector3 upDirection) { Matrix newMatrix = Matrix.Invert( Matrix.CreateLookAt( Position, LookAtPoint, upDirection)); // Kill the translation newMatrix.M41 = 0; newMatrix.M42 = 0; newMatrix.M43 = 0; // leave M44 to 1 RotationMatrix = newMatrix; } public void SetDeviceViewAndProjection(BasicEffect effect, bool relativeToCamera) { #if !SILVERLIGHT // Set up our view matrix. A view matrix can be defined given an eye point, // a point to lookat, and a direction for which way is up. effect.View = GetLookAtMatrix(relativeToCamera); effect.Projection = GetProjectionMatrix(); #endif } public void SetDeviceViewAndProjection(GenericEffect effect, bool relativeToCamera) { // Set up our view matrix. A view matrix can be defined given an eye point, // a point to lookat, and a direction for which way is up. effect.View = GetLookAtMatrix(relativeToCamera); effect.Projection = GetProjectionMatrix(); } public void SetDeviceViewAndProjection(Effect effect, bool relativeToCamera) { //TimeManager.SumTimeSection("Start of SetDeviceViewAndProjection"); #region Create the matrices // Get view, projection, and viewproj values Matrix view = (relativeToCamera)? mViewRelative : mView; Matrix viewProj; Matrix.Multiply(ref view, ref mProjection, out viewProj); #endregion if (effect is AlphaTestEffect) { AlphaTestEffect asAlphaTestEffect = effect as AlphaTestEffect; asAlphaTestEffect.View = view; asAlphaTestEffect.Projection = mProjection; } else { //TimeManager.SumTimeSection("Create the matrices"); //EffectParameterBlock block = new EffectParameterBlock(effect); #region Get all valid parameters EffectParameter paramNameViewProj = effect.Parameters["ViewProj"]; EffectParameter paramNameView = effect.Parameters["View"]; EffectParameter paramNameProjection = effect.Parameters["Projection"]; //EffectParameter paramSemViewProj = effect.Parameters.GetParameterBySemantic("VIEWPROJ"); //EffectParameter paramSemView = effect.Parameters.GetParameterBySemantic("VIEW"); //EffectParameter paramSemProjection = effect.Parameters.GetParameterBySemantic("PROJECTION"); #endregion //TimeManager.SumTimeSection("Get all valid parameters"); #region Set all available parameters //if (paramNameProjection != null || paramNameView != null || // paramNameViewProj != null || paramSemProjection != null || // paramSemView != null || paramSemViewProj != null) //{ //block.Begin(); if (paramNameView != null) paramNameView.SetValue(view); //if (paramSemView != null) paramSemView.SetValue(view); if (paramNameProjection != null) paramNameProjection.SetValue(mProjection); //if (paramSemProjection != null) paramSemProjection.SetValue(mProjection); if (paramNameViewProj != null) paramNameViewProj.SetValue(viewProj); //if (paramSemViewProj != null) paramSemViewProj.SetValue(viewProj); //block.End(); //block.Apply(); //} #endregion //TimeManager.SumTimeSection("Set available parameters"); } } public override void TimedActivity(float secondDifference, double secondDifferenceSquaredDividedByTwo, float secondsPassedLastFrame) { base.TimedActivity(secondDifference, secondDifferenceSquaredDividedByTwo, secondsPassedLastFrame); // This will be done both in UpdateDependencies as well as here X = System.Math.Min(X, mMaximumX); X = System.Math.Max(X, mMinimumX); Y = System.Math.Min(Y, mMaximumY); Y = System.Math.Max(Y, mMinimumY); if (!double.IsNaN(this.mBaseMaximumX)) { CalculateMaxAndMins(); } #region update the destination rectangle (for viewport) if (mTopDestinationVelocity != 0f || mBottomDestinationVelocity != 0f || mLeftDestinationVelocity != 0f || mRightDestinationVelocity != 0f) { mTopDestination += mTopDestinationVelocity * TimeManager.SecondDifference; mBottomDestination += mBottomDestinationVelocity * TimeManager.SecondDifference; mLeftDestination += mLeftDestinationVelocity * TimeManager.SecondDifference; mRightDestination += mRightDestinationVelocity * TimeManager.SecondDifference; UpdateDestinationRectangle(); FixAspectRatioYConstant(); } #endregion } public override void UpdateDependencies(double currentTime) { base.UpdateDependencies(currentTime); // This will be done both in TimedUpdate as well as here X = System.Math.Min(X, mMaximumX); X = System.Math.Max(X, mMinimumX); Y = System.Math.Min(Y, mMaximumY); Y = System.Math.Max(Y, mMinimumY); if (!double.IsNaN(this.mBaseMaximumX)) { CalculateMaxAndMins(); } // I'm not sure if this is the proper fix but on WP7 it prevents // tile maps from rendering improperly when scrolling. if (ShiftsHalfUnitForRendering && this.Parent != null) { Position.X = (int)Position.X + .25f; Position.Y = (int)Position.Y - .25f; } // This should happen AFTER mins and maxes are set UpdateViewProjectionMatrix(true); } public void UpdateViewProjectionMatrix() { UpdateViewProjectionMatrix(false); } public void UpdateViewProjectionMatrix(bool updateFrustum) { mView = GetLookAtMatrix(false); mViewRelative = GetLookAtMatrix(true); //NOTE: Certain objects need to be rendered "Pixel Perfect" on screen. // However, DX9 (and by extension XNA) has an "issue" moving from texel space to pixel space. // http://msdn.microsoft.com/en-us/library/bb219690(v=vs.85).aspx // if an object needs to be pixel perfect, it needs to have it's projection matrix shifted by -.5 x and -.5 y //EXAMPLE: // mProjection = Matrix.CreateTranslation(-0.5f, -0.5f, 0) * GetProjectionMatrix(); mProjection = GetProjectionMatrix(); if (updateFrustum) { Matrix.Multiply(ref mView, ref mProjection, out mViewProjection); mBoundingFrustum.Matrix = (mViewProjection); } } public void UsePixelCoordinates() { UsePixelCoordinates(false, mDestinationRectangle.Width, mDestinationRectangle.Height); } [Obsolete("Use parameterless method")] public void UsePixelCoordinates(bool moveCornerToOrigin) { UsePixelCoordinates(moveCornerToOrigin, mDestinationRectangle.Width, mDestinationRectangle.Height); } #region XML Docs /// <summary> /// Sets the viewport for this camera to a standard split-screen viewport /// </summary> /// <param name="viewport">The viewport to use for this camera</param> #endregion public void SetSplitScreenViewport(SplitScreenViewport viewport) { mUsesSplitScreenViewport = true; splitScreenViewport = viewport; // Set the left mLeftDestination = //FlatRedBallServices.GraphicsDevice.Viewport.X + (( (( viewport != SplitScreenViewport.RightHalf && viewport != SplitScreenViewport.TopRight && viewport != SplitScreenViewport.BottomRight) ? 0 : FlatRedBallServices.ClientWidth / 2); // Set the top mTopDestination = //FlatRedBallServices.GraphicsDevice.Viewport.Y + (( (( viewport != SplitScreenViewport.BottomHalf && viewport != SplitScreenViewport.BottomLeft && viewport != SplitScreenViewport.BottomRight) ? 0 : FlatRedBallServices.ClientHeight / 2); // Set the right (left + width) mRightDestination = mLeftDestination + (( viewport != SplitScreenViewport.FullScreen && viewport != SplitScreenViewport.BottomHalf && viewport != SplitScreenViewport.TopHalf) ? FlatRedBallServices.ClientWidth / 2 : FlatRedBallServices.ClientWidth); // Set the bottom (top + height) mBottomDestination = mTopDestination + (( viewport != SplitScreenViewport.FullScreen && viewport != SplitScreenViewport.LeftHalf && viewport != SplitScreenViewport.RightHalf) ? FlatRedBallServices.ClientHeight / 2 : FlatRedBallServices.ClientHeight); // Update the destination rectangle UpdateDestinationRectangle(); } #if SUPPORTS_POST_PROCESSING public Texture2D GetShadowMapDepthTexture() { if (null != MyShadow) { ShadowMap shadowMap = MyShadow as ShadowMap; if (null != shadowMap) { return shadowMap.ShadowDepthTexture; } } return null; } public bool HasRenderTexture(RenderMode renderMode) { return RenderTargetTextures.ContainsKey((int)renderMode); } public Texture2D GetRenderTexture(RenderMode renderMode) { if (!RenderTargetTextures.ContainsKey((int)renderMode)) { Debug.Assert(false, "The specified render mode, " + renderMode.ToString() + " does not exist in this camera - did you forget to add it to the Camera's render order list? See http://www.flatredball.com/frb/docs/index.php?title=FlatRedBall.Camera#Rendering_Modes"); return null; } return RenderTargetTextures[(int)renderMode].Texture; } #endif #endregion #region Internal Methods //internal void FlushLayers() //{ // int layerCount = mLayers.Count; // for (int i = 0; i < layerCount; i++) // { // mLayers[i].Flush(); // } //} internal int UpdateSpriteInCameraView(SpriteList spriteList) { return UpdateSpriteInCameraView(spriteList, false); } internal int UpdateSpriteInCameraView(SpriteList spriteList, bool relativeToCamera) { int numberVisible = 0; for (int i = 0; i < spriteList.Count; i++) { Sprite s = spriteList[i]; if (!s.AbsoluteVisible || // If using InterpolateColor, then alpha is used for interpolation of colors and // not transparency #if FRB_MDX s.Alpha < .0001f) #else (s.ColorOperation != ColorOperation.InterpolateColor && s.Alpha < .0001f )) #endif { s.mInCameraView = false; continue; } s.mInCameraView = IsSpriteInView(s, relativeToCamera); if (s.mInCameraView) { numberVisible++; } } return numberVisible; } internal void UpdateOnResize() { if (mUsesSplitScreenViewport) SetSplitScreenViewport(splitScreenViewport); } #endregion #region Private Methods #region XML Docs /// <summary> /// Calculates the minimum and maximum X values for the camera based off of its /// base values (such as mBaseMaximumX) and its current view /// </summary> #endregion public void CalculateMaxAndMins() { // Vic says: This method used to be private. But now we want it public so that // Entities that control the camera can force calculate it. if (mOrthogonal) { mMinimumX = mBaseMinimumX + mOrthogonalWidth / 2.0f; mMaximumX = mBaseMaximumX - mOrthogonalWidth / 2.0f; mMinimumY = mBaseMinimumY + mOrthogonalHeight / 2.0f; mMaximumY = mBaseMaximumY - mOrthogonalHeight / 2.0f; } else { mMinimumX = mBaseMinimumX + mXEdge * (mBaseZ - Z) / (100f * MathFunctions.ForwardVector3.Z); mMaximumX = mBaseMaximumX - mXEdge * (mBaseZ - Z) / (100f * MathFunctions.ForwardVector3.Z); mMinimumY = mBaseMinimumY + mYEdge * (mBaseZ - Z) / (100f * MathFunctions.ForwardVector3.Z); mMaximumY = mBaseMaximumY - mYEdge * (mBaseZ - Z) / (100f * MathFunctions.ForwardVector3.Z); } } #region XML Docs /// <summary> /// Updates the destination rectangle (for the viewport). Also fixes the aspect ratio. /// </summary> #endregion private void UpdateDestinationRectangle() { //usesSplitScreenViewport = false; //mDestinationRectangle = value; //mTopDestination = mDestinationRectangle.Top; //mBottomDestination = mDestinationRectangle.Bottom; //mLeftDestination = mDestinationRectangle.Left; //mRightDestination = mDestinationRectangle.Right; //FixAspectRatioYConstant(); mDestinationRectangle = new Rectangle( (int)mLeftDestination, (int)mTopDestination, (int)(mRightDestination - mLeftDestination), (int)(mBottomDestination - mTopDestination)); FixAspectRatioYConstant(); #if SUPPORTS_POST_PROCESSING // Update post-processing buffers if (Renderer.UseRenderTargets && PostProcessingManager.IsInitialized) { foreach (PostProcessingEffectBase effect in PostProcessing.EffectCombineOrder) { effect.UpdateToScreenSize(); } } #endif } #endregion #region Protected Methods #endregion #endregion } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace ConditionsQuery.Models { /// <summary> /// Provides an implementation of the daml condition element. /// </summary> /// <remarks>Conditions can either be true or false depending on whether /// their corresponding 'state' is true or false. State, within Pro, is /// constantly changing in response to the UI Context, selected items, /// Project content changes, etc. Context changes are propogated to the UI /// in many cases via conditions. Whenever a condition changes from true to /// false, any UI elements using that condition are enabled/disabled or visible/hidden /// depending on what kind of UI element they are.<br/> /// You can read more about conditions here:<br/> /// <a href="https://github.com/ArcGIS/arcgis-pro-sdk/wiki/ProConcepts-Framework#condition-and-state"> /// https://github.com/ArcGIS/arcgis-pro-sdk/wiki/ProConcepts-Framework#condition-and-state</a></remarks> internal class Condition : INotifyPropertyChanged, IEnumerable<State> { private List<State> _states = null; private List<string> _flattenedStates = null; private bool _hasNotState = false; private bool _hasNotStateIsInitialized = false; private string _xml = ""; public Condition() { } private string _id = ""; private string _caption = ""; private bool _enabled = false; public event PropertyChangedEventHandler PropertyChanged = delegate { }; /// <summary> /// The condition id from the DAML /// </summary> public string ID => _id; /// <summary> /// Condition caption as read from the DAML /// </summary> /// <remarks>Optional</remarks> public string Caption => string.IsNullOrEmpty(_caption) ? _id : _caption; /// <summary> /// Gets and Sets whether the condition is currently enabled /// </summary> /// <remarks>The condition enabled/disabled state is controlled /// by whether or not Pro's active state matches the condition's /// state combination(s). /// The combination of state that a given condition may have can /// be quite complex and include Or, And, and Not relationships that /// can be nested. ///</remarks> public bool IsEnabled { get { return _enabled; } set { _enabled = value; OnPropertyChanged(); } } /// <summary> /// Gets the xml of the condition as read from the daml /// </summary> public string Xml => _xml; /// <summary> /// Configure the condition and state based on the condition xml read /// from the daml /// </summary> /// <param name="condition"></param> /// <returns></returns> public bool Configure(XElement condition) { //the condition must have children if (!condition.HasElements) //The condition node must have at least one child return false; _xml = condition.ToString(SaveOptions.DisableFormatting); //var reader = condition.CreateReader(); //reader.MoveToContent(); //_xml = reader.ReadInnerXml(); _id = condition.Attribute("id").Value; var attrib = condition.Attributes().FirstOrDefault(a => a.Name == "caption"); _caption = attrib?.Value; //The first child MUST be one of Or, And, or Not //The Or is implicit and so must be added if it was not //specified in the DAML bool needsOrStateNodeAdded = condition.Elements().First().Name.LocalName == "state"; //Get all the child state nodes var states = new List<State>(); foreach (var child in condition.Elements()) { //check what the first child node is var state = new State(); if (state.Configure(child)) { states.Add(state); } } //Do we need an Or Node added? if (needsOrStateNodeAdded) { _states = new List<State>(); _states.Add(new State() { StateType = StateType.Or }); _states[0].AddChildren(states); } else { _states = states; } return _states.Count > 0;//There has to be at least one state } /// <summary> /// Creates a condition for the given pane /// </summary> /// <remarks>Pane ids in Pro are implicitly conditions that are set true/false /// whenever their corresponding pane is activated/deactivated</remarks> /// <param name="pane"></param> /// <returns></returns> public bool ConfigurePane(XElement pane) { _id = pane.Attribute("id").Value; var attrib = pane.Attributes().FirstOrDefault(a => a.Name == "caption"); _caption = attrib?.Value; _states = new List<State>(); _states.Add(new State() { StateType = StateType.Or }); _states[0].AddChild(new State() { StateType = StateType.State, ID = _id }); return true; } /// <summary> /// Does the condition contain the given state id? /// </summary> /// <param name="stateID"></param> /// <returns></returns> public bool ContainsState(string stateID) { var states = this.GetStatesAsFlattenedList(); return states.Any(s => s == stateID); } /// <summary> /// Get the contained ids of the condition's states /// </summary> /// <remarks>Strips out the hierarchy and any boolean operators</remarks> /// <returns></returns> public IReadOnlyList<string> GetStatesAsFlattenedList() { //This can be cached. Once Pro has started it does not change if (_flattenedStates == null) { _flattenedStates = new List<string>(); foreach (var s in _states) { var fl = s.GetStateIdsAsFlattenedList(); foreach (var c in fl) _flattenedStates.Add(c); } } return _flattenedStates; } /// <summary> /// Gets whether or not the condition contains any "Not" /// state operators /// </summary> /// <remarks>Conditions containing Not state require special handling</remarks> /// <returns>True if the condition contains a "not" state node</returns> public bool HasNotState() { if (!_hasNotStateIsInitialized) { bool hasNotState = false; foreach (var s in _states) { var fl = s.GetStateIdsAsFlattenedList(StateType.Not); if (fl.Count > 0) { hasNotState = true; break; } } _hasNotState = hasNotState; _hasNotStateIsInitialized = true; } return _hasNotState; } /// <summary> /// Evaluates the condition against the given list of state ids /// </summary> /// <param name="activeStates"></param> /// <returns>True if the condition evaluates to true for the given state</returns> public bool MatchContext(IReadOnlyList<string> activeStates) { if (_states.Count > 1) { //implicit Or foreach (var state in _states) { if (state.MatchContext(activeStates)) return true; } return false; } else { return _states[0].MatchContext(activeStates); } } private void OnPropertyChanged([CallerMemberName] string propName = "") { PropertyChanged(this, new PropertyChangedEventArgs(propName)); } /// <summary> /// Required for implementation of IEnumerable /// </summary> /// <returns></returns> public IEnumerator<State> GetEnumerator() { return _states.GetEnumerator(); } /// <summary> /// Required for implementation of IEnumerable /// </summary> /// <returns></returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.IO; using System.Text; using NUnit.Framework; using osu.Game.Audio; using osu.Game.Beatmaps; using osu.Game.Beatmaps.Formats; using osu.Game.IO; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Osu.Beatmaps; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Screens.Edit; using osuTK; using Decoder = osu.Game.Beatmaps.Formats.Decoder; namespace osu.Game.Tests.Editing { [TestFixture] public class LegacyEditorBeatmapPatcherTest { private LegacyEditorBeatmapPatcher patcher; private EditorBeatmap current; [SetUp] public void Setup() { patcher = new LegacyEditorBeatmapPatcher(current = new EditorBeatmap(new OsuBeatmap { BeatmapInfo = { Ruleset = new OsuRuleset().RulesetInfo } })); } [Test] public void TestPatchNoObjectChanges() { runTest(new OsuBeatmap()); } [Test] public void TestAddHitObject() { var patch = new OsuBeatmap { HitObjects = { new HitCircle { StartTime = 1000, NewCombo = true } } }; runTest(patch); } [Test] public void TestInsertHitObject() { current.AddRange(new[] { new HitCircle { StartTime = 1000, NewCombo = true }, new HitCircle { StartTime = 3000 }, }); var patch = new OsuBeatmap { HitObjects = { (OsuHitObject)current.HitObjects[0], new HitCircle { StartTime = 2000 }, (OsuHitObject)current.HitObjects[1], } }; runTest(patch); } [Test] public void TestDeleteHitObject() { current.AddRange(new[] { new HitCircle { StartTime = 1000, NewCombo = true }, new HitCircle { StartTime = 2000 }, new HitCircle { StartTime = 3000 }, }); var patch = new OsuBeatmap { HitObjects = { (OsuHitObject)current.HitObjects[0], (OsuHitObject)current.HitObjects[2], } }; runTest(patch); } [Test] public void TestChangeStartTime() { current.AddRange(new[] { new HitCircle { StartTime = 1000, NewCombo = true }, new HitCircle { StartTime = 2000 }, new HitCircle { StartTime = 3000 }, }); var patch = new OsuBeatmap { HitObjects = { new HitCircle { StartTime = 500, NewCombo = true }, (OsuHitObject)current.HitObjects[1], (OsuHitObject)current.HitObjects[2], } }; runTest(patch); } [Test] public void TestChangeSample() { current.AddRange(new[] { new HitCircle { StartTime = 1000, NewCombo = true }, new HitCircle { StartTime = 2000 }, new HitCircle { StartTime = 3000 }, }); var patch = new OsuBeatmap { HitObjects = { (OsuHitObject)current.HitObjects[0], new HitCircle { StartTime = 2000, Samples = { new HitSampleInfo(HitSampleInfo.HIT_FINISH) } }, (OsuHitObject)current.HitObjects[2], } }; runTest(patch); } [Test] public void TestChangeSliderPath() { current.AddRange(new OsuHitObject[] { new HitCircle { StartTime = 1000, NewCombo = true }, new Slider { StartTime = 2000, Path = new SliderPath(new[] { new PathControlPoint(Vector2.Zero), new PathControlPoint(Vector2.One), new PathControlPoint(new Vector2(2), PathType.Bezier), new PathControlPoint(new Vector2(3)), }, 50) }, new HitCircle { StartTime = 3000 }, }); var patch = new OsuBeatmap { HitObjects = { (OsuHitObject)current.HitObjects[0], new Slider { StartTime = 2000, Path = new SliderPath(new[] { new PathControlPoint(Vector2.Zero, PathType.Bezier), new PathControlPoint(new Vector2(4)), new PathControlPoint(new Vector2(5)), }, 100) }, (OsuHitObject)current.HitObjects[2], } }; runTest(patch); } [Test] public void TestAddMultipleHitObjects() { current.AddRange(new[] { new HitCircle { StartTime = 1000, NewCombo = true }, new HitCircle { StartTime = 2000 }, new HitCircle { StartTime = 3000 }, }); var patch = new OsuBeatmap { HitObjects = { new HitCircle { StartTime = 500, NewCombo = true }, (OsuHitObject)current.HitObjects[0], new HitCircle { StartTime = 1500 }, (OsuHitObject)current.HitObjects[1], new HitCircle { StartTime = 2250 }, new HitCircle { StartTime = 2500 }, (OsuHitObject)current.HitObjects[2], new HitCircle { StartTime = 3500 }, } }; runTest(patch); } [Test] public void TestDeleteMultipleHitObjects() { current.AddRange(new[] { new HitCircle { StartTime = 500, NewCombo = true }, new HitCircle { StartTime = 1000 }, new HitCircle { StartTime = 1500 }, new HitCircle { StartTime = 2000 }, new HitCircle { StartTime = 2250 }, new HitCircle { StartTime = 2500 }, new HitCircle { StartTime = 3000 }, new HitCircle { StartTime = 3500 }, }); var patchedFirst = (HitCircle)current.HitObjects[1]; patchedFirst.NewCombo = true; var patch = new OsuBeatmap { HitObjects = { (OsuHitObject)current.HitObjects[1], (OsuHitObject)current.HitObjects[3], (OsuHitObject)current.HitObjects[6], } }; runTest(patch); } [Test] public void TestChangeSamplesOfMultipleHitObjects() { current.AddRange(new[] { new HitCircle { StartTime = 500, NewCombo = true }, new HitCircle { StartTime = 1000 }, new HitCircle { StartTime = 1500 }, new HitCircle { StartTime = 2000 }, new HitCircle { StartTime = 2250 }, new HitCircle { StartTime = 2500 }, new HitCircle { StartTime = 3000 }, new HitCircle { StartTime = 3500 }, }); var patch = new OsuBeatmap { HitObjects = { (OsuHitObject)current.HitObjects[0], new HitCircle { StartTime = 1000, Samples = { new HitSampleInfo(HitSampleInfo.HIT_FINISH) } }, (OsuHitObject)current.HitObjects[2], (OsuHitObject)current.HitObjects[3], new HitCircle { StartTime = 2250, Samples = { new HitSampleInfo(HitSampleInfo.HIT_WHISTLE) } }, (OsuHitObject)current.HitObjects[5], new HitCircle { StartTime = 3000, Samples = { new HitSampleInfo(HitSampleInfo.HIT_CLAP) } }, (OsuHitObject)current.HitObjects[7], } }; runTest(patch); } [Test] public void TestAddAndDeleteHitObjects() { current.AddRange(new[] { new HitCircle { StartTime = 500, NewCombo = true }, new HitCircle { StartTime = 1000 }, new HitCircle { StartTime = 1500 }, new HitCircle { StartTime = 2000 }, new HitCircle { StartTime = 2250 }, new HitCircle { StartTime = 2500 }, new HitCircle { StartTime = 3000 }, new HitCircle { StartTime = 3500 }, }); var patch = new OsuBeatmap { HitObjects = { new HitCircle { StartTime = 750, NewCombo = true }, (OsuHitObject)current.HitObjects[1], (OsuHitObject)current.HitObjects[4], (OsuHitObject)current.HitObjects[5], new HitCircle { StartTime = 2650 }, new HitCircle { StartTime = 2750 }, new HitCircle { StartTime = 4000 }, } }; runTest(patch); } [Test] public void TestChangeHitObjectAtSameTime() { current.AddRange(new[] { new HitCircle { StartTime = 500, Position = new Vector2(50), NewCombo = true }, new HitCircle { StartTime = 500, Position = new Vector2(100), NewCombo = true }, new HitCircle { StartTime = 500, Position = new Vector2(150), NewCombo = true }, new HitCircle { StartTime = 500, Position = new Vector2(200), NewCombo = true }, }); var patch = new OsuBeatmap { HitObjects = { new HitCircle { StartTime = 500, Position = new Vector2(150), NewCombo = true }, new HitCircle { StartTime = 500, Position = new Vector2(100), NewCombo = true }, new HitCircle { StartTime = 500, Position = new Vector2(50), NewCombo = true }, new HitCircle { StartTime = 500, Position = new Vector2(200), NewCombo = true }, } }; runTest(patch); } private void runTest(IBeatmap patch) { // Due to the method of testing, "patch" comes in without having been decoded via a beatmap decoder. // This causes issues because the decoder adds various default properties (e.g. new combo on first object, default samples). // To resolve "patch" into a sane state it is encoded and then re-decoded. patch = decode(encode(patch)); // Apply the patch. patcher.Patch(encode(current), encode(patch)); // Convert beatmaps to strings for assertion purposes. string currentStr = Encoding.ASCII.GetString(encode(current)); string patchStr = Encoding.ASCII.GetString(encode(patch)); Assert.That(currentStr, Is.EqualTo(patchStr)); } private byte[] encode(IBeatmap beatmap) { using (var encoded = new MemoryStream()) { using (var sw = new StreamWriter(encoded)) new LegacyBeatmapEncoder(beatmap, null).Encode(sw); return encoded.ToArray(); } } private IBeatmap decode(byte[] state) { using (var stream = new MemoryStream(state)) using (var reader = new LineBufferedReader(stream)) return Decoder.GetDecoder<Beatmap>(reader).Decode(reader); } } }
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 MVP.Service.WebAPI.Areas.HelpPage.ModelDescriptions; using MVP.Service.WebAPI.Areas.HelpPage.Models; namespace MVP.Service.WebAPI.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); } } } }
namespace Azure.Storage.Queues { public partial class QueueClient { protected QueueClient() { } public QueueClient(string connectionString, string queueName) { } public QueueClient(string connectionString, string queueName, Azure.Storage.Queues.QueueClientOptions options) { } public QueueClient(System.Uri queueUri, Azure.AzureSasCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { } public QueueClient(System.Uri queueUri, Azure.Core.TokenCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { } public QueueClient(System.Uri queueUri, Azure.Storage.Queues.QueueClientOptions options = null) { } public QueueClient(System.Uri queueUri, Azure.Storage.StorageSharedKeyCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { } public virtual string AccountName { get { throw null; } } public virtual bool CanGenerateSasUri { get { throw null; } } public virtual int MaxPeekableMessages { get { throw null; } } public virtual int MessageMaxBytes { get { throw null; } } protected virtual System.Uri MessagesUri { get { throw null; } } public virtual string Name { get { throw null; } } public virtual System.Uri Uri { get { throw null; } } public virtual Azure.Response ClearMessages(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> ClearMessagesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response Create(System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> CreateAsync(System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response CreateIfNotExists(System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> CreateIfNotExistsAsync(System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response Delete(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> DeleteAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<bool> DeleteIfExists(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<bool>> DeleteIfExistsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response DeleteMessage(string messageId, string popReceipt, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> DeleteMessageAsync(string messageId, string popReceipt, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<bool> Exists(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<bool>> ExistsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Uri GenerateSasUri(Azure.Storage.Sas.QueueSasBuilder builder) { throw null; } public virtual System.Uri GenerateSasUri(Azure.Storage.Sas.QueueSasPermissions permissions, System.DateTimeOffset expiresOn) { throw null; } public virtual Azure.Response<System.Collections.Generic.IEnumerable<Azure.Storage.Queues.Models.QueueSignedIdentifier>> GetAccessPolicy(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<System.Collections.Generic.IEnumerable<Azure.Storage.Queues.Models.QueueSignedIdentifier>>> GetAccessPolicyAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } protected internal virtual Azure.Storage.Queues.QueueServiceClient GetParentQueueServiceClientCore() { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.QueueProperties> GetProperties(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueProperties>> GetPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } protected virtual System.Threading.Tasks.Task OnMessageDecodingFailedAsync(Azure.Storage.Queues.Models.QueueMessage receivedMessage, Azure.Storage.Queues.Models.PeekedMessage peekedMessage, bool isRunningSynchronously, System.Threading.CancellationToken cancellationToken) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.PeekedMessage> PeekMessage(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.PeekedMessage>> PeekMessageAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.PeekedMessage[]> PeekMessages(int? maxMessages = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.PeekedMessage[]>> PeekMessagesAsync(int? maxMessages = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.QueueMessage> ReceiveMessage(System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueMessage>> ReceiveMessageAsync(System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]> ReceiveMessages() { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]> ReceiveMessages(int? maxMessages = default(int?), System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]> ReceiveMessages(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]>> ReceiveMessagesAsync() { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]>> ReceiveMessagesAsync(int? maxMessages = default(int?), System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]>> ReceiveMessagesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.SendReceipt> SendMessage(System.BinaryData message, System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.TimeSpan? timeToLive = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.SendReceipt> SendMessage(string messageText) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.SendReceipt> SendMessage(string messageText, System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.TimeSpan? timeToLive = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.SendReceipt> SendMessage(string messageText, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.SendReceipt>> SendMessageAsync(System.BinaryData message, System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.TimeSpan? timeToLive = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.SendReceipt>> SendMessageAsync(string messageText) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.SendReceipt>> SendMessageAsync(string messageText, System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.TimeSpan? timeToLive = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.SendReceipt>> SendMessageAsync(string messageText, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response SetAccessPolicy(System.Collections.Generic.IEnumerable<Azure.Storage.Queues.Models.QueueSignedIdentifier> permissions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> SetAccessPolicyAsync(System.Collections.Generic.IEnumerable<Azure.Storage.Queues.Models.QueueSignedIdentifier> permissions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response SetMetadata(System.Collections.Generic.IDictionary<string, string> metadata, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> SetMetadataAsync(System.Collections.Generic.IDictionary<string, string> metadata, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.UpdateReceipt> UpdateMessage(string messageId, string popReceipt, System.BinaryData message, System.TimeSpan visibilityTimeout = default(System.TimeSpan), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.UpdateReceipt> UpdateMessage(string messageId, string popReceipt, string messageText = null, System.TimeSpan visibilityTimeout = default(System.TimeSpan), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.UpdateReceipt>> UpdateMessageAsync(string messageId, string popReceipt, System.BinaryData message, System.TimeSpan visibilityTimeout = default(System.TimeSpan), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.UpdateReceipt>> UpdateMessageAsync(string messageId, string popReceipt, string messageText = null, System.TimeSpan visibilityTimeout = default(System.TimeSpan), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } protected internal virtual Azure.Storage.Queues.QueueClient WithClientSideEncryptionOptionsCore(Azure.Storage.ClientSideEncryptionOptions clientSideEncryptionOptions) { throw null; } } public partial class QueueClientOptions : Azure.Core.ClientOptions { public QueueClientOptions(Azure.Storage.Queues.QueueClientOptions.ServiceVersion version = Azure.Storage.Queues.QueueClientOptions.ServiceVersion.V2020_10_02) { } public bool EnableTenantDiscovery { get { throw null; } set { } } public System.Uri GeoRedundantSecondaryUri { get { throw null; } set { } } public Azure.Storage.Queues.QueueMessageEncoding MessageEncoding { get { throw null; } set { } } public Azure.Storage.Queues.QueueClientOptions.ServiceVersion Version { get { throw null; } } public event Azure.Core.SyncAsyncEventHandler<Azure.Storage.Queues.QueueMessageDecodingFailedEventArgs> MessageDecodingFailed { add { } remove { } } public enum ServiceVersion { V2019_02_02 = 1, V2019_07_07 = 2, V2019_12_12 = 3, V2020_02_10 = 4, V2020_04_08 = 5, V2020_06_12 = 6, V2020_08_04 = 7, V2020_10_02 = 8, V2020_12_06 = 9, } } public partial class QueueMessageDecodingFailedEventArgs : Azure.SyncAsyncEventArgs { public QueueMessageDecodingFailedEventArgs(Azure.Storage.Queues.QueueClient queueClient, Azure.Storage.Queues.Models.QueueMessage receivedMessage, Azure.Storage.Queues.Models.PeekedMessage peekedMessage, bool isRunningSynchronously, System.Threading.CancellationToken cancellationToken) : base (default(bool), default(System.Threading.CancellationToken)) { } public Azure.Storage.Queues.Models.PeekedMessage PeekedMessage { get { throw null; } } public Azure.Storage.Queues.QueueClient Queue { get { throw null; } } public Azure.Storage.Queues.Models.QueueMessage ReceivedMessage { get { throw null; } } } public enum QueueMessageEncoding { None = 0, Base64 = 1, } public partial class QueueServiceClient { protected QueueServiceClient() { } public QueueServiceClient(string connectionString) { } public QueueServiceClient(string connectionString, Azure.Storage.Queues.QueueClientOptions options) { } public QueueServiceClient(System.Uri serviceUri, Azure.AzureSasCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { } public QueueServiceClient(System.Uri serviceUri, Azure.Core.TokenCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { } public QueueServiceClient(System.Uri serviceUri, Azure.Storage.Queues.QueueClientOptions options = null) { } public QueueServiceClient(System.Uri serviceUri, Azure.Storage.StorageSharedKeyCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { } public virtual string AccountName { get { throw null; } } public virtual bool CanGenerateAccountSasUri { get { throw null; } } public virtual System.Uri Uri { get { throw null; } } public virtual Azure.Response<Azure.Storage.Queues.QueueClient> CreateQueue(string queueName, System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.QueueClient>> CreateQueueAsync(string queueName, System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response DeleteQueue(string queueName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> DeleteQueueAsync(string queueName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public System.Uri GenerateAccountSasUri(Azure.Storage.Sas.AccountSasBuilder builder) { throw null; } public System.Uri GenerateAccountSasUri(Azure.Storage.Sas.AccountSasPermissions permissions, System.DateTimeOffset expiresOn, Azure.Storage.Sas.AccountSasResourceTypes resourceTypes) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.QueueServiceProperties> GetProperties(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueServiceProperties>> GetPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Storage.Queues.QueueClient GetQueueClient(string queueName) { throw null; } public virtual Azure.Pageable<Azure.Storage.Queues.Models.QueueItem> GetQueues(Azure.Storage.Queues.Models.QueueTraits traits = Azure.Storage.Queues.Models.QueueTraits.None, string prefix = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.Storage.Queues.Models.QueueItem> GetQueuesAsync(Azure.Storage.Queues.Models.QueueTraits traits = Azure.Storage.Queues.Models.QueueTraits.None, string prefix = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.QueueServiceStatistics> GetStatistics(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueServiceStatistics>> GetStatisticsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response SetProperties(Azure.Storage.Queues.Models.QueueServiceProperties properties, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> SetPropertiesAsync(Azure.Storage.Queues.Models.QueueServiceProperties properties, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class QueueUriBuilder { public QueueUriBuilder(System.Uri uri) { } public string AccountName { get { throw null; } set { } } public string Host { get { throw null; } set { } } public string MessageId { get { throw null; } set { } } public bool Messages { get { throw null; } set { } } public int Port { get { throw null; } set { } } public string Query { get { throw null; } set { } } public string QueueName { get { throw null; } set { } } public Azure.Storage.Sas.SasQueryParameters Sas { get { throw null; } set { } } public string Scheme { get { throw null; } set { } } public override string ToString() { throw null; } public System.Uri ToUri() { throw null; } } } namespace Azure.Storage.Queues.Models { public partial class PeekedMessage { internal PeekedMessage() { } public System.BinaryData Body { get { throw null; } } public long DequeueCount { get { throw null; } } public System.DateTimeOffset? ExpiresOn { get { throw null; } } public System.DateTimeOffset? InsertedOn { get { throw null; } } public string MessageId { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public string MessageText { get { throw null; } } } public partial class QueueAccessPolicy { public QueueAccessPolicy() { } public System.DateTimeOffset? ExpiresOn { get { throw null; } set { } } public string Permissions { get { throw null; } set { } } public System.DateTimeOffset? StartsOn { get { throw null; } set { } } } public partial class QueueAnalyticsLogging { public QueueAnalyticsLogging() { } public bool Delete { get { throw null; } set { } } public bool Read { get { throw null; } set { } } public Azure.Storage.Queues.Models.QueueRetentionPolicy RetentionPolicy { get { throw null; } set { } } public string Version { get { throw null; } set { } } public bool Write { get { throw null; } set { } } } public partial class QueueCorsRule { public QueueCorsRule() { } public string AllowedHeaders { get { throw null; } set { } } public string AllowedMethods { get { throw null; } set { } } public string AllowedOrigins { get { throw null; } set { } } public string ExposedHeaders { get { throw null; } set { } } public int MaxAgeInSeconds { get { throw null; } set { } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct QueueErrorCode : System.IEquatable<Azure.Storage.Queues.Models.QueueErrorCode> { private readonly object _dummy; private readonly int _dummyPrimitive; public QueueErrorCode(string value) { throw null; } public static Azure.Storage.Queues.Models.QueueErrorCode AccountAlreadyExists { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode AccountBeingCreated { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode AccountIsDisabled { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode AuthenticationFailed { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationFailure { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationPermissionMismatch { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationProtocolMismatch { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationResourceTypeMismatch { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationServiceMismatch { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationSourceIPMismatch { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode ConditionHeadersNotSupported { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode ConditionNotMet { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode EmptyMetadataKey { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode FeatureVersionMismatch { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InsufficientAccountPermissions { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InternalError { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidAuthenticationInfo { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidHeaderValue { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidHttpVerb { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidInput { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidMarker { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidMd5 { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidMetadata { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidQueryParameterValue { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidRange { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidResourceName { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidUri { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidXmlDocument { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidXmlNodeValue { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode Md5Mismatch { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode MessageNotFound { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode MessageTooLarge { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode MetadataTooLarge { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode MissingContentLengthHeader { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode MissingRequiredHeader { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode MissingRequiredQueryParameter { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode MissingRequiredXmlNode { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode MultipleConditionHeadersNotSupported { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode OperationTimedOut { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode OutOfRangeInput { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode OutOfRangeQueryParameterValue { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode PopReceiptMismatch { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode QueueAlreadyExists { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode QueueBeingDeleted { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode QueueDisabled { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode QueueNotEmpty { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode QueueNotFound { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode RequestBodyTooLarge { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode RequestUrlFailedToParse { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode ResourceAlreadyExists { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode ResourceNotFound { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode ResourceTypeMismatch { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode ServerBusy { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode UnsupportedHeader { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode UnsupportedHttpVerb { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode UnsupportedQueryParameter { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode UnsupportedXmlNode { get { throw null; } } public bool Equals(Azure.Storage.Queues.Models.QueueErrorCode other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Storage.Queues.Models.QueueErrorCode left, Azure.Storage.Queues.Models.QueueErrorCode right) { throw null; } public static implicit operator Azure.Storage.Queues.Models.QueueErrorCode (string value) { throw null; } public static bool operator !=(Azure.Storage.Queues.Models.QueueErrorCode left, Azure.Storage.Queues.Models.QueueErrorCode right) { throw null; } public override string ToString() { throw null; } } public partial class QueueGeoReplication { internal QueueGeoReplication() { } public System.DateTimeOffset? LastSyncedOn { get { throw null; } } public Azure.Storage.Queues.Models.QueueGeoReplicationStatus Status { get { throw null; } } } public enum QueueGeoReplicationStatus { Live = 0, Bootstrap = 1, Unavailable = 2, } public partial class QueueItem { internal QueueItem() { } public System.Collections.Generic.IDictionary<string, string> Metadata { get { throw null; } } public string Name { get { throw null; } } } public partial class QueueMessage { internal QueueMessage() { } public System.BinaryData Body { get { throw null; } } public long DequeueCount { get { throw null; } } public System.DateTimeOffset? ExpiresOn { get { throw null; } } public System.DateTimeOffset? InsertedOn { get { throw null; } } public string MessageId { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public string MessageText { get { throw null; } } public System.DateTimeOffset? NextVisibleOn { get { throw null; } } public string PopReceipt { get { throw null; } } public Azure.Storage.Queues.Models.QueueMessage Update(Azure.Storage.Queues.Models.UpdateReceipt updated) { throw null; } } public partial class QueueMetrics { public QueueMetrics() { } public bool Enabled { get { throw null; } set { } } public bool? IncludeApis { get { throw null; } set { } } public Azure.Storage.Queues.Models.QueueRetentionPolicy RetentionPolicy { get { throw null; } set { } } public string Version { get { throw null; } set { } } } public partial class QueueProperties { public QueueProperties() { } public int ApproximateMessagesCount { get { throw null; } } public System.Collections.Generic.IDictionary<string, string> Metadata { get { throw null; } } } public partial class QueueRetentionPolicy { public QueueRetentionPolicy() { } public int? Days { get { throw null; } set { } } public bool Enabled { get { throw null; } set { } } } public partial class QueueServiceProperties { public QueueServiceProperties() { } public System.Collections.Generic.IList<Azure.Storage.Queues.Models.QueueCorsRule> Cors { get { throw null; } set { } } public Azure.Storage.Queues.Models.QueueMetrics HourMetrics { get { throw null; } set { } } public Azure.Storage.Queues.Models.QueueAnalyticsLogging Logging { get { throw null; } set { } } public Azure.Storage.Queues.Models.QueueMetrics MinuteMetrics { get { throw null; } set { } } } public partial class QueueServiceStatistics { internal QueueServiceStatistics() { } public Azure.Storage.Queues.Models.QueueGeoReplication GeoReplication { get { throw null; } } } public partial class QueueSignedIdentifier { public QueueSignedIdentifier() { } public Azure.Storage.Queues.Models.QueueAccessPolicy AccessPolicy { get { throw null; } set { } } public string Id { get { throw null; } set { } } } public static partial class QueuesModelFactory { public static Azure.Storage.Queues.Models.PeekedMessage PeekedMessage(string messageId, System.BinaryData message, long dequeueCount, System.DateTimeOffset? insertedOn = default(System.DateTimeOffset?), System.DateTimeOffset? expiresOn = default(System.DateTimeOffset?)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static Azure.Storage.Queues.Models.PeekedMessage PeekedMessage(string messageId, string messageText, long dequeueCount, System.DateTimeOffset? insertedOn = default(System.DateTimeOffset?), System.DateTimeOffset? expiresOn = default(System.DateTimeOffset?)) { throw null; } public static Azure.Storage.Queues.Models.QueueGeoReplication QueueGeoReplication(Azure.Storage.Queues.Models.QueueGeoReplicationStatus status, System.DateTimeOffset? lastSyncedOn = default(System.DateTimeOffset?)) { throw null; } public static Azure.Storage.Queues.Models.QueueItem QueueItem(string name, System.Collections.Generic.IDictionary<string, string> metadata = null) { throw null; } public static Azure.Storage.Queues.Models.QueueMessage QueueMessage(string messageId, string popReceipt, System.BinaryData body, long dequeueCount, System.DateTimeOffset? nextVisibleOn = default(System.DateTimeOffset?), System.DateTimeOffset? insertedOn = default(System.DateTimeOffset?), System.DateTimeOffset? expiresOn = default(System.DateTimeOffset?)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static Azure.Storage.Queues.Models.QueueMessage QueueMessage(string messageId, string popReceipt, string messageText, long dequeueCount, System.DateTimeOffset? nextVisibleOn = default(System.DateTimeOffset?), System.DateTimeOffset? insertedOn = default(System.DateTimeOffset?), System.DateTimeOffset? expiresOn = default(System.DateTimeOffset?)) { throw null; } public static Azure.Storage.Queues.Models.QueueProperties QueueProperties(System.Collections.Generic.IDictionary<string, string> metadata, int approximateMessagesCount) { throw null; } public static Azure.Storage.Queues.Models.QueueServiceStatistics QueueServiceStatistics(Azure.Storage.Queues.Models.QueueGeoReplication geoReplication = null) { throw null; } public static Azure.Storage.Queues.Models.SendReceipt SendReceipt(string messageId, System.DateTimeOffset insertionTime, System.DateTimeOffset expirationTime, string popReceipt, System.DateTimeOffset timeNextVisible) { throw null; } public static Azure.Storage.Queues.Models.UpdateReceipt UpdateReceipt(string popReceipt, System.DateTimeOffset nextVisibleOn) { throw null; } } [System.FlagsAttribute] public enum QueueTraits { None = 0, Metadata = 1, } public partial class SendReceipt { internal SendReceipt() { } public System.DateTimeOffset ExpirationTime { get { throw null; } } public System.DateTimeOffset InsertionTime { get { throw null; } } public string MessageId { get { throw null; } } public string PopReceipt { get { throw null; } } public System.DateTimeOffset TimeNextVisible { get { throw null; } } } public partial class UpdateReceipt { internal UpdateReceipt() { } public System.DateTimeOffset NextVisibleOn { get { throw null; } } public string PopReceipt { get { throw null; } } } } namespace Azure.Storage.Queues.Specialized { public partial class ClientSideDecryptionFailureEventArgs { internal ClientSideDecryptionFailureEventArgs() { } public System.Exception Exception { get { throw null; } } } public partial class QueueClientSideEncryptionOptions : Azure.Storage.ClientSideEncryptionOptions { public QueueClientSideEncryptionOptions(Azure.Storage.ClientSideEncryptionVersion version) : base (default(Azure.Storage.ClientSideEncryptionVersion)) { } public event System.EventHandler<Azure.Storage.Queues.Specialized.ClientSideDecryptionFailureEventArgs> DecryptionFailed { add { } remove { } } } public partial class SpecializedQueueClientOptions : Azure.Storage.Queues.QueueClientOptions { public SpecializedQueueClientOptions(Azure.Storage.Queues.QueueClientOptions.ServiceVersion version = Azure.Storage.Queues.QueueClientOptions.ServiceVersion.V2020_10_02) : base (default(Azure.Storage.Queues.QueueClientOptions.ServiceVersion)) { } public Azure.Storage.ClientSideEncryptionOptions ClientSideEncryption { get { throw null; } set { } } } public static partial class SpecializedQueueExtensions { public static Azure.Storage.Queues.QueueServiceClient GetParentQueueServiceClient(this Azure.Storage.Queues.QueueClient client) { throw null; } public static Azure.Storage.Queues.QueueClient WithClientSideEncryptionOptions(this Azure.Storage.Queues.QueueClient client, Azure.Storage.ClientSideEncryptionOptions clientSideEncryptionOptions) { throw null; } } } namespace Azure.Storage.Sas { [System.FlagsAttribute] public enum QueueAccountSasPermissions { All = -1, Read = 1, Write = 2, Delete = 4, List = 8, Add = 16, Update = 32, Process = 64, } public partial class QueueSasBuilder { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public QueueSasBuilder() { } public QueueSasBuilder(Azure.Storage.Sas.QueueAccountSasPermissions permissions, System.DateTimeOffset expiresOn) { } public QueueSasBuilder(Azure.Storage.Sas.QueueSasPermissions permissions, System.DateTimeOffset expiresOn) { } public System.DateTimeOffset ExpiresOn { get { throw null; } set { } } public string Identifier { get { throw null; } set { } } public Azure.Storage.Sas.SasIPRange IPRange { get { throw null; } set { } } public string Permissions { get { throw null; } } public Azure.Storage.Sas.SasProtocol Protocol { get { throw null; } set { } } public string QueueName { get { throw null; } set { } } public System.DateTimeOffset StartsOn { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public string Version { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public void SetPermissions(Azure.Storage.Sas.QueueAccountSasPermissions permissions) { } public void SetPermissions(Azure.Storage.Sas.QueueSasPermissions permissions) { } public void SetPermissions(string rawPermissions) { } public void SetPermissions(string rawPermissions, bool normalize = false) { } public Azure.Storage.Sas.SasQueryParameters ToSasQueryParameters(Azure.Storage.StorageSharedKeyCredential sharedKeyCredential) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } [System.FlagsAttribute] public enum QueueSasPermissions { All = -1, Read = 1, Add = 2, Update = 4, Process = 8, } } namespace Microsoft.Extensions.Azure { public static partial class QueueClientBuilderExtensions { public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Storage.Queues.QueueServiceClient, Azure.Storage.Queues.QueueClientOptions> AddQueueServiceClient<TBuilder>(this TBuilder builder, string connectionString) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Storage.Queues.QueueServiceClient, Azure.Storage.Queues.QueueClientOptions> AddQueueServiceClient<TBuilder>(this TBuilder builder, System.Uri serviceUri) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Storage.Queues.QueueServiceClient, Azure.Storage.Queues.QueueClientOptions> AddQueueServiceClient<TBuilder>(this TBuilder builder, System.Uri serviceUri, Azure.Storage.StorageSharedKeyCredential sharedKeyCredential) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Storage.Queues.QueueServiceClient, Azure.Storage.Queues.QueueClientOptions> AddQueueServiceClient<TBuilder, TConfiguration>(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration<TConfiguration> { throw null; } } }
using System; using System.Data; using Csla; using Csla.Data; using ParentLoadSoftDelete.DataAccess; using ParentLoadSoftDelete.DataAccess.ERLevel; namespace ParentLoadSoftDelete.Business.ERLevel { /// <summary> /// E04_SubContinent (editable child object).<br/> /// This is a generated base class of <see cref="E04_SubContinent"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="E05_CountryObjects"/> of type <see cref="E05_CountryColl"/> (1:M relation to <see cref="E06_Country"/>)<br/> /// This class is an item of <see cref="E03_SubContinentColl"/> collection. /// </remarks> [Serializable] public partial class E04_SubContinent : BusinessBase<E04_SubContinent> { #region Static Fields private static int _lastID; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="SubContinent_ID"/> property. /// </summary> public static readonly PropertyInfo<int> SubContinent_IDProperty = RegisterProperty<int>(p => p.SubContinent_ID, "SubContinents ID"); /// <summary> /// Gets the SubContinents ID. /// </summary> /// <value>The SubContinents ID.</value> public int SubContinent_ID { get { return GetProperty(SubContinent_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="SubContinent_Name"/> property. /// </summary> public static readonly PropertyInfo<string> SubContinent_NameProperty = RegisterProperty<string>(p => p.SubContinent_Name, "SubContinents Name"); /// <summary> /// Gets or sets the SubContinents Name. /// </summary> /// <value>The SubContinents Name.</value> public string SubContinent_Name { get { return GetProperty(SubContinent_NameProperty); } set { SetProperty(SubContinent_NameProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="E05_SubContinent_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<E05_SubContinent_Child> E05_SubContinent_SingleObjectProperty = RegisterProperty<E05_SubContinent_Child>(p => p.E05_SubContinent_SingleObject, "E05 SubContinent Single Object", RelationshipTypes.Child); /// <summary> /// Gets the E05 Sub Continent Single Object ("parent load" child property). /// </summary> /// <value>The E05 Sub Continent Single Object.</value> public E05_SubContinent_Child E05_SubContinent_SingleObject { get { return GetProperty(E05_SubContinent_SingleObjectProperty); } private set { LoadProperty(E05_SubContinent_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="E05_SubContinent_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<E05_SubContinent_ReChild> E05_SubContinent_ASingleObjectProperty = RegisterProperty<E05_SubContinent_ReChild>(p => p.E05_SubContinent_ASingleObject, "E05 SubContinent ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the E05 Sub Continent ASingle Object ("parent load" child property). /// </summary> /// <value>The E05 Sub Continent ASingle Object.</value> public E05_SubContinent_ReChild E05_SubContinent_ASingleObject { get { return GetProperty(E05_SubContinent_ASingleObjectProperty); } private set { LoadProperty(E05_SubContinent_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="E05_CountryObjects"/> property. /// </summary> public static readonly PropertyInfo<E05_CountryColl> E05_CountryObjectsProperty = RegisterProperty<E05_CountryColl>(p => p.E05_CountryObjects, "E05 Country Objects", RelationshipTypes.Child); /// <summary> /// Gets the E05 Country Objects ("parent load" child property). /// </summary> /// <value>The E05 Country Objects.</value> public E05_CountryColl E05_CountryObjects { get { return GetProperty(E05_CountryObjectsProperty); } private set { LoadProperty(E05_CountryObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="E04_SubContinent"/> object. /// </summary> /// <returns>A reference to the created <see cref="E04_SubContinent"/> object.</returns> internal static E04_SubContinent NewE04_SubContinent() { return DataPortal.CreateChild<E04_SubContinent>(); } /// <summary> /// Factory method. Loads a <see cref="E04_SubContinent"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="E04_SubContinent"/> object.</returns> internal static E04_SubContinent GetE04_SubContinent(SafeDataReader dr) { E04_SubContinent obj = new E04_SubContinent(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.LoadProperty(E05_CountryObjectsProperty, E05_CountryColl.NewE05_CountryColl()); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="E04_SubContinent"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public E04_SubContinent() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="E04_SubContinent"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(SubContinent_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(E05_SubContinent_SingleObjectProperty, DataPortal.CreateChild<E05_SubContinent_Child>()); LoadProperty(E05_SubContinent_ASingleObjectProperty, DataPortal.CreateChild<E05_SubContinent_ReChild>()); LoadProperty(E05_CountryObjectsProperty, DataPortal.CreateChild<E05_CountryColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="E04_SubContinent"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(SubContinent_IDProperty, dr.GetInt32("SubContinent_ID")); LoadProperty(SubContinent_NameProperty, dr.GetString("SubContinent_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child <see cref="E05_SubContinent_Child"/> object. /// </summary> /// <param name="child">The child object to load.</param> internal void LoadChild(E05_SubContinent_Child child) { LoadProperty(E05_SubContinent_SingleObjectProperty, child); } /// <summary> /// Loads child <see cref="E05_SubContinent_ReChild"/> object. /// </summary> /// <param name="child">The child object to load.</param> internal void LoadChild(E05_SubContinent_ReChild child) { LoadProperty(E05_SubContinent_ASingleObjectProperty, child); } /// <summary> /// Inserts a new <see cref="E04_SubContinent"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(E02_Continent parent) { using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnInsertPre(args); var dal = dalManager.GetProvider<IE04_SubContinentDal>(); using (BypassPropertyChecks) { int subContinent_ID = -1; dal.Insert( parent.Continent_ID, out subContinent_ID, SubContinent_Name ); LoadProperty(SubContinent_IDProperty, subContinent_ID); } OnInsertPost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="E04_SubContinent"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnUpdatePre(args); var dal = dalManager.GetProvider<IE04_SubContinentDal>(); using (BypassPropertyChecks) { dal.Update( SubContinent_ID, SubContinent_Name ); } OnUpdatePost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="E04_SubContinent"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); // flushes all pending data operations FieldManager.UpdateChildren(this); OnDeletePre(args); var dal = dalManager.GetProvider<IE04_SubContinentDal>(); using (BypassPropertyChecks) { dal.Delete(ReadProperty(SubContinent_IDProperty)); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Net.Security; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class SspiCli { internal const uint SECQOP_WRAP_NO_ENCRYPT = 0x80000001; internal const int SEC_I_RENEGOTIATE = 0x90321; internal const int SECPKG_NEGOTIATION_COMPLETE = 0; internal const int SECPKG_NEGOTIATION_OPTIMISTIC = 1; [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct CredHandle { private IntPtr dwLower; private IntPtr dwUpper; public bool IsZero { get { return dwLower == IntPtr.Zero && dwUpper == IntPtr.Zero; } } internal void SetToInvalid() { dwLower = IntPtr.Zero; dwUpper = IntPtr.Zero; } public override string ToString() { { return dwLower.ToString("x") + ":" + dwUpper.ToString("x"); } } } internal enum ContextAttribute { // sspi.h SECPKG_ATTR_SIZES = 0, SECPKG_ATTR_NAMES = 1, SECPKG_ATTR_LIFESPAN = 2, SECPKG_ATTR_DCE_INFO = 3, SECPKG_ATTR_STREAM_SIZES = 4, SECPKG_ATTR_AUTHORITY = 6, SECPKG_ATTR_PACKAGE_INFO = 10, SECPKG_ATTR_NEGOTIATION_INFO = 12, SECPKG_ATTR_UNIQUE_BINDINGS = 25, SECPKG_ATTR_ENDPOINT_BINDINGS = 26, SECPKG_ATTR_CLIENT_SPECIFIED_TARGET = 27, SECPKG_ATTR_APPLICATION_PROTOCOL = 35, // minschannel.h SECPKG_ATTR_REMOTE_CERT_CONTEXT = 0x53, // returns PCCERT_CONTEXT SECPKG_ATTR_LOCAL_CERT_CONTEXT = 0x54, // returns PCCERT_CONTEXT SECPKG_ATTR_ROOT_STORE = 0x55, // returns HCERTCONTEXT to the root store SECPKG_ATTR_ISSUER_LIST_EX = 0x59, // returns SecPkgContext_IssuerListInfoEx SECPKG_ATTR_CONNECTION_INFO = 0x5A, // returns SecPkgContext_ConnectionInfo SECPKG_ATTR_CIPHER_INFO = 0x64, // returns SecPkgContext_CipherInfo SECPKG_ATTR_UI_INFO = 0x68, // sets SEcPkgContext_UiInfo } // These values are defined within sspi.h as ISC_REQ_*, ISC_RET_*, ASC_REQ_* and ASC_RET_*. [Flags] internal enum ContextFlags { Zero = 0, // The server in the transport application can // build new security contexts impersonating the // client that will be accepted by other servers // as the client's contexts. Delegate = 0x00000001, // The communicating parties must authenticate // their identities to each other. Without MutualAuth, // the client authenticates its identity to the server. // With MutualAuth, the server also must authenticate // its identity to the client. MutualAuth = 0x00000002, // The security package detects replayed packets and // notifies the caller if a packet has been replayed. // The use of this flag implies all of the conditions // specified by the Integrity flag. ReplayDetect = 0x00000004, // The context must be allowed to detect out-of-order // delivery of packets later through the message support // functions. Use of this flag implies all of the // conditions specified by the Integrity flag. SequenceDetect = 0x00000008, // The context must protect data while in transit. // Confidentiality is supported for NTLM with Microsoft // Windows NT version 4.0, SP4 and later and with the // Kerberos protocol in Microsoft Windows 2000 and later. Confidentiality = 0x00000010, UseSessionKey = 0x00000020, AllocateMemory = 0x00000100, // Connection semantics must be used. Connection = 0x00000800, // Client applications requiring extended error messages specify the // ISC_REQ_EXTENDED_ERROR flag when calling the InitializeSecurityContext // Server applications requiring extended error messages set // the ASC_REQ_EXTENDED_ERROR flag when calling AcceptSecurityContext. InitExtendedError = 0x00004000, AcceptExtendedError = 0x00008000, // A transport application requests stream semantics // by setting the ISC_REQ_STREAM and ASC_REQ_STREAM // flags in the calls to the InitializeSecurityContext // and AcceptSecurityContext functions InitStream = 0x00008000, AcceptStream = 0x00010000, // Buffer integrity can be verified; however, replayed // and out-of-sequence messages will not be detected InitIntegrity = 0x00010000, // ISC_REQ_INTEGRITY AcceptIntegrity = 0x00020000, // ASC_REQ_INTEGRITY InitManualCredValidation = 0x00080000, // ISC_REQ_MANUAL_CRED_VALIDATION InitUseSuppliedCreds = 0x00000080, // ISC_REQ_USE_SUPPLIED_CREDS InitIdentify = 0x00020000, // ISC_REQ_IDENTIFY AcceptIdentify = 0x00080000, // ASC_REQ_IDENTIFY ProxyBindings = 0x04000000, // ASC_REQ_PROXY_BINDINGS AllowMissingBindings = 0x10000000, // ASC_REQ_ALLOW_MISSING_BINDINGS UnverifiedTargetName = 0x20000000, // ISC_REQ_UNVERIFIED_TARGET_NAME } internal enum Endianness { SECURITY_NETWORK_DREP = 0x00, SECURITY_NATIVE_DREP = 0x10, } internal enum CredentialUse { SECPKG_CRED_INBOUND = 0x1, SECPKG_CRED_OUTBOUND = 0x2, SECPKG_CRED_BOTH = 0x3, } // wincrypt.h [StructLayout(LayoutKind.Sequential)] internal struct CERT_CHAIN_ELEMENT { public uint cbSize; public IntPtr pCertContext; // Since this structure is allocated by unmanaged code, we can // omit the fields below since we don't need to access them // CERT_TRUST_STATUS TrustStatus; // IntPtr pRevocationInfo; // IntPtr pIssuanceUsage; // IntPtr pApplicationUsage; } // schannel.h [StructLayout(LayoutKind.Sequential)] internal unsafe struct SecPkgContext_IssuerListInfoEx { public IntPtr aIssuers; public uint cIssuers; } [StructLayout(LayoutKind.Sequential)] internal struct SCHANNEL_CRED { public const int CurrentVersion = 0x4; public int dwVersion; public int cCreds; // ptr to an array of pointers // There is a hack done with this field. AcquireCredentialsHandle requires an array of // certificate handles; we only ever use one. In order to avoid pinning a one element array, // we copy this value onto the stack, create a pointer on the stack to the copied value, // and replace this field with the pointer, during the call to AcquireCredentialsHandle. // Then we fix it up afterwards. Fine as long as all the SSPI credentials are not // supposed to be threadsafe. public IntPtr paCred; public IntPtr hRootStore; // == always null, OTHERWISE NOT RELIABLE public int cMappers; public IntPtr aphMappers; // == always null, OTHERWISE NOT RELIABLE public int cSupportedAlgs; public IntPtr palgSupportedAlgs; // == always null, OTHERWISE NOT RELIABLE public int grbitEnabledProtocols; public int dwMinimumCipherStrength; public int dwMaximumCipherStrength; public int dwSessionLifespan; public SCHANNEL_CRED.Flags dwFlags; public int reserved; [Flags] public enum Flags { Zero = 0, SCH_CRED_NO_SYSTEM_MAPPER = 0x02, SCH_CRED_NO_SERVERNAME_CHECK = 0x04, SCH_CRED_MANUAL_CRED_VALIDATION = 0x08, SCH_CRED_NO_DEFAULT_CREDS = 0x10, SCH_CRED_AUTO_CRED_VALIDATION = 0x20, SCH_SEND_AUX_RECORD = 0x00200000, SCH_USE_STRONG_CRYPTO = 0x00400000, } } [StructLayout(LayoutKind.Sequential)] internal unsafe struct SecBuffer { public int cbBuffer; public SecurityBufferType BufferType; public IntPtr pvBuffer; public static readonly int Size = sizeof(SecBuffer); } [StructLayout(LayoutKind.Sequential)] internal unsafe struct SecBufferDesc { public readonly int ulVersion; public readonly int cBuffers; public void* pBuffers; public SecBufferDesc(int count) { ulVersion = 0; cBuffers = count; pBuffers = null; } } [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern int EncryptMessage( ref CredHandle contextHandle, [In] uint qualityOfProtection, [In, Out] ref SecBufferDesc inputOutput, [In] uint sequenceNumber ); [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern unsafe int DecryptMessage( [In] ref CredHandle contextHandle, [In, Out] ref SecBufferDesc inputOutput, [In] uint sequenceNumber, uint* qualityOfProtection ); [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern int QuerySecurityContextToken( ref CredHandle phContext, [Out] out SecurityContextTokenHandle handle); [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern int FreeContextBuffer( [In] IntPtr contextBuffer); [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern int FreeCredentialsHandle( ref CredHandle handlePtr ); [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern int DeleteSecurityContext( ref CredHandle handlePtr ); [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern unsafe int AcceptSecurityContext( ref CredHandle credentialHandle, [In] void* inContextPtr, [In] SecBufferDesc* inputBuffer, [In] ContextFlags inFlags, [In] Endianness endianness, ref CredHandle outContextPtr, [In, Out] ref SecBufferDesc outputBuffer, [In, Out] ref ContextFlags attributes, out long timeStamp ); [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern unsafe int QueryContextAttributesW( ref CredHandle contextHandle, [In] ContextAttribute attribute, [In] void* buffer); [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern unsafe int SetContextAttributesW( ref CredHandle contextHandle, [In] ContextAttribute attribute, [In] byte[] buffer, [In] int bufferSize); [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern int EnumerateSecurityPackagesW( [Out] out int pkgnum, [Out] out SafeFreeContextBuffer_SECURITY handle); [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern unsafe int AcquireCredentialsHandleW( [In] string principal, [In] string moduleName, [In] int usage, [In] void* logonID, [In] IntPtr zero, [In] void* keyCallback, [In] void* keyArgument, ref CredHandle handlePtr, [Out] out long timeStamp ); [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern unsafe int AcquireCredentialsHandleW( [In] string principal, [In] string moduleName, [In] int usage, [In] void* logonID, [In] SafeSspiAuthDataHandle authdata, [In] void* keyCallback, [In] void* keyArgument, ref CredHandle handlePtr, [Out] out long timeStamp ); [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern unsafe int AcquireCredentialsHandleW( [In] string principal, [In] string moduleName, [In] int usage, [In] void* logonID, [In] ref SCHANNEL_CRED authData, [In] void* keyCallback, [In] void* keyArgument, ref CredHandle handlePtr, [Out] out long timeStamp ); [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern unsafe int InitializeSecurityContextW( ref CredHandle credentialHandle, [In] void* inContextPtr, [In] byte* targetName, [In] ContextFlags inFlags, [In] int reservedI, [In] Endianness endianness, [In] SecBufferDesc* inputBuffer, [In] int reservedII, ref CredHandle outContextPtr, [In, Out] ref SecBufferDesc outputBuffer, [In, Out] ref ContextFlags attributes, out long timeStamp ); [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern unsafe int CompleteAuthToken( [In] void* inContextPtr, [In, Out] ref SecBufferDesc inputBuffers ); [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern unsafe int ApplyControlToken( [In] void* inContextPtr, [In, Out] ref SecBufferDesc inputBuffers ); [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern unsafe SECURITY_STATUS SspiFreeAuthIdentity( [In] IntPtr authData); [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern unsafe SECURITY_STATUS SspiEncodeStringsAsAuthIdentity( [In] string userName, [In] string domainName, [In] string password, [Out] out SafeSspiAuthDataHandle authData); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Tests; using System.Security.Principal; using Xunit; namespace System.Security.Claims { public class ClaimsPrincipalTests { [Fact] public void Ctor_Default() { var cp = new ClaimsPrincipal(); Assert.NotNull(cp.Identities); Assert.Equal(0, cp.Identities.Count()); Assert.NotNull(cp.Claims); Assert.Equal(0, cp.Claims.Count()); Assert.Null(cp.Identity); } [Fact] public void Ctor_IIdentity() { var id = new ClaimsIdentity( new List<Claim> { new Claim("claim_type", "claim_value") }, ""); var cp = new ClaimsPrincipal(id); Assert.NotNull(cp.Identities); Assert.Equal(1, cp.Identities.Count()); Assert.Same(id, cp.Identities.First()); Assert.Same(id, cp.Identity); Assert.NotNull(cp.Claims); Assert.Equal(1, cp.Claims.Count()); Assert.True(cp.Claims.Any(claim => claim.Type == "claim_type" && claim.Value == "claim_value")); } [Fact] public void Ctor_IIdentity_NonClaims() { var id = new NonClaimsIdentity() { Name = "NonClaimsIdentity_Name" }; var cp = new ClaimsPrincipal(id); Assert.NotNull(cp.Identities); Assert.Equal(1, cp.Identities.Count()); Assert.NotSame(id, cp.Identities.First()); Assert.NotSame(id, cp.Identity); Assert.Equal(id.Name, cp.Identity.Name); Assert.NotNull(cp.Claims); Assert.Equal(1, cp.Claims.Count()); Assert.True(cp.Claims.Any(claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "NonClaimsIdentity_Name")); } [Fact] public void Ctor_IPrincipal() { var baseId = new ClaimsIdentity( new List<Claim> { new Claim("claim_type", "claim_value") }, ""); var basePrincipal = new ClaimsPrincipal(); basePrincipal.AddIdentity(baseId); var cp = new ClaimsPrincipal(basePrincipal); Assert.NotNull(cp.Identities); Assert.Equal(1, cp.Identities.Count()); Assert.Same(baseId, cp.Identities.First()); Assert.Same(baseId, cp.Identity); Assert.NotNull(cp.Claims); Assert.Equal(1, cp.Claims.Count()); Assert.True(cp.Claims.Any(claim => claim.Type == "claim_type" && claim.Value == "claim_value"), "#7"); } [Fact] public void Ctor_NonClaimsIPrincipal_NonClaimsIdentity() { var id = new NonClaimsIdentity() { Name = "NonClaimsIdentity_Name" }; var basePrincipal = new NonClaimsPrincipal { Identity = id }; var cp = new ClaimsPrincipal(basePrincipal); Assert.NotNull(cp.Identities); Assert.Equal(1, cp.Identities.Count()); Assert.NotSame(id, cp.Identities.First()); Assert.NotSame(id, cp.Identity); Assert.Equal(id.Name, cp.Identity.Name); Assert.NotNull(cp.Claims); Assert.Equal(1, cp.Claims.Count()); Assert.True(cp.Claims.Any(claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "NonClaimsIdentity_Name")); } [Fact] public void Ctor_NonClaimsIPrincipal_NoIdentity() { var p = new ClaimsPrincipal(new NonClaimsPrincipal()); Assert.NotNull(p.Identities); Assert.Equal(1, p.Identities.Count()); Assert.NotNull(p.Claims); Assert.Equal(0, p.Claims.Count()); Assert.NotNull(p.Identity); Assert.False(p.Identity.IsAuthenticated); } [Fact] public void Ctor_IPrincipal_NoIdentity() { var cp = new ClaimsPrincipal(new ClaimsPrincipal()); Assert.NotNull(cp.Identities); Assert.Equal(0, cp.Identities.Count()); Assert.NotNull(cp.Claims); Assert.Equal(0, cp.Claims.Count()); Assert.Null(cp.Identity); } [Fact] public void Ctor_IPrincipal_MultipleIdentities() { var baseId1 = new ClaimsIdentity("baseId1"); var baseId2 = new GenericIdentity("generic_name", "baseId2"); var baseId3 = new ClaimsIdentity("customType"); var basePrincipal = new ClaimsPrincipal(baseId1); basePrincipal.AddIdentity(baseId2); basePrincipal.AddIdentity(baseId3); var cp = new ClaimsPrincipal(basePrincipal); Assert.NotNull(cp.Identities); Assert.Equal(3, cp.Identities.Count()); Assert.NotNull(cp.Claims); Assert.Equal(1, cp.Claims.Count()); Assert.Equal(baseId1, cp.Identity); Assert.True(cp.Claims.Any(claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "generic_name")); Assert.Equal(baseId2.Claims.First(), cp.Claims.First()); } [Fact] public void Ctor_IEnumerableClaimsIdentity_Empty() { var cp = new ClaimsPrincipal(new ClaimsIdentity[0]); Assert.NotNull(cp.Identities); Assert.Equal(0, cp.Identities.Count()); Assert.NotNull(cp.Claims); Assert.Equal(0, cp.Claims.Count()); Assert.Null(cp.Identity); } [Fact] public void Ctor_IEnumerableClaimsIdentity_Multiple() { var baseId1 = new ClaimsIdentity("baseId1"); var baseId2 = new GenericIdentity("generic_name2", "baseId2"); var baseId3 = new GenericIdentity("generic_name3", "baseId3"); var cp = new ClaimsPrincipal(new List<ClaimsIdentity> { baseId1, baseId2, baseId3 }); Assert.NotNull(cp.Identities); Assert.Equal(3, cp.Identities.Count()); Assert.NotNull(cp.Claims); Assert.Equal(2, cp.Claims.Count()); Assert.Equal(baseId1, cp.Identity); Assert.True(cp.Claims.Any(claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "generic_name2")); Assert.True(cp.Claims.Any(claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "generic_name3")); Assert.Equal(baseId2.Claims.First(), cp.Claims.First()); Assert.Equal(baseId3.Claims.Last(), cp.Claims.Last()); } [Fact] public void Ctor_ArgumentValidation() { Assert.Throws<ArgumentNullException>("identities", () => new ClaimsPrincipal((IEnumerable<ClaimsIdentity>)null)); Assert.Throws<ArgumentNullException>("identity", () => new ClaimsPrincipal((IIdentity)null)); Assert.Throws<ArgumentNullException>("principal", () => new ClaimsPrincipal((IPrincipal)null)); Assert.Throws<ArgumentNullException>("reader", () => new ClaimsPrincipal((BinaryReader)null)); } [Fact] public void ClaimPrincipal_SerializeDeserialize_Roundtrip() { Assert.NotNull(BinaryFormatterHelpers.Clone(new ClaimsPrincipal())); } private class NonClaimsPrincipal : IPrincipal { public IIdentity Identity { get; set; } public bool IsInRole(string role) { throw new NotImplementedException(); } } } }
using System; using System.Data; using Csla; using Csla.Data; namespace Codisa.InterwayDocs.Business { /// <summary> /// OutgoingInfo (read only object).<br/> /// This is a generated <see cref="OutgoingInfo"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="OutgoingBook"/> collection. /// </remarks> [Serializable] public partial class OutgoingInfo : ReadOnlyBase<OutgoingInfo> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="RegisterId"/> property. /// </summary> public static readonly PropertyInfo<int> RegisterIdProperty = RegisterProperty<int>(p => p.RegisterId, "Register Id"); /// <summary> /// Gets the Register Id. /// </summary> /// <value>The Register Id.</value> public int RegisterId { get { return GetProperty(RegisterIdProperty); } } /// <summary> /// Maintains metadata about <see cref="RegisterDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> RegisterDateProperty = RegisterProperty<SmartDate>(p => p.RegisterDate, "Register Date"); /// <summary> /// Gets the Register Date. /// </summary> /// <value>The Register Date.</value> public string RegisterDate { get { return GetPropertyConvert<SmartDate, string>(RegisterDateProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentType"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentTypeProperty = RegisterProperty<string>(p => p.DocumentType, "Document Type"); /// <summary> /// Gets the Document Type. /// </summary> /// <value>The Document Type.</value> public string DocumentType { get { return GetProperty(DocumentTypeProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentReference"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentReferenceProperty = RegisterProperty<string>(p => p.DocumentReference, "Document Reference"); /// <summary> /// Gets the Document Reference. /// </summary> /// <value>The Document Reference.</value> public string DocumentReference { get { return GetProperty(DocumentReferenceProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentEntity"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentEntityProperty = RegisterProperty<string>(p => p.DocumentEntity, "Document Entity"); /// <summary> /// Gets the Document Entity. /// </summary> /// <value>The Document Entity.</value> public string DocumentEntity { get { return GetProperty(DocumentEntityProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentDept"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentDeptProperty = RegisterProperty<string>(p => p.DocumentDept, "Document Dept"); /// <summary> /// Gets the Document Dept. /// </summary> /// <value>The Document Dept.</value> public string DocumentDept { get { return GetProperty(DocumentDeptProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentClass"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentClassProperty = RegisterProperty<string>(p => p.DocumentClass, "Document Class"); /// <summary> /// Gets the Document Class. /// </summary> /// <value>The Document Class.</value> public string DocumentClass { get { return GetProperty(DocumentClassProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> DocumentDateProperty = RegisterProperty<SmartDate>(p => p.DocumentDate, "Document Date"); /// <summary> /// Gets the Document Date. /// </summary> /// <value>The Document Date.</value> public string DocumentDate { get { return GetPropertyConvert<SmartDate, string>(DocumentDateProperty); } } /// <summary> /// Maintains metadata about <see cref="Subject"/> property. /// </summary> public static readonly PropertyInfo<string> SubjectProperty = RegisterProperty<string>(p => p.Subject, "Subject"); /// <summary> /// Gets the Subject. /// </summary> /// <value>The Subject.</value> public string Subject { get { return GetProperty(SubjectProperty); } } /// <summary> /// Maintains metadata about <see cref="SendDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> SendDateProperty = RegisterProperty<SmartDate>(p => p.SendDate, "Send Date"); /// <summary> /// Gets the Send Date. /// </summary> /// <value>The Send Date.</value> public string SendDate { get { return GetPropertyConvert<SmartDate, string>(SendDateProperty); } } /// <summary> /// Maintains metadata about <see cref="RecipientName"/> property. /// </summary> public static readonly PropertyInfo<string> RecipientNameProperty = RegisterProperty<string>(p => p.RecipientName, "Recipient Name"); /// <summary> /// Gets the Recipient Name. /// </summary> /// <value>The Recipient Name.</value> public string RecipientName { get { return GetProperty(RecipientNameProperty); } } /// <summary> /// Maintains metadata about <see cref="RecipientTown"/> property. /// </summary> public static readonly PropertyInfo<string> RecipientTownProperty = RegisterProperty<string>(p => p.RecipientTown, "Recipient Town"); /// <summary> /// Gets the Recipient Town. /// </summary> /// <value>The Recipient Town.</value> public string RecipientTown { get { return GetProperty(RecipientTownProperty); } } /// <summary> /// Maintains metadata about <see cref="Notes"/> property. /// </summary> public static readonly PropertyInfo<string> NotesProperty = RegisterProperty<string>(p => p.Notes, "Notes"); /// <summary> /// Gets the Notes. /// </summary> /// <value>The Notes.</value> public string Notes { get { return GetProperty(NotesProperty); } } /// <summary> /// Maintains metadata about <see cref="ArchiveLocation"/> property. /// </summary> public static readonly PropertyInfo<string> ArchiveLocationProperty = RegisterProperty<string>(p => p.ArchiveLocation, "Archive Location"); /// <summary> /// Gets the Archive Location. /// </summary> /// <value>The Archive Location.</value> public string ArchiveLocation { get { return GetProperty(ArchiveLocationProperty); } } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="OutgoingInfo"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="OutgoingInfo"/> object.</returns> internal static OutgoingInfo GetOutgoingInfo(SafeDataReader dr) { OutgoingInfo obj = new OutgoingInfo(); obj.Fetch(dr); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="OutgoingInfo"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public OutgoingInfo() { // Use factory methods and do not use direct creation. } #endregion #region Data Access /// <summary> /// Loads a <see cref="OutgoingInfo"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(RegisterIdProperty, dr.GetInt32("RegisterId")); LoadProperty(RegisterDateProperty, dr.GetSmartDate("RegisterDate", true)); LoadProperty(DocumentTypeProperty, dr.GetString("DocumentType")); LoadProperty(DocumentReferenceProperty, dr.GetString("DocumentReference")); LoadProperty(DocumentEntityProperty, dr.GetString("DocumentEntity")); LoadProperty(DocumentDeptProperty, dr.GetString("DocumentDept")); LoadProperty(DocumentClassProperty, dr.GetString("DocumentClass")); LoadProperty(DocumentDateProperty, dr.GetSmartDate("DocumentDate", true)); LoadProperty(SubjectProperty, dr.GetString("Subject")); LoadProperty(SendDateProperty, dr.GetSmartDate("SendDate", true)); LoadProperty(RecipientNameProperty, dr.GetString("RecipientName")); LoadProperty(RecipientTownProperty, dr.GetString("RecipientTown")); LoadProperty(NotesProperty, dr.GetString("Notes")); LoadProperty(ArchiveLocationProperty, dr.GetString("ArchiveLocation")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } #endregion #region DataPortal Hooks /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Automation { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ScheduleOperations operations. /// </summary> internal partial class ScheduleOperations : IServiceOperations<AutomationClient>, IScheduleOperations { /// <summary> /// Initializes a new instance of the ScheduleOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ScheduleOperations(AutomationClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AutomationClient /// </summary> public AutomationClient Client { get; private set; } /// <summary> /// Create a schedule. /// <see href="http://aka.ms/azureautomationsdk/scheduleoperations" /> /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='scheduleName'> /// The schedule name. /// </param> /// <param name='parameters'> /// The parameters supplied to the create or update schedule operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Schedule>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, string scheduleName, ScheduleCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (automationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName"); } if (scheduleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "scheduleName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2015-10-31"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccountName", automationAccountName); tracingParameters.Add("scheduleName", scheduleName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/schedules/{scheduleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName)); _url = _url.Replace("{scheduleName}", System.Uri.EscapeDataString(scheduleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201 && (int)_statusCode != 409) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Schedule>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Schedule>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Update the schedule identified by schedule name. /// <see href="http://aka.ms/azureautomationsdk/scheduleoperations" /> /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='scheduleName'> /// The schedule name. /// </param> /// <param name='parameters'> /// The parameters supplied to the update schedule operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Schedule>> UpdateWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, string scheduleName, ScheduleUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (automationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName"); } if (scheduleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "scheduleName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2015-10-31"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccountName", automationAccountName); tracingParameters.Add("scheduleName", scheduleName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/schedules/{scheduleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName)); _url = _url.Replace("{scheduleName}", System.Uri.EscapeDataString(scheduleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Schedule>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Schedule>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Retrieve the schedule identified by schedule name. /// <see href="http://aka.ms/azureautomationsdk/scheduleoperations" /> /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='scheduleName'> /// The schedule name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Schedule>> GetWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, string scheduleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (automationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName"); } if (scheduleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "scheduleName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2015-10-31"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccountName", automationAccountName); tracingParameters.Add("scheduleName", scheduleName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/schedules/{scheduleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName)); _url = _url.Replace("{scheduleName}", System.Uri.EscapeDataString(scheduleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Schedule>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Schedule>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Delete the schedule identified by schedule name. /// <see href="http://aka.ms/azureautomationsdk/scheduleoperations" /> /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='scheduleName'> /// The schedule name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, string scheduleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (automationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName"); } if (scheduleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "scheduleName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2015-10-31"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccountName", automationAccountName); tracingParameters.Add("scheduleName", scheduleName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/schedules/{scheduleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName)); _url = _url.Replace("{scheduleName}", System.Uri.EscapeDataString(scheduleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 404) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Retrieve a list of schedules. /// <see href="http://aka.ms/azureautomationsdk/scheduleoperations" /> /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Schedule>>> ListByAutomationAccountWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (automationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2015-10-31"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccountName", automationAccountName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByAutomationAccount", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/schedules").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Schedule>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Schedule>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Retrieve a list of schedules. /// <see href="http://aka.ms/azureautomationsdk/scheduleoperations" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Schedule>>> ListByAutomationAccountNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByAutomationAccountNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Schedule>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Schedule>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. // See THIRD-PARTY-NOTICES.TXT in the project root for license information. using System.Diagnostics; namespace System.Net.Http.HPack { internal class HPackDecoder { // Can't use Action<,> because of Span public delegate void HeaderCallback(object state, ReadOnlySpan<byte> headerName, ReadOnlySpan<byte> headerValue); private enum State { Ready, HeaderFieldIndex, HeaderNameIndex, HeaderNameLength, HeaderNameLengthContinue, HeaderName, HeaderValueLength, HeaderValueLengthContinue, HeaderValue, DynamicTableSizeUpdate } public const int DefaultHeaderTableSize = 4096; public const int DefaultStringOctetsSize = 4096; public const int DefaultMaxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength * 1024; // http://httpwg.org/specs/rfc7541.html#rfc.section.6.1 // 0 1 2 3 4 5 6 7 // +---+---+---+---+---+---+---+---+ // | 1 | Index (7+) | // +---+---------------------------+ private const byte IndexedHeaderFieldMask = 0x80; private const byte IndexedHeaderFieldRepresentation = 0x80; // http://httpwg.org/specs/rfc7541.html#rfc.section.6.2.1 // 0 1 2 3 4 5 6 7 // +---+---+---+---+---+---+---+---+ // | 0 | 1 | Index (6+) | // +---+---+-----------------------+ private const byte LiteralHeaderFieldWithIncrementalIndexingMask = 0xc0; private const byte LiteralHeaderFieldWithIncrementalIndexingRepresentation = 0x40; // http://httpwg.org/specs/rfc7541.html#rfc.section.6.2.2 // 0 1 2 3 4 5 6 7 // +---+---+---+---+---+---+---+---+ // | 0 | 0 | 0 | 0 | Index (4+) | // +---+---+-----------------------+ private const byte LiteralHeaderFieldWithoutIndexingMask = 0xf0; private const byte LiteralHeaderFieldWithoutIndexingRepresentation = 0x00; // http://httpwg.org/specs/rfc7541.html#rfc.section.6.2.3 // 0 1 2 3 4 5 6 7 // +---+---+---+---+---+---+---+---+ // | 0 | 0 | 0 | 1 | Index (4+) | // +---+---+-----------------------+ private const byte LiteralHeaderFieldNeverIndexedMask = 0xf0; private const byte LiteralHeaderFieldNeverIndexedRepresentation = 0x10; // http://httpwg.org/specs/rfc7541.html#rfc.section.6.3 // 0 1 2 3 4 5 6 7 // +---+---+---+---+---+---+---+---+ // | 0 | 0 | 1 | Max size (5+) | // +---+---------------------------+ private const byte DynamicTableSizeUpdateMask = 0xe0; private const byte DynamicTableSizeUpdateRepresentation = 0x20; // http://httpwg.org/specs/rfc7541.html#rfc.section.5.2 // 0 1 2 3 4 5 6 7 // +---+---+---+---+---+---+---+---+ // | H | String Length (7+) | // +---+---------------------------+ private const byte HuffmanMask = 0x80; private const int IndexedHeaderFieldPrefix = 7; private const int LiteralHeaderFieldWithIncrementalIndexingPrefix = 6; private const int LiteralHeaderFieldWithoutIndexingPrefix = 4; private const int LiteralHeaderFieldNeverIndexedPrefix = 4; private const int DynamicTableSizeUpdatePrefix = 5; private const int StringLengthPrefix = 7; private readonly int _maxDynamicTableSize; private readonly int _maxResponseHeadersLength; private readonly DynamicTable _dynamicTable; private readonly IntegerDecoder _integerDecoder = new IntegerDecoder(); private byte[] _stringOctets = new byte[DefaultStringOctetsSize]; private byte[] _headerNameOctets = new byte[DefaultStringOctetsSize]; private byte[] _headerValueOctets = new byte[DefaultStringOctetsSize]; private State _state = State.Ready; private byte[] _headerName; private int _stringIndex; private int _stringLength; private int _headerNameLength; private int _headerValueLength; private bool _index; private bool _huffman; private bool _headersObserved; public HPackDecoder(int maxDynamicTableSize = DefaultHeaderTableSize, int maxResponseHeadersLength = DefaultMaxResponseHeadersLength) : this(maxDynamicTableSize, maxResponseHeadersLength, new DynamicTable(maxDynamicTableSize)) { } // For testing. internal HPackDecoder(int maxDynamicTableSize, int maxResponseHeadersLength, DynamicTable dynamicTable) { _maxDynamicTableSize = maxDynamicTableSize; _maxResponseHeadersLength = maxResponseHeadersLength; _dynamicTable = dynamicTable; } public void Decode(ReadOnlySpan<byte> data, bool endHeaders, HeaderCallback onHeader, object onHeaderState) { for (int i = 0; i < data.Length; i++) { byte b = data[i]; switch (_state) { case State.Ready: // TODO: Instead of masking and comparing each prefix value, // consider doing a 16-way switch on the first four bits (which is the max prefix size). // Look at this once we have more concrete perf data. if ((b & IndexedHeaderFieldMask) == IndexedHeaderFieldRepresentation) { _headersObserved = true; int val = b & ~IndexedHeaderFieldMask; if (_integerDecoder.StartDecode((byte)val, IndexedHeaderFieldPrefix)) { OnIndexedHeaderField(_integerDecoder.Value, onHeader, onHeaderState); } else { _state = State.HeaderFieldIndex; } } else if ((b & LiteralHeaderFieldWithIncrementalIndexingMask) == LiteralHeaderFieldWithIncrementalIndexingRepresentation) { _headersObserved = true; _index = true; int val = b & ~LiteralHeaderFieldWithIncrementalIndexingMask; if (val == 0) { _state = State.HeaderNameLength; } else if (_integerDecoder.StartDecode((byte)val, LiteralHeaderFieldWithIncrementalIndexingPrefix)) { OnIndexedHeaderName(_integerDecoder.Value); } else { _state = State.HeaderNameIndex; } } else if ((b & LiteralHeaderFieldWithoutIndexingMask) == LiteralHeaderFieldWithoutIndexingRepresentation) { _headersObserved = true; _index = false; int val = b & ~LiteralHeaderFieldWithoutIndexingMask; if (val == 0) { _state = State.HeaderNameLength; } else if (_integerDecoder.StartDecode((byte)val, LiteralHeaderFieldWithoutIndexingPrefix)) { OnIndexedHeaderName(_integerDecoder.Value); } else { _state = State.HeaderNameIndex; } } else if ((b & LiteralHeaderFieldNeverIndexedMask) == LiteralHeaderFieldNeverIndexedRepresentation) { _headersObserved = true; _index = false; int val = b & ~LiteralHeaderFieldNeverIndexedMask; if (val == 0) { _state = State.HeaderNameLength; } else if (_integerDecoder.StartDecode((byte)val, LiteralHeaderFieldNeverIndexedPrefix)) { OnIndexedHeaderName(_integerDecoder.Value); } else { _state = State.HeaderNameIndex; } } else if ((b & DynamicTableSizeUpdateMask) == DynamicTableSizeUpdateRepresentation) { // https://tools.ietf.org/html/rfc7541#section-4.2 // This dynamic table size // update MUST occur at the beginning of the first header block // following the change to the dynamic table size. if (_headersObserved) { throw new HPackDecodingException(SR.net_http_hpack_late_dynamic_table_size_update); } if (_integerDecoder.StartDecode((byte)(b & ~DynamicTableSizeUpdateMask), DynamicTableSizeUpdatePrefix)) { // TODO: validate that it's less than what's defined via SETTINGS _dynamicTable.Resize(_integerDecoder.Value); } else { _state = State.DynamicTableSizeUpdate; } } else { // Can't happen Debug.Fail("Unreachable code"); throw new InternalException(); } break; case State.HeaderFieldIndex: if (_integerDecoder.Decode(b)) { OnIndexedHeaderField(_integerDecoder.Value, onHeader, onHeaderState); } break; case State.HeaderNameIndex: if (_integerDecoder.Decode(b)) { OnIndexedHeaderName(_integerDecoder.Value); } break; case State.HeaderNameLength: _huffman = (b & HuffmanMask) != 0; if (_integerDecoder.StartDecode((byte)(b & ~HuffmanMask), StringLengthPrefix)) { if (_integerDecoder.Value == 0) { throw new HPackDecodingException(SR.Format(SR.net_http_invalid_response_header_name, "")); } OnStringLength(_integerDecoder.Value, nextState: State.HeaderName); } else { _state = State.HeaderNameLengthContinue; } break; case State.HeaderNameLengthContinue: if (_integerDecoder.Decode(b)) { OnStringLength(_integerDecoder.Value, nextState: State.HeaderName); } break; case State.HeaderName: _stringOctets[_stringIndex++] = b; if (_stringIndex == _stringLength) { OnString(nextState: State.HeaderValueLength); } break; case State.HeaderValueLength: _huffman = (b & HuffmanMask) != 0; if (_integerDecoder.StartDecode((byte)(b & ~HuffmanMask), StringLengthPrefix)) { if (_integerDecoder.Value > 0) { OnStringLength(_integerDecoder.Value, nextState: State.HeaderValue); } else { OnStringLength(_integerDecoder.Value, nextState: State.Ready); OnHeaderComplete(onHeader, onHeaderState, new ReadOnlySpan<byte>(_headerName, 0, _headerNameLength), new ReadOnlySpan<byte>()); } } else { _state = State.HeaderValueLengthContinue; } break; case State.HeaderValueLengthContinue: if (_integerDecoder.Decode(b)) { OnStringLength(_integerDecoder.Value, nextState: State.HeaderValue); } break; case State.HeaderValue: _stringOctets[_stringIndex++] = b; if (_stringIndex == _stringLength) { OnString(nextState: State.Ready); var headerNameSpan = new ReadOnlySpan<byte>(_headerName, 0, _headerNameLength); var headerValueSpan = new ReadOnlySpan<byte>(_headerValueOctets, 0, _headerValueLength); OnHeaderComplete(onHeader, onHeaderState, headerNameSpan, headerValueSpan); } break; case State.DynamicTableSizeUpdate: if (_integerDecoder.Decode(b)) { if (_integerDecoder.Value > _maxDynamicTableSize) { // Dynamic table size update is too large. throw new HPackDecodingException(); } _dynamicTable.Resize(_integerDecoder.Value); _state = State.Ready; } break; default: // Can't happen Debug.Fail("HPACK decoder reach an invalid state"); throw new InternalException(_state); } } if (endHeaders) { if (_state != State.Ready) { throw new HPackDecodingException(SR.net_http_hpack_incomplete_header_block); } _headersObserved = false; } } public void CompleteDecode() { if (_state != State.Ready) { // Incomplete header block throw new HPackDecodingException(); } } private void OnIndexedHeaderField(int index, HeaderCallback onHeader, object onHeaderState) { HeaderField header = GetHeader(index); onHeader(onHeaderState, new ReadOnlySpan<byte>(header.Name), new ReadOnlySpan<byte>(header.Value)); _state = State.Ready; } private void OnIndexedHeaderName(int index) { HeaderField header = GetHeader(index); _headerName = header.Name; _headerNameLength = header.Name.Length; _state = State.HeaderValueLength; } private void OnStringLength(int length, State nextState) { if (length > _stringOctets.Length) { if (length > _maxResponseHeadersLength) { throw new HPackDecodingException(SR.Format(SR.net_http_response_headers_exceeded_length, _maxResponseHeadersLength)); } _stringOctets = new byte[Math.Max(length, _stringOctets.Length * 2)]; } _stringLength = length; _stringIndex = 0; _state = nextState; } private void OnString(State nextState) { int Decode(ref byte[] dst) { if (_huffman) { return Huffman.Decode(new ReadOnlySpan<byte>(_stringOctets, 0, _stringLength), ref dst); } else { if (dst.Length < _stringLength) { dst = new byte[Math.Max(_stringLength, dst.Length * 2)]; } Buffer.BlockCopy(_stringOctets, 0, dst, 0, _stringLength); return _stringLength; } } try { if (_state == State.HeaderName) { _headerNameLength = Decode(ref _headerNameOctets); _headerName = _headerNameOctets; } else { _headerValueLength = Decode(ref _headerValueOctets); } } catch (HuffmanDecodingException ex) { // Error in huffman encoding. throw new HPackDecodingException(SR.net_http_hpack_huffman_decode_failed, ex); } _state = nextState; } // Called when we have complete header with name and value. private void OnHeaderComplete(HeaderCallback onHeader, object onHeaderState, ReadOnlySpan<byte> headerName, ReadOnlySpan<byte> headerValue) { // Call provided callback. onHeader(onHeaderState, headerName, headerValue); if (_index) { _dynamicTable.Insert(headerName, headerValue); } } private HeaderField GetHeader(int index) { try { return index <= StaticTable.Count ? StaticTable.Get(index - 1) : _dynamicTable[index - StaticTable.Count - 1]; } catch (IndexOutOfRangeException) { // Header index out of range. throw new HPackDecodingException(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Xml; using Microsoft.Build.Construction; using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException; using Xunit; namespace Microsoft.Build.UnitTests.OM.Construction { /// <summary> // <summary>Tests for the ProjectExtensionsElement class.</summary> /// Tests for the class /// </summary> public class ProjectExtensionsElement_Tests { /// <summary> /// Read ProjectExtensions with some child /// </summary> [Fact] public void Read() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ProjectExtensions> <a/> </ProjectExtensions> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectExtensionsElement extensions = (ProjectExtensionsElement)Helpers.GetFirst(project.Children); Assert.Equal(@"<a xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" />", extensions.Content); } /// <summary> /// Read ProjectExtensions with invalid Condition attribute /// </summary> [Fact] public void ReadInvalidCondition() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ProjectExtensions Condition='c'/> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Read project with more than one ProjectExtensions /// </summary> [Fact] public void ReadInvalidDuplicate() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ProjectExtensions/> <Target Name='t'/> <ProjectExtensions /> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Set valid content /// </summary> [Fact] public void SetValid() { ProjectExtensionsElement extensions = GetEmptyProjectExtensions(); Helpers.ClearDirtyFlag(extensions.ContainingProject); extensions.Content = "a<b/>c"; Assert.Equal(@"a<b xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" />c", extensions.Content); Assert.True(extensions.ContainingProject.HasUnsavedChanges); } /// <summary> /// Set null content /// </summary> [Fact] public void SetInvalidNull() { Assert.Throws<ArgumentNullException>(() => { ProjectExtensionsElement extensions = GetEmptyProjectExtensions(); extensions.Content = null; } ); } /// <summary> /// Delete by ID /// </summary> [Fact] public void DeleteById() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ProjectExtensions> <a>x</a> <b>y</b> </ProjectExtensions> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectExtensionsElement extensions = (ProjectExtensionsElement)Helpers.GetFirst(project.Children); extensions["a"] = String.Empty; content = extensions["a"]; Assert.Equal(String.Empty, content); extensions["a"] = String.Empty; // make sure it doesn't die or something Assert.Equal("y", extensions["b"]); } /// <summary> /// Get by ID /// </summary> [Fact] public void GetById() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ProjectExtensions> <a>x</a> <b>y</b> </ProjectExtensions> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectExtensionsElement extensions = (ProjectExtensionsElement)Helpers.GetFirst(project.Children); content = extensions["b"]; Assert.Equal("y", content); content = extensions["nonexistent"]; Assert.Equal(String.Empty, content); } /// <summary> /// Set by ID on not existing ID /// </summary> [Fact] public void SetById() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ProjectExtensions> <a>x</a> <b>y</b> </ProjectExtensions> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectExtensionsElement extensions = (ProjectExtensionsElement)Helpers.GetFirst(project.Children); extensions["c"] = "z"; Assert.Equal("z", extensions["c"]); } /// <summary> /// Set by ID on existing ID /// </summary> [Fact] public void SetByIdWhereItAlreadyExists() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ProjectExtensions> <a>x</a> <b>y</b> </ProjectExtensions> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectExtensionsElement extensions = (ProjectExtensionsElement)Helpers.GetFirst(project.Children); extensions["b"] = "y2"; Assert.Equal("y2", extensions["b"]); } /// <summary> /// Helper to get an empty ProjectExtensionsElement object /// </summary> private static ProjectExtensionsElement GetEmptyProjectExtensions() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ProjectExtensions/> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectExtensionsElement extensions = (ProjectExtensionsElement)Helpers.GetFirst(project.Children); return extensions; } } }
/* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace ZXing.Common { /// <summary> This Binarizer implementation uses the old ZXing global histogram approach. It is suitable /// for low-end mobile devices which don't have enough CPU or memory to use a local thresholding /// algorithm. However, because it picks a global black point, it cannot handle difficult shadows /// and gradients. /// /// Faster mobile devices and all desktop applications should probably use HybridBinarizer instead. /// /// <author>[email protected] (Daniel Switkin)</author> /// <author>Sean Owen</author> /// </summary> public class GlobalHistogramBinarizer : Binarizer { private const int LUMINANCE_BITS = 5; private const int LUMINANCE_SHIFT = 8 - LUMINANCE_BITS; private const int LUMINANCE_BUCKETS = 1 << LUMINANCE_BITS; private static readonly byte[] EMPTY = new byte[0]; private byte[] luminances; private readonly int[] buckets; /// <summary> /// Initializes a new instance of the <see cref="GlobalHistogramBinarizer"/> class. /// </summary> /// <param name="source">The source.</param> public GlobalHistogramBinarizer(LuminanceSource source) : base(source) { luminances = EMPTY; buckets = new int[LUMINANCE_BUCKETS]; } /// <summary> /// Applies simple sharpening to the row data to improve performance of the 1D Readers. /// </summary> /// <param name="y"></param> /// <param name="row"></param> /// <returns></returns> public override BitArray getBlackRow(int y, BitArray row) { LuminanceSource source = LuminanceSource; int width = source.Width; if (row == null || row.Size < width) { row = new BitArray(width); } else { row.clear(); } initArrays(width); byte[] localLuminances = source.getRow(y, luminances); int[] localBuckets = buckets; for (int x = 0; x < width; x++) { localBuckets[(localLuminances[x] & 0xff) >> LUMINANCE_SHIFT]++; } int blackPoint; if (!estimateBlackPoint(localBuckets, out blackPoint)) return null; if (width < 3) { // Special case for very small images for (int x = 0; x < width; x++) { if ((localLuminances[x] & 0xff) < blackPoint) { row[x] = true; } } } else { int left = localLuminances[0] & 0xff; int center = localLuminances[1] & 0xff; for (int x = 1; x < width - 1; x++) { int right = localLuminances[x + 1] & 0xff; // A simple -1 4 -1 box filter with a weight of 2. // ((center << 2) - left - right) >> 1 if (((center * 4) - left - right) / 2 < blackPoint) { row[x] = true; } left = center; center = right; } } return row; } /// <summary> /// Does not sharpen the data, as this call is intended to only be used by 2D Readers. /// </summary> public override BitMatrix BlackMatrix { get { LuminanceSource source = LuminanceSource; byte[] localLuminances; int width = source.Width; int height = source.Height; BitMatrix matrix = new BitMatrix(width, height); // Quickly calculates the histogram by sampling four rows from the image. This proved to be // more robust on the blackbox tests than sampling a diagonal as we used to do. initArrays(width); int[] localBuckets = buckets; for (int y = 1; y < 5; y++) { int row = height * y / 5; localLuminances = source.getRow(row, luminances); int right = (width << 2) / 5; for (int x = width / 5; x < right; x++) { int pixel = localLuminances[x] & 0xff; localBuckets[pixel >> LUMINANCE_SHIFT]++; } } int blackPoint; if (!estimateBlackPoint(localBuckets, out blackPoint)) return null; // We delay reading the entire image luminance until the black point estimation succeeds. // Although we end up reading four rows twice, it is consistent with our motto of // "fail quickly" which is necessary for continuous scanning. localLuminances = source.Matrix; for (int y = 0; y < height; y++) { int offset = y * width; for (int x = 0; x < width; x++) { int pixel = localLuminances[offset + x] & 0xff; matrix[x, y] = (pixel < blackPoint); } } return matrix; } } /// <summary> /// Creates a new object with the same type as this Binarizer implementation, but with pristine /// state. This is needed because Binarizer implementations may be stateful, e.g. keeping a cache /// of 1 bit data. See Effective Java for why we can't use Java's clone() method. /// </summary> /// <param name="source">The LuminanceSource this Binarizer will operate on.</param> /// <returns> /// A new concrete Binarizer implementation object. /// </returns> public override Binarizer createBinarizer(LuminanceSource source) { return new GlobalHistogramBinarizer(source); } private void initArrays(int luminanceSize) { if (luminances.Length < luminanceSize) { luminances = new byte[luminanceSize]; } for (int x = 0; x < LUMINANCE_BUCKETS; x++) { buckets[x] = 0; } } private static bool estimateBlackPoint(int[] buckets, out int blackPoint) { blackPoint = 0; // Find the tallest peak in the histogram. int numBuckets = buckets.Length; int maxBucketCount = 0; int firstPeak = 0; int firstPeakSize = 0; for (int x = 0; x < numBuckets; x++) { if (buckets[x] > firstPeakSize) { firstPeak = x; firstPeakSize = buckets[x]; } if (buckets[x] > maxBucketCount) { maxBucketCount = buckets[x]; } } // Find the second-tallest peak which is somewhat far from the tallest peak. int secondPeak = 0; int secondPeakScore = 0; for (int x = 0; x < numBuckets; x++) { int distanceToBiggest = x - firstPeak; // Encourage more distant second peaks by multiplying by square of distance. int score = buckets[x] * distanceToBiggest * distanceToBiggest; if (score > secondPeakScore) { secondPeak = x; secondPeakScore = score; } } // Make sure firstPeak corresponds to the black peak. if (firstPeak > secondPeak) { int temp = firstPeak; firstPeak = secondPeak; secondPeak = temp; } // If there is too little contrast in the image to pick a meaningful black point, throw rather // than waste time trying to decode the image, and risk false positives. // TODO: It might be worth comparing the brightest and darkest pixels seen, rather than the // two peaks, to determine the contrast. if (secondPeak - firstPeak <= numBuckets >> 4) { return false; } // Find a valley between them that is low and closer to the white peak. int bestValley = secondPeak - 1; int bestValleyScore = -1; for (int x = secondPeak - 1; x > firstPeak; x--) { int fromFirst = x - firstPeak; int score = fromFirst*fromFirst*(secondPeak - x)*(maxBucketCount - buckets[x]); if (score > bestValleyScore) { bestValley = x; bestValleyScore = score; } } blackPoint = bestValley << LUMINANCE_SHIFT; return true; } } }
/* Copyright (c) 2003-2008 Niels Kokholm and Peter Sestoft 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. */ // C5 example: EventPatterns.cs for pattern chapter // Compile with // csc /r:C5.dll EventPatterns.cs using System; using C5; namespace EventPatterns { class EventPatterns { public static void Main(String[] args) { UnindexedCollectionEvents(); Console.WriteLine("--------------------"); IndexedCollectionEvents(); Console.WriteLine("--------------------"); UpdateEvent(); } public static void UnindexedCollectionEvents() { ICollection<int> coll = new ArrayList<int>(); ICollection<int> bag1 = new HashBag<int>(); bag1.AddAll(new[] { 3, 2, 5, 5, 7, 7, 5, 3, 7, 7 }); // Add change handler coll.CollectionChanged += delegate(Object c) { Console.WriteLine("Collection changed"); }; // Add cleared handler coll.CollectionCleared += delegate(Object c, ClearedEventArgs args) { Console.WriteLine("Collection cleared"); }; // Add added handler coll.ItemsAdded += delegate(Object c, ItemCountEventArgs<int> args) { Console.WriteLine("Item {0} added", args.Item); }; // Add item count handler AddItemsAddedCounter(coll); AddItemsRemovedCounter(coll); coll.AddAll(bag1); coll.RemoveAll(new[] { 2, 5, 6, 3, 7, 2 }); coll.Clear(); ICollection<int> bag2 = new HashBag<int>(); // Add added handler with multiplicity bag2.ItemsAdded += delegate(Object c, ItemCountEventArgs<int> args) { Console.WriteLine("{0} copies of {1} added", args.Count, args.Item); }; bag2.AddAll(bag1); // Add removed handler with multiplicity bag2.ItemsRemoved += delegate(Object c, ItemCountEventArgs<int> args) { Console.WriteLine("{0} copies of {1} removed", args.Count, args.Item); }; bag2.RemoveAllCopies(7); } // This works for all kinds of collections, also those with bag // semantics and representing duplicates by counting: private static void AddItemsAddedCounter<T>(ICollection<T> coll) { int addedCount = 0; coll.ItemsAdded += delegate(Object c, ItemCountEventArgs<T> args) { addedCount += args.Count; }; coll.CollectionChanged += delegate(Object c) { if (addedCount > 0) Console.WriteLine("{0} items were added", addedCount); addedCount = 0; }; } // This works for all kinds of collections, also those with bag // semantics and representing duplicates by counting: private static void AddItemsRemovedCounter<T>(ICollection<T> coll) { int removedCount = 0; coll.ItemsRemoved += delegate(Object c, ItemCountEventArgs<T> args) { removedCount += args.Count; }; coll.CollectionChanged += delegate(Object c) { if (removedCount > 0) Console.WriteLine("{0} items were removed", removedCount); removedCount = 0; }; } // Event patterns on indexed collections public static void IndexedCollectionEvents() { IList<int> coll = new ArrayList<int>(); ICollection<int> bag = new HashBag<int>(); bag.AddAll(new[] { 3, 2, 5, 5, 7, 7, 5, 3, 7, 7 }); // Add item inserted handler coll.ItemInserted += delegate(Object c, ItemAtEventArgs<int> args) { Console.WriteLine("Item {0} inserted at {1}", args.Item, args.Index); }; coll.InsertAll(0, bag); // Add item removed-at handler coll.ItemRemovedAt += delegate(Object c, ItemAtEventArgs<int> args) { Console.WriteLine("Item {0} removed at {1}", args.Item, args.Index); }; coll.RemoveLast(); coll.RemoveFirst(); coll.RemoveAt(1); } // Recognizing Update event as a Removed-Added-Changed sequence private enum State { Before, Removed, Updated }; private static void AddItemUpdatedHandler<T>(ICollection<T> coll) { State state = State.Before; T removed = default(T), added = default(T); coll.ItemsRemoved += delegate(Object c, ItemCountEventArgs<T> args) { if (state == State.Before) { state = State.Removed; removed = args.Item; } else state = State.Before; }; coll.ItemsAdded += delegate(Object c, ItemCountEventArgs<T> args) { if (state == State.Removed) { state = State.Updated; added = args.Item; } else state = State.Before; }; coll.CollectionChanged += delegate(Object c) { if (state == State.Updated) Console.WriteLine("Item {0} was updated to {1}", removed, added); state = State.Before; }; } public static void UpdateEvent() { ICollection<Teacher> coll = new HashSet<Teacher>(); AddItemUpdatedHandler(coll); Teacher kristian = new Teacher("Kristian", "physics"); coll.Add(kristian); coll.Add(new Teacher("Poul Einer", "mathematics")); // This should be caught by the update handler: coll.Update(new Teacher("Thomas", "mathematics")); // This should not be caught by the update handler: coll.Remove(kristian); coll.Add(new Teacher("Jens", "physics")); // The update handler is activated also by indexed updates IList<int> list = new ArrayList<int>(); list.AddAll(new[] { 7, 11, 13 }); AddItemUpdatedHandler(list); list[1] = 9; } } // Example class where objects may be equal yet display differently class Teacher : IEquatable<Teacher> { private readonly String name, subject; public Teacher(String name, String subject) { this.name = name; this.subject = subject; } public bool Equals(Teacher that) { return this.subject.Equals(that.subject); } public override int GetHashCode() { return subject.GetHashCode(); } public override String ToString() { return name + "[" + subject + "]"; } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using DataBinding; using SDKTemplate; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using Windows.ApplicationModel.Activation; using Windows.Media.Import; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using System.ComponentModel; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace ImportSample { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class Scenario1 : Page , INotifyPropertyChanged { private MainPage rootPage; private PhotoImportSession session; private PhotoImportSource importSource; private PhotoImportFindItemsResult itemsResult; private PhotoImportImportItemsResult importedResult; private PhotoImportDeleteImportedItemsFromSourceResult deleteResult; private CancellationTokenSource cts; private DeviceActivatedEventArgs arguments; private PhotoImportContentTypeFilter contentTypeFilder; // GeneratorIncrementalLoadingClass taken from MSDN example https://code.msdn.microsoft.com/windowsapps/Data-Binding-7b1d67b5 // Used to incrementally load items in the Listview view including thumbnails GeneratorIncrementalLoadingClass<ImportableItemWrapper> itemsToImport = null; public Scenario1() { this.InitializeComponent(); this.DataContext = this; } public bool AppendSessionDateToDestinationFolder { get { if (session != null) { return session.AppendSessionDateToDestinationFolder; } else { return false; } } set { if (session != null) { session.AppendSessionDateToDestinationFolder = value; RaisePropertyChanged("AppendSessionDateToDestinationFolder"); } } } /// <summary> /// Enumerate all PTP / MTP sources when FindAllSources button is clicked. /// </summary> /// <param name="sender">The source of the click event</param> /// <param name="e">Details about the click event </param> private async void OnFindSourcesClicked(object sender, RoutedEventArgs e) { try { rootPage.NotifyUser(String.Empty, NotifyType.StatusMessage); // clear our list of items to import this.itemsToImport = null; this.fileListView.ItemsSource = this.itemsToImport; // reset UI elements this.progressBar.Value = 0.0; this.propertiesTxtBox.Text = ""; // disable all buttons until source selection is made setButtonState(false); // reenable source selection this.sourceListBox.IsEnabled = true; // clear find criteria this.OnlyImages.IsChecked = false; this.OnlyVideo.IsChecked = false; this.ImagesAndVideo.IsChecked = false; // Dispose any created import session if (this.session != null) { this.session.Dispose(); } // Check to ensure API is supported bool importSupported = await PhotoImportManager.IsSupportedAsync(); if (importSupported) { // enumerate all available sources to where we can import from sourceListBox.ItemsSource = await PhotoImportManager.FindAllSourcesAsync(); } else { rootPage.NotifyUser("Import is not supported.", NotifyType.ErrorMessage); } } catch (Exception ex) { rootPage.NotifyUser("FindAllSourcesAsync Failed. " + "Exception: " + ex.ToString(), NotifyType.ErrorMessage); } } /// <summary> /// Display the source properties when a new source is selected. /// </summary> /// <param name="sender">The source of the selection changed event</param> /// <param name="e">Details about the selection chagned event</param> private void SourceList_SelectionChanged(object sender, SelectionChangedEventArgs e) { // reset any previous items this.itemsToImport = null; this.fileListView.ItemsSource = null; // enable find options this.OnlyImages.IsEnabled = true; this.OnlyVideo.IsEnabled = true; this.ImagesAndVideo.IsEnabled = true; // set the default to find Images and Video this.ImagesAndVideo.IsChecked = true; // clear any values in the source properties this.propertiesTxtBox.Text = ""; if (e.AddedItems.Count != 0) { this.importSource = e.AddedItems.First() as PhotoImportSource; DisplaySourceProperties(); // enable Find New and Find All buttons, disable the rest this.findNewItemsButton.IsEnabled = true; this.findAllItemsButton.IsEnabled = true; this.selectNewButton.IsEnabled = false; this.selectNoneButton.IsEnabled = false; this.selectAllButton.IsEnabled = false; this.deleteButton.IsEnabled = false; this.importButton.IsEnabled = false; } } /// <summary> /// Enumerate new importable items from the source when FindAllItems button is clicked /// </summary> /// <param name="sender">The source of the click event</param> /// <param name="e">Details about the click event</param> private void OnFindNewItemsClicked(object sender, RoutedEventArgs e) { findItems(this.contentTypeFilder, PhotoImportItemSelectionMode.SelectNew); } /// <summary> /// Enumerate all importable items from the source when FindAllItems button is clicked /// </summary> /// <param name="sender">The source of the click event</param> /// <param name="e">Details about the click event</param> private void OnFindAllItemsClicked(object sender, RoutedEventArgs e) { findItems(this.contentTypeFilder, PhotoImportItemSelectionMode.SelectAll); } /// <summary> /// Helper method to Enumerate all importable items /// </summary> /// <param name="contentType">the content type</param> /// <param name="selectionMode">the selection mode</param> private async void findItems(PhotoImportContentTypeFilter contentType, PhotoImportItemSelectionMode selectionMode) { rootPage.NotifyUser(String.Empty, NotifyType.StatusMessage); // Disable buttons and lists to prevent unexpected reentrance. setButtonState(false); this.sourceListBox.IsEnabled = false; this.cts = new CancellationTokenSource(); try { this.progressRing.IsActive = true; this.itemsToImport = null; this.fileListView.ItemsSource = null; // Dispose any created import session if (this.session != null) { this.session.Dispose(); } // Create the import session from the source selected this.session = importSource.CreateImportSession(); RaisePropertyChanged("AppendSessionDateToDestinationFolder"); // Progress handler for FindItemsAsync var progress = new Progress<uint>((result) => { rootPage.NotifyUser(String.Format("Found {0} Files", result.ToString()), NotifyType.StatusMessage); }); // Find all items available importable item from our source this.itemsResult = await session.FindItemsAsync(contentType, selectionMode).AsTask(cts.Token, progress); setIncrementalFileList(this.itemsResult); DisplayFindItemsResult(); if (this.itemsResult.HasSucceeded) { // disable Find New , Find All and Delete button. this.findNewItemsButton.IsEnabled = false; this.findAllItemsButton.IsEnabled = false; this.deleteButton.IsEnabled = false; // enable list selection , folder options and import buttons this.selectNewButton.IsEnabled = true; this.selectNoneButton.IsEnabled = true; this.selectAllButton.IsEnabled = true; this.importButton.IsEnabled = true; this.fileListView.IsEnabled = true; this.AddSessionDateFolder.IsEnabled = true; this.NoSubFolder.IsEnabled = true; this.FileDateSubfolder.IsEnabled = true; this.ExifDateSubfolder.IsEnabled = true; this.KeepOriginalFolder.IsEnabled = true; } else { rootPage.NotifyUser("FindItemsAsync did not succeed or was not completed.", NotifyType.StatusMessage); // re-enable Find New and Find All buttons this.findNewItemsButton.IsEnabled = true; this.findAllItemsButton.IsEnabled = true; this.progressRing.IsActive = false; } this.progressRing.IsActive = false; // Set the CancellationTokenSource to null when the work is complete. cts = null; } catch (Exception ex) { rootPage.NotifyUser("Error: Operation incomplete. " + "Exception: " + ex.ToString(), NotifyType.ErrorMessage); } } /// <summary> /// Initiate the import operation when the Import button is clicked. /// </summary> /// <param name="sender">Source of the click event</param> /// <param name="e">Details about the click event</param> private async void OnImportButtonClicked(object sender, RoutedEventArgs e) { rootPage.NotifyUser(String.Empty, NotifyType.StatusMessage); // disable UI while async operations are running. setButtonState(false); this.sourceListBox.IsEnabled = false; this.progressBar.Value = 0.0; cts = new CancellationTokenSource(); try { if (itemsResult.SelectedTotalCount <= 0) { rootPage.NotifyUser("Nothing Selected for Import.", NotifyType.StatusMessage); } else { var progress = new Progress<PhotoImportProgress>((result) => { progressBar.Value = result.ImportProgress; }); this.itemsResult.ItemImported += async (s, a) => { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { rootPage.NotifyUser(String.Format("Imported: {0}", a.ImportedItem.Name), NotifyType.StatusMessage); }); }; // import items from the our list of selected items this.importedResult = await this.itemsResult.ImportItemsAsync().AsTask(cts.Token, progress); DisplayImportedSummary(); if (!this.importedResult.HasSucceeded) { rootPage.NotifyUser("ImportItemsAsync did not succeed or was not completed", NotifyType.StatusMessage); } } } catch (Exception ex) { rootPage.NotifyUser("Files could not be imported. " + "Exception: " + ex.ToString(), NotifyType.ErrorMessage); } cts = null; // allow the user to find sources and delete the files from the media this.findSourceButton.IsEnabled = true; this.deleteButton.IsEnabled = true; this.importButton.IsEnabled = false; this.findNewItemsButton.IsEnabled = false; this.findAllItemsButton.IsEnabled = false; this.selectNewButton.IsEnabled = false; this.selectAllButton.IsEnabled = false; this.selectNoneButton.IsEnabled = false; this.NoSubFolder.IsChecked = false; this.FileDateSubfolder.IsChecked = false; this.ExifDateSubfolder.IsChecked = false; this.KeepOriginalFolder.IsChecked = false; } /// <summary> /// Select all items. /// </summary> /// <param name="sender">Source of the click event</param> /// <param name="e">Details about the click event</param> private void OnSelectAllButtonClicked(object sender, RoutedEventArgs e) { // select all items for import this.itemsResult.SelectAll(); setIncrementalFileList(this.itemsResult); DisplayFindItemsResult(); } /// <summary> /// Select only new items. Items that have already been imported is not selected. /// </summary> /// <param name="sender">Source of the click event</param> /// <param name="e">Details about the click event</param> private async void OnSelectNewButtonClicked(object sender, RoutedEventArgs e) { // select only items that new await this.itemsResult.SelectNewAsync(); setIncrementalFileList(this.itemsResult); DisplayFindItemsResult(); } /// <summary> /// Deselect all items. /// </summary> /// <param name="sender">Source of the click event</param> /// <param name="e">Details about the click event</param> private void OnSelectNoneButtonClicked(object sender, RoutedEventArgs e) { // deselects all items this.itemsResult.SelectNone(); setIncrementalFileList(this.itemsResult); DisplayFindItemsResult(); } /// <summary> /// Creates a GeneratorIncrementalLoadingClass and sets the FindItemsResult to the filelist for display /// </summary> /// <param name="list">PhotoImportFindItemResult list</param> private void setIncrementalFileList (PhotoImportFindItemsResult list) { // GeneratorIncrementalLoadingClass is used to incrementally load items in the Listview view including thumbnails this.itemsToImport = new GeneratorIncrementalLoadingClass<ImportableItemWrapper>(list.TotalCount, (int index) => { return new ImportableItemWrapper(list.FoundItems[index]); }); this.fileListView.ItemsSource = this.itemsToImport; } /// <summary> /// When a user clicks the delete button, deletes the content that were imported. /// Calling DeleteImportedItemsFromSourceAsync does not delete content that were not imported. /// </summary> /// <param name="sender">Source of the click event</param> /// <param name="e">Detials about the click event</param> private async void OnDeleteButtonClicked(object sender, RoutedEventArgs e) { rootPage.NotifyUser("Deleting items...", NotifyType.StatusMessage); // Prevent unexpected reentrance. this.deleteButton.IsEnabled = false; cts = new CancellationTokenSource(); try { if (importedResult == null) { rootPage.NotifyUser("Nothing was imported for deletion.", NotifyType.StatusMessage); } else { var progress = new Progress<double>((result) => { this.progressBar.Value = result; }); this.deleteResult = await this.importedResult.DeleteImportedItemsFromSourceAsync().AsTask(cts.Token, progress); DisplayDeletedResults(); if (!this.deleteResult.HasSucceeded) { rootPage.NotifyUser("Delete operation did not succeed or was not completed", NotifyType.StatusMessage); } } } catch (Exception ex) { rootPage.NotifyUser("Files could not be Deleted." + "Exception: " + ex.ToString(), NotifyType.ErrorMessage); } // set the CancellationTokenSource to null when the work is complete. cts = null; // content is removed, disable the appropriate buttons this.findSourceButton.IsEnabled = true; this.importButton.IsEnabled = false; this.findNewItemsButton.IsEnabled = false; this.findAllItemsButton.IsEnabled = false; this.selectNewButton.IsEnabled = false; this.selectAllButton.IsEnabled = false; this.selectNoneButton.IsEnabled = false; this.deleteButton.IsEnabled = false; this.fileListView.IsEnabled = false; } /// <summary> /// Cancels an async operation /// </summary> /// <param name="sender">Source of the cancel event</param> /// <param name="e">Details about the cancel event</param> private void OnCancelButtonClicked(object sender, RoutedEventArgs e) { if (cts != null) { cts.Cancel(); rootPage.NotifyUser("Operation canceled by the Cancel button.", NotifyType.StatusMessage); } } /// <summary> /// Helper method to display the files enumerated from the source. /// </summary> void DisplayFindItemsResult() { if (itemsResult != null) { StringBuilder findResultProperties = new StringBuilder(); findResultProperties.AppendLine(String.Format("Photos\t\t\t : {0} \t\t Selected Photos\t\t: {1}", itemsResult.PhotosCount, itemsResult.SelectedPhotosCount)); findResultProperties.AppendLine(String.Format("Videos\t\t\t : {0} \t\t Selected Videos\t\t: {1}", itemsResult.VideosCount, itemsResult.SelectedVideosCount)); findResultProperties.AppendLine(String.Format("SideCars\t\t : {0} \t\t Selected Sidecars\t: {1}", itemsResult.SidecarsCount, itemsResult.SelectedSidecarsCount)); findResultProperties.AppendLine(String.Format("Siblings\t\t\t : {0} \t\t Selected Sibilings\t: {1} ", itemsResult.SiblingsCount, itemsResult.SelectedSiblingsCount)); findResultProperties.AppendLine(String.Format("Total Items Items\t : {0} \t\t Selected TotalCount \t: {1}", itemsResult.TotalCount, itemsResult.SelectedTotalCount)); rootPage.NotifyUser(findResultProperties.ToString(), NotifyType.StatusMessage); } } /// <summary> /// Helper method to display the files that were imported. /// </summary> void DisplayImportedSummary() { if (importedResult != null) { StringBuilder importedSummary = new StringBuilder(); importedSummary.AppendLine(String.Format("Photos Imported \t: {0} ", importedResult.PhotosCount)); importedSummary.AppendLine(String.Format("Videos Imported \t: {0} ", importedResult.VideosCount)); importedSummary.AppendLine(String.Format("SideCars Imported \t: {0} ", importedResult.SidecarsCount)); importedSummary.AppendLine(String.Format("Siblings Imported \t: {0} ", importedResult.SiblingsCount)); importedSummary.AppendLine(String.Format("Total Items Imported \t: {0} ", importedResult.TotalCount)); importedSummary.AppendLine(String.Format("Total Bytes Imported \t: {0} ", importedResult.TotalSizeInBytes)); rootPage.NotifyUser(importedSummary.ToString(), NotifyType.StatusMessage); } } /// <summary> /// Helper method to display the source properties information. /// </summary> void DisplaySourceProperties() { if (importSource != null) { StringBuilder sourceProperties = new StringBuilder(); sourceProperties.AppendLine(String.Format("Description: {0} ", importSource.Description)); sourceProperties.AppendLine(String.Format("IsMassStorage: {0} ", importSource.IsMassStorage)); sourceProperties.AppendLine(String.Format("Manufacturer: {0} ", importSource.Manufacturer)); IReadOnlyList<PhotoImportStorageMedium> sm = importSource.StorageMedia; sourceProperties.AppendLine(String.Format("AvailableSpaceInBytes: {0} ", sm[0].AvailableSpaceInBytes)); sourceProperties.AppendLine(String.Format("CapacityInBytes: {0} ", sm[0].CapacityInBytes)); sourceProperties.AppendLine(String.Format("Name: {0} ", sm[0].Name)); sourceProperties.AppendLine(String.Format("SerialNumber: {0} ", sm[0].SerialNumber)); sourceProperties.AppendLine(String.Format("StorageMediaType: {0} ", sm[0].StorageMediumType)); sourceProperties.AppendLine(String.Format("Id: {0} ", importSource.Id)); propertiesTxtBox.Text = sourceProperties.ToString(); } } /// <summary> /// Helper method to display the imported files that were deleted /// </summary> void DisplayDeletedResults() { if (deleteResult != null) { StringBuilder deletedResults = new StringBuilder(); deletedResults.AppendLine(String.Format("Total Photos Deleted:\t{0} ", deleteResult.PhotosCount)); deletedResults.AppendLine(String.Format("Total Videos Deleted:\t{0} ", deleteResult.VideosCount)); deletedResults.AppendLine(String.Format("Total Sidecars Deleted:\t{0} ", deleteResult.SidecarsCount)); deletedResults.AppendLine(String.Format("Total Sibilings Deleted:\t{0} ", deleteResult.SiblingsCount)); deletedResults.AppendLine(String.Format("Total Files Deleted:\t{0} ", deleteResult.TotalCount)); deletedResults.AppendLine(String.Format("Total Bytes Deleted:\t{0} ", deleteResult.TotalSizeInBytes)); rootPage.NotifyUser(deletedResults.ToString(), NotifyType.StatusMessage); } } /// <summary> /// Helper method to set the state of the button /// </summary> /// <param name="isEnabled">state of the button</param> void setButtonState(bool isEnabled) { this.importButton.IsEnabled = isEnabled; this.deleteButton.IsEnabled = isEnabled; this.findNewItemsButton.IsEnabled = isEnabled; this.findAllItemsButton.IsEnabled = isEnabled; this.selectNewButton.IsEnabled = isEnabled; this.selectAllButton.IsEnabled = isEnabled; this.selectNoneButton.IsEnabled = isEnabled; this.fileListView.IsEnabled = isEnabled; this.OnlyImages.IsEnabled = isEnabled; this.OnlyVideo.IsEnabled = isEnabled; this.ImagesAndVideo.IsEnabled = isEnabled; this.AddSessionDateFolder.IsEnabled = isEnabled; this.NoSubFolder.IsEnabled = isEnabled; this.FileDateSubfolder.IsEnabled = isEnabled; this.ExifDateSubfolder.IsEnabled = isEnabled; this.KeepOriginalFolder.IsEnabled = isEnabled; } /// <summary> /// When a checkbox is clicked, update the UI to the latest selection /// </summary> /// <param name="sender">Sender</param> /// <param name="e">RoutedEventArgs</param> private void CheckBox_Click(object sender, RoutedEventArgs e) { // update the result count DisplayFindItemsResult(); } /// <summary /// This app is registered as a hanlder for WPD\IMageSourceAutoPlay event. /// When a user connects a WPD device (ie: Camera), OnNavigatedTo is called with DeviceInformationId /// that we can call FromIdAsync() and preselect the device. /// /// We also need to handle the situation where the client was terminated while an import operation was in flight. /// Import will continue and we attempt to reconnect back to the session. /// </summary> /// <param name="e">Details about the NavigationEventArgs</param> protected override async void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); rootPage = MainPage.Current; try { //An photo import session was in progress if (e.Parameter is PhotoImportOperation) { PhotoImportOperation op = e.Parameter as PhotoImportOperation; switch (op.Stage) { // file enumeration was running case PhotoImportStage.FindingItems: cts = new CancellationTokenSource(); rootPage.NotifyUser("Reconnected back to the file enumeration stage", NotifyType.StatusMessage); // Set up progress handler for existing file enumeration var findAllItemsProgress = new Progress<uint>((result) => { rootPage.NotifyUser(String.Format("Found {0} Files", result.ToString()), NotifyType.StatusMessage); }); // retrieve previous session this.session = op.Session; // get to the operation for the existing FindItemsAsync session this.itemsResult = await op.ContinueFindingItemsAsync.AsTask(cts.Token, findAllItemsProgress); // display the items we found in the previous session setIncrementalFileList(this.itemsResult); this.selectAllButton.IsEnabled = true; this.selectNoneButton.IsEnabled = true; this.selectNewButton.IsEnabled = true; this.importButton.IsEnabled = true; DisplayFindItemsResult(); cts = null; break; // Import was running case PhotoImportStage.ImportingItems: rootPage.NotifyUser("Reconnected back to the importing stage.", NotifyType.StatusMessage); setButtonState(false); cts = new CancellationTokenSource(); // Set up progress handler for the existing import session var importSelectedItemsProgress = new Progress<PhotoImportProgress>((result) => { progressBar.Value = result.ImportProgress; }); // retrieve the previous operation this.session = op.Session; // get the itemsResult that were found in the previous session this.itemsResult = await op.ContinueFindingItemsAsync.AsTask(); // hook up the ItemImported Handler to show progress this.itemsResult.ItemImported += async (s, a) => { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { rootPage.NotifyUser(String.Format("Imported: {0}", a.ImportedItem.Name), NotifyType.StatusMessage); }); }; // Get the operation for the import operation that was in flight this.importedResult = await op.ContinueImportingItemsAsync.AsTask(cts.Token, importSelectedItemsProgress); DisplayImportedSummary(); this.findSourceButton.IsEnabled = true; this.deleteButton.IsEnabled = true; cts = null; break; // Delete operation is in progress case PhotoImportStage.DeletingImportedItemsFromSource: rootPage.NotifyUser("Reconnected to the deletion stage.",NotifyType.StatusMessage); this.findSourceButton.IsEnabled = false; this.deleteButton.IsEnabled = false; cts = new CancellationTokenSource(); var progress = new Progress<double>((result) => { this.progressBar.Value = result; }); // get the operation for the existing delete session this.deleteResult = await op.ContinueDeletingImportedItemsFromSourceAsync.AsTask(cts.Token, progress); DisplayDeletedResults(); if (!deleteResult.HasSucceeded) { rootPage.NotifyUser("Deletion did not succeeded or was cancelled.", NotifyType.StatusMessage); } this.findSourceButton.IsEnabled = true; // Set the CancellationTokenSource to null when the work is complete. cts = null; break; // Idle State. case PhotoImportStage.NotStarted: rootPage.NotifyUser("No import tasks was started.", NotifyType.StatusMessage); this.session = op.Session; break; default: break; } } // Activated by AutoPlay if (e.Parameter is DeviceActivatedEventArgs) { this.arguments = e.Parameter as DeviceActivatedEventArgs; bool importSupported = await PhotoImportManager.IsSupportedAsync(); this.sourceListBox.Items.Clear(); List<PhotoImportSource> source = new List<PhotoImportSource>(); // Create the source from a device Id source.Add(await PhotoImportSource.FromIdAsync(this.arguments.DeviceInformationId)); // bind and preselects source this.sourceListBox.ItemsSource = source; this.sourceListBox.SelectedIndex = 0; rootPage.NotifyUser("Device selected from AutoPlay", NotifyType.StatusMessage); } } catch (Exception ex) { rootPage.NotifyUser("Exception: " + ex.ToString(), NotifyType.ErrorMessage); } } private void OnlyImages_Checked(object sender, RoutedEventArgs e) { this.contentTypeFilder = PhotoImportContentTypeFilter.OnlyImages; // enable find since the filter has changed this.findAllItemsButton.IsEnabled = true; this.findNewItemsButton.IsEnabled = true; } private void OnlyVideo_Checked(object sender, RoutedEventArgs e) { this.contentTypeFilder = PhotoImportContentTypeFilter.OnlyVideos; // enable find since the filter has changed this.findAllItemsButton.IsEnabled = true; this.findNewItemsButton.IsEnabled = true; } private void ImagesAndVideo_Checked(object sender, RoutedEventArgs e) { this.contentTypeFilder = PhotoImportContentTypeFilter.ImagesAndVideos; // enable find since the filter has changed this.findAllItemsButton.IsEnabled = true; this.findNewItemsButton.IsEnabled = true; } private void NoSubFolder_checked(object sender, RoutedEventArgs e) { this.session.SubfolderCreationMode = PhotoImportSubfolderCreationMode.DoNotCreateSubfolders; } private void FileDateSubfolder_checked(object sender, RoutedEventArgs e) { this.session.SubfolderCreationMode = PhotoImportSubfolderCreationMode.CreateSubfoldersFromFileDate; } private void ExifDateSubfolder_checked(object sender, RoutedEventArgs e) { this.session.SubfolderCreationMode = PhotoImportSubfolderCreationMode.CreateSubfoldersFromExifDate; } private void KeepOriginalFolder_checked(object sender, RoutedEventArgs e) { this.session.SubfolderCreationMode = PhotoImportSubfolderCreationMode.KeepOriginalFolderStructure; } public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(string propName) { PropertyChanged(this, new PropertyChangedEventArgs(propName)); } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Sounds //-------------------------------------------------------------------------- // Added for Lesson 5 - Adding Weapons - 23 Sep 11 datablock SFXProfile(WeaponTemplateFireSound) { filename = "data/FPSGameplay/sound/weapons/wpn_fire"; description = AudioClose3D; preload = true; }; datablock SFXProfile(WeaponTemplateReloadSound) { filename = "data/FPSGameplay/sound/weapons/wpn_reload"; description = AudioClose3D; preload = true; }; datablock SFXProfile(WeaponTemplateSwitchinSound) { filename = "data/FPSGameplay/sound/weapons/wpn_switchin"; description = AudioClose3D; preload = true; }; datablock SFXProfile(WeaponTemplateIdleSound) { filename = "data/FPSGameplay/sound/weapons/wpn_idle"; description = AudioClose3D; preload = true; }; datablock SFXProfile(WeaponTemplateGrenadeSound) { filename = "data/FPSGameplay/sound/weapons/wpn_grenadelaunch"; description = AudioClose3D; preload = true; }; datablock SFXProfile(WeaponTemplateMineSwitchinSound) { filename = "data/FPSGameplay/sound/weapons/wpn_mine_switchin"; description = AudioClose3D; preload = true; }; //----------------------------------------------------------------------------- // Added 28 Sep 11 datablock LightDescription( BulletProjectileLightDesc ) { color = "0.0 0.5 0.7"; range = 3.0; }; datablock ProjectileData( BulletProjectile ) { projectileShapeName = ""; directDamage = 5; radiusDamage = 0; damageRadius = 0.5; areaImpulse = 0.5; impactForce = 1; explosion = BulletDirtExplosion; decal = BulletHoleDecal; muzzleVelocity = 120; velInheritFactor = 1; armingDelay = 0; lifetime = 992; fadeDelay = 1472; bounceElasticity = 0; bounceFriction = 0; isBallistic = false; gravityMod = 1; }; function BulletProjectile::onCollision(%this,%obj,%col,%fade,%pos,%normal) { // Apply impact force from the projectile. // Apply damage to the object all shape base objects if ( %col.getType() & $TypeMasks::GameBaseObjectType ) %col.damage(%obj,%pos,%this.directDamage,"BulletProjectile"); } //----------------------------------------------------------------------------- datablock ProjectileData( WeaponTemplateProjectile ) { projectileShapeName = ""; directDamage = 5; radiusDamage = 0; damageRadius = 0.5; areaImpulse = 0.5; impactForce = 1; muzzleVelocity = 120; velInheritFactor = 1; armingDelay = 0; lifetime = 992; fadeDelay = 1472; bounceElasticity = 0; bounceFriction = 0; isBallistic = false; gravityMod = 1; }; function WeaponTemplateProjectile::onCollision(%this,%obj,%col,%fade,%pos,%normal) { // Apply impact force from the projectile. // Apply damage to the object all shape base objects if ( %col.getType() & $TypeMasks::GameBaseObjectType ) %col.damage(%obj,%pos,%this.directDamage,"WeaponTemplateProjectile"); } //----------------------------------------------------------------------------- // Ammo Item //----------------------------------------------------------------------------- datablock ItemData(WeaponTemplateAmmo) { // Mission editor category category = "Ammo"; // Add the Ammo namespace as a parent. The ammo namespace provides // common ammo related functions and hooks into the inventory system. className = "Ammo"; // Basic Item properties shapeFile = ""; mass = 1; elasticity = 0.2; friction = 0.6; // Dynamic properties defined by the scripts pickUpName = ""; maxInventory = 1000; }; //-------------------------------------------------------------------------- // Weapon Item. This is the item that exists in the world, i.e. when it's // been dropped, thrown or is acting as re-spawnable item. When the weapon // is mounted onto a shape, the NewWeaponTemplate is used. //----------------------------------------------------------------------------- datablock ItemData(WeaponTemplateItem) { // Mission editor category category = "Weapon"; // Hook into Item Weapon class hierarchy. The weapon namespace // provides common weapon handling functions in addition to hooks // into the inventory system. className = "Weapon"; // Basic Item properties shapeFile = ""; mass = 1; elasticity = 0.2; friction = 0.6; emap = true; // Dynamic properties defined by the scripts pickUpName = "A basic weapon"; description = "Weapon"; image = WeaponTemplateImage; reticle = "crossHair"; }; datablock ShapeBaseImageData(WeaponTemplateImage) { // FP refers to first person specific features // Defines what art file to use. shapeFile = "data/FPSGameplay/art/shapes/weapons/Lurker/TP_Lurker.DAE"; shapeFileFP = "data/FPSGameplay/art/shapes/weapons/Lurker/FP_Lurker.DAE"; // Whether or not to enable environment mapping //emap = true; //imageAnimPrefixFP = ""; // Specify mount point & offset for 3rd person, and eye offset // for first person rendering. mountPoint = 0; //firstPerson = true; //eyeOffset = "0.001 -0.05 -0.065"; // When firing from a point offset from the eye, muzzle correction // will adjust the muzzle vector to point to the eye LOS point. // Since this weapon doesn't actually fire from the muzzle point, // we need to turn this off. //correctMuzzleVector = true; // Add the WeaponImage namespace as a parent, WeaponImage namespace // provides some hooks into the inventory system. class = "WeaponImage"; className = "WeaponImage"; // Projectiles and Ammo. item = WeaponTemplateItem; ammo = WeaponTemplateAmmo; //projectile = BulletProjectile; //projectileType = Projectile; //projectileSpread = "0.005"; // Properties associated with the shell casing that gets ejected during firing //casing = BulletShell; //shellExitDir = "1.0 0.3 1.0"; //shellExitOffset = "0.15 -0.56 -0.1"; //shellExitVariance = 15.0; //shellVelocity = 3.0; // Properties associated with a light that occurs when the weapon fires //lightType = ""; //lightColor = "0.992126 0.968504 0.708661 1"; //lightRadius = "4"; //lightDuration = "100"; //lightBrightness = 2; // Properties associated with shaking the camera during firing //shakeCamera = false; //camShakeFreq = "0 0 0"; //camShakeAmp = "0 0 0"; // Images have a state system which controls how the animations // are run, which sounds are played, script callbacks, etc. This // state system is downloaded to the client so that clients can // predict state changes and animate accordingly. The following // system supports basic ready->fire->reload transitions as // well as a no-ammo->dryfire idle state. // If true, allow multiple timeout transitions to occur within a single tick // useful if states have a very small timeout //useRemainderDT = true; // Initial start up state stateName[0] = "Preactivate"; stateTransitionOnLoaded[0] = "Activate"; stateTransitionOnNoAmmo[0] = "NoAmmo"; // Activating the gun. Called when the weapon is first // mounted and there is ammo. stateName[1] = "Activate"; stateTransitionGeneric0In[1] = "SprintEnter"; stateTransitionOnTimeout[1] = "Ready"; stateTimeoutValue[1] = 0.5; stateSequence[1] = "switch_in"; // Ready to fire, just waiting for the trigger stateName[2] = "Ready"; stateTransitionGeneric0In[2] = "SprintEnter"; stateTransitionOnMotion[2] = "ReadyMotion"; stateTransitionOnTimeout[2] = "ReadyFidget"; stateTimeoutValue[2] = 10; stateWaitForTimeout[2] = false; stateScaleAnimation[2] = false; stateScaleAnimationFP[2] = false; stateTransitionOnNoAmmo[2] = "NoAmmo"; stateTransitionOnTriggerDown[2] = "Fire"; stateSequence[2] = "idle"; // Same as Ready state but plays a fidget sequence stateName[3] = "ReadyFidget"; stateTransitionGeneric0In[3] = "SprintEnter"; stateTransitionOnMotion[3] = "ReadyMotion"; stateTransitionOnTimeout[3] = "Ready"; stateTimeoutValue[3] = 6; stateWaitForTimeout[3] = false; stateTransitionOnNoAmmo[3] = "NoAmmo"; stateTransitionOnTriggerDown[3] = "Fire"; stateSequence[3] = "idle_fidget1"; // Ready to fire with player moving stateName[4] = "ReadyMotion"; stateTransitionGeneric0In[4] = "SprintEnter"; stateTransitionOnNoMotion[4] = "Ready"; stateWaitForTimeout[4] = false; stateScaleAnimation[4] = false; stateScaleAnimationFP[4] = false; stateSequenceTransitionIn[4] = true; stateSequenceTransitionOut[4] = true; stateTransitionOnNoAmmo[4] = "NoAmmo"; stateTransitionOnTriggerDown[4] = "Fire"; stateSequence[4] = "run"; // Fire the weapon. Calls the fire script which does // the actual work. stateName[5] = "Fire"; stateTransitionGeneric0In[5] = "SprintEnter"; stateTransitionOnTimeout[5] = "Reload"; stateTimeoutValue[5] = 0.15; stateFire[5] = true; stateRecoil[5] = ""; stateAllowImageChange[5] = false; stateSequence[5] = "fire"; stateScaleAnimation[5] = false; stateSequenceNeverTransition[5] = true; stateSequenceRandomFlash[5] = true; // use muzzle flash sequence stateScript[5] = "onFire"; stateSound[5] = WeaponTemplateFireSound; stateEmitter[5] = GunFireSmokeEmitter; stateEmitterTime[5] = 0.025; // Play the reload animation, and transition into stateName[6] = "Reload"; stateTransitionGeneric0In[6] = "SprintEnter"; stateTransitionOnNoAmmo[6] = "NoAmmo"; stateTransitionOnTimeout[6] = "Ready"; stateWaitForTimeout[6] = "0"; stateTimeoutValue[6] = 0.05; stateAllowImageChange[6] = false; //stateSequence[6] = "reload"; stateEjectShell[6] = true; // No ammo in the weapon, just idle until something // shows up. Play the dry fire sound if the trigger is // pulled. stateName[7] = "NoAmmo"; stateTransitionGeneric0In[7] = "SprintEnter"; stateTransitionOnAmmo[7] = "ReloadClip"; stateScript[7] = "onClipEmpty"; // No ammo dry fire stateName[8] = "DryFire"; stateTransitionGeneric0In[8] = "SprintEnter"; stateTimeoutValue[8] = 1.0; stateTransitionOnTimeout[8] = "NoAmmo"; stateScript[8] = "onDryFire"; // Play the reload clip animation stateName[9] = "ReloadClip"; stateTransitionGeneric0In[9] = "SprintEnter"; stateTransitionOnTimeout[9] = "Ready"; stateWaitForTimeout[9] = true; stateTimeoutValue[9] = 3.0; stateReload[9] = true; stateSequence[9] = "reload"; stateShapeSequence[9] = "Reload"; stateScaleShapeSequence[9] = true; // Start Sprinting stateName[10] = "SprintEnter"; stateTransitionGeneric0Out[10] = "SprintExit"; stateTransitionOnTimeout[10] = "Sprinting"; stateWaitForTimeout[10] = false; stateTimeoutValue[10] = 0.5; stateWaitForTimeout[10] = false; stateScaleAnimation[10] = false; stateScaleAnimationFP[10] = false; stateSequenceTransitionIn[10] = true; stateSequenceTransitionOut[10] = true; stateAllowImageChange[10] = false; stateSequence[10] = "sprint"; // Sprinting stateName[11] = "Sprinting"; stateTransitionGeneric0Out[11] = "SprintExit"; stateWaitForTimeout[11] = false; stateScaleAnimation[11] = false; stateScaleAnimationFP[11] = false; stateSequenceTransitionIn[11] = true; stateSequenceTransitionOut[11] = true; stateAllowImageChange[11] = false; stateSequence[11] = "sprint"; // Stop Sprinting stateName[12] = "SprintExit"; stateTransitionGeneric0In[12] = "SprintEnter"; stateTransitionOnTimeout[12] = "Ready"; stateWaitForTimeout[12] = false; stateTimeoutValue[12] = 0.5; stateSequenceTransitionIn[12] = true; stateSequenceTransitionOut[12] = true; stateAllowImageChange[12] = false; stateSequence[12] = "sprint"; };
//------------------------------------------------------------------------------ // <copyright file="SQLByteStorage.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> // <owner current="false" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data.Common { using System; using System.Xml; using System.Data.SqlTypes; using System.Diagnostics; using System.Globalization; using System.IO; using System.Xml.Serialization; using System.Collections; internal sealed class SqlByteStorage : DataStorage { private SqlByte[] values; public SqlByteStorage(DataColumn column) : base(column, typeof(SqlByte), SqlByte.Null, SqlByte.Null, StorageType.SqlByte) { } override public Object Aggregate(int[] records, AggregateType kind) { bool hasData = false; try { switch (kind) { case AggregateType.Sum: SqlInt64 sum = 0; foreach (int record in records) { if (IsNull(record)) continue; checked { sum += values[record];} hasData = true; } if (hasData) { return sum; } return NullValue; case AggregateType.Mean: SqlInt64 meanSum = 0; int meanCount = 0; foreach (int record in records) { if (IsNull(record)) continue; checked { meanSum += values[record].ToSqlInt64();} meanCount++; hasData = true; } if (hasData) { SqlByte mean = 0; checked {mean = (meanSum / (SqlInt64)meanCount).ToSqlByte();} return mean; } return NullValue; case AggregateType.Var: case AggregateType.StDev: int count = 0; SqlDouble var = (SqlDouble)0; SqlDouble prec = (SqlDouble)0; SqlDouble dsum = (SqlDouble)0; SqlDouble sqrsum = (SqlDouble)0; foreach (int record in records) { if (IsNull(record)) continue; dsum += values[record].ToSqlDouble(); sqrsum += values[record].ToSqlDouble() * values[record].ToSqlDouble(); count++; } if (count > 1) { var = ((SqlDouble)count * sqrsum - (dsum * dsum)); prec = var / (dsum * dsum); // we are dealing with the risk of a cancellation error // double is guaranteed only for 15 digits so a difference // with a result less than 1e-15 should be considered as zero if ((prec < 1e-15) || (var <0)) var = 0; else var = var / (count * (count -1)); if (kind == AggregateType.StDev) { return Math.Sqrt(var.Value); } return var; } return NullValue; case AggregateType.Min: SqlByte min = SqlByte.MaxValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (IsNull(record)) continue; if ((SqlByte.LessThan(values[record], min)).IsTrue) min = values[record]; hasData = true; } if (hasData) { return min; } return NullValue; case AggregateType.Max: SqlByte max = SqlByte.MinValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (IsNull(record)) continue; if ((SqlByte.GreaterThan(values[record], max)).IsTrue) max = values[record]; hasData = true; } if (hasData) { return max; } return NullValue; case AggregateType.First: if (records.Length > 0) { return values[records[0]]; } return null;// no data => null case AggregateType.Count: count = 0; for (int i = 0; i < records.Length; i++) { if (!IsNull(records[i])) count++; } return count; } } catch (OverflowException) { throw ExprException.Overflow(typeof(SqlByte)); } throw ExceptionBuilder.AggregateException(kind, DataType); } override public int Compare(int recordNo1, int recordNo2) { return values[recordNo1].CompareTo(values[recordNo2]); } override public int CompareValueTo(int recordNo, Object value) { return values[recordNo].CompareTo((SqlByte)value); } override public object ConvertValue(object value) { if (null != value) { return SqlConvert.ConvertToSqlByte(value); } return NullValue; } override public void Copy(int recordNo1, int recordNo2) { values[recordNo2] = values[recordNo1]; } override public Object Get(int record) { return values[record]; } override public bool IsNull(int record) { return (values[record].IsNull); } override public void Set(int record, Object value) { values[record] = SqlConvert.ConvertToSqlByte(value); } override public void SetCapacity(int capacity) { SqlByte[] newValues = new SqlByte[capacity]; if (null != values) { Array.Copy(values, 0, newValues, 0, Math.Min(capacity, values.Length)); } values = newValues; } override public object ConvertXmlToObject(string s) { SqlByte newValue = new SqlByte(); string tempStr =string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader, bug 98767 StringReader strReader = new StringReader(tempStr); IXmlSerializable tmp = newValue; using (XmlTextReader xmlTextReader = new XmlTextReader(strReader)) { tmp.ReadXml(xmlTextReader); } return ((SqlByte)tmp); } override public string ConvertObjectToXml(object value) { Debug.Assert(!DataStorage.IsObjectNull(value), "we shouldn't have null here"); Debug.Assert((value.GetType() == typeof(SqlByte)), "wrong input type"); StringWriter strwriter = new StringWriter(FormatProvider); using (XmlTextWriter xmlTextWriter = new XmlTextWriter (strwriter)) { ((IXmlSerializable)value).WriteXml(xmlTextWriter); } return (strwriter.ToString ()); } override protected object GetEmptyStorage(int recordCount) { return new SqlByte[recordCount]; } override protected void CopyValue(int record, object store, BitArray nullbits, int storeIndex) { SqlByte[] typedStore = (SqlByte[]) store; typedStore[storeIndex] = values[record]; nullbits.Set(record, IsNull(record)); } override protected void SetStorage(object store, BitArray nullbits) { values = (SqlByte[]) store; //SetNullStorage(nullbits); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines { /// <summary> /// CA1033: Interface methods should be callable by child types /// </summary> [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic), Shared] public sealed class InterfaceMethodsShouldBeCallableByChildTypesFixer : CodeFixProvider { public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(InterfaceMethodsShouldBeCallableByChildTypesAnalyzer.RuleId); public override FixAllProvider GetFixAllProvider() { return WellKnownFixAllProviders.BatchFixer; } public override async Task RegisterCodeFixesAsync(CodeFixContext context) { SemanticModel semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); SyntaxNode nodeToFix = root.FindNode(context.Span); if (nodeToFix == null) { return; } if (semanticModel.GetDeclaredSymbol(nodeToFix, context.CancellationToken) is not IMethodSymbol methodSymbol) { return; } SyntaxGenerator generator = SyntaxGenerator.GetGenerator(context.Document); SyntaxNode declaration = generator.GetDeclaration(nodeToFix); if (declaration == null) { return; } IMethodSymbol? candidateToIncreaseVisibility = GetExistingNonVisibleAlternate(methodSymbol); if (candidateToIncreaseVisibility != null) { ISymbol symbolToChange; bool checkSetter = false; if (candidateToIncreaseVisibility.IsAccessorMethod()) { symbolToChange = candidateToIncreaseVisibility.AssociatedSymbol; if (methodSymbol.AssociatedSymbol.Kind == SymbolKind.Property) { var originalProperty = (IPropertySymbol)methodSymbol.AssociatedSymbol; checkSetter = originalProperty.SetMethod != null; } } else { symbolToChange = candidateToIncreaseVisibility; } if (symbolToChange != null) { string title = string.Format(CultureInfo.CurrentCulture, MicrosoftCodeQualityAnalyzersResources.InterfaceMethodsShouldBeCallableByChildTypesFix1, symbolToChange.Name); context.RegisterCodeFix(new MyCodeAction(title, async ct => await MakeProtectedAsync(context.Document, symbolToChange, checkSetter, ct).ConfigureAwait(false), equivalenceKey: MicrosoftCodeQualityAnalyzersResources.InterfaceMethodsShouldBeCallableByChildTypesFix1), context.Diagnostics); } } else { ISymbol symbolToChange = methodSymbol.IsAccessorMethod() ? methodSymbol.AssociatedSymbol : methodSymbol; if (symbolToChange != null) { string title = string.Format(CultureInfo.CurrentCulture, MicrosoftCodeQualityAnalyzersResources.InterfaceMethodsShouldBeCallableByChildTypesFix2, symbolToChange.Name); context.RegisterCodeFix(new MyCodeAction(title, async ct => await ChangeToPublicInterfaceImplementationAsync(context.Document, symbolToChange, ct).ConfigureAwait(false), equivalenceKey: MicrosoftCodeQualityAnalyzersResources.InterfaceMethodsShouldBeCallableByChildTypesFix2), context.Diagnostics); } } context.RegisterCodeFix(new MyCodeAction(string.Format(CultureInfo.CurrentCulture, MicrosoftCodeQualityAnalyzersResources.InterfaceMethodsShouldBeCallableByChildTypesFix3, methodSymbol.ContainingType.Name), async ct => await MakeContainingTypeSealedAsync(context.Document, methodSymbol, ct).ConfigureAwait(false), equivalenceKey: MicrosoftCodeQualityAnalyzersResources.InterfaceMethodsShouldBeCallableByChildTypesFix3), context.Diagnostics); } private static IMethodSymbol? GetExistingNonVisibleAlternate(IMethodSymbol methodSymbol) { foreach (IMethodSymbol interfaceMethod in methodSymbol.ExplicitInterfaceImplementations) { foreach (INamedTypeSymbol type in methodSymbol.ContainingType.GetBaseTypesAndThis()) { IMethodSymbol candidate = type.GetMembers(interfaceMethod.Name).OfType<IMethodSymbol>().FirstOrDefault(m => !m.Equals(methodSymbol)); if (candidate != null) { return candidate; } } } return null; } private static async Task<Document> MakeProtectedAsync(Document document, ISymbol symbolToChange, bool checkSetter, CancellationToken cancellationToken) { SymbolEditor editor = SymbolEditor.Create(document); ISymbol? getter = null; ISymbol? setter = null; if (symbolToChange.Kind == SymbolKind.Property) { var propertySymbol = (IPropertySymbol)symbolToChange; getter = propertySymbol.GetMethod; setter = propertySymbol.SetMethod; } await editor.EditAllDeclarationsAsync(symbolToChange, (docEditor, declaration) => { docEditor.SetAccessibility(declaration, Accessibility.Protected); }, cancellationToken).ConfigureAwait(false); if (getter != null && getter.DeclaredAccessibility == Accessibility.Private) { await editor.EditAllDeclarationsAsync(getter, (docEditor, declaration) => { docEditor.SetAccessibility(declaration, Accessibility.NotApplicable); }, cancellationToken).ConfigureAwait(false); } if (checkSetter && setter != null && setter.DeclaredAccessibility == Accessibility.Private) { await editor.EditAllDeclarationsAsync(setter, (docEditor, declaration) => { docEditor.SetAccessibility(declaration, Accessibility.NotApplicable); }, cancellationToken).ConfigureAwait(false); } return editor.GetChangedDocuments().First(); } private static async Task<Document> ChangeToPublicInterfaceImplementationAsync(Document document, ISymbol symbolToChange, CancellationToken cancellationToken) { SymbolEditor editor = SymbolEditor.Create(document); IEnumerable<ISymbol>? explicitImplementations = GetExplicitImplementations(symbolToChange); if (explicitImplementations == null) { return document; } await editor.EditAllDeclarationsAsync(symbolToChange, (docEditor, declaration) => { SyntaxNode newDeclaration = declaration; foreach (ISymbol implementedMember in explicitImplementations) { SyntaxNode interfaceTypeNode = docEditor.Generator.TypeExpression(implementedMember.ContainingType); newDeclaration = docEditor.Generator.AsPublicInterfaceImplementation(newDeclaration, interfaceTypeNode); } docEditor.ReplaceNode(declaration, newDeclaration); }, cancellationToken).ConfigureAwait(false); return editor.GetChangedDocuments().First(); } private static IEnumerable<ISymbol>? GetExplicitImplementations(ISymbol? symbol) { if (symbol == null) { return null; } return symbol.Kind switch { SymbolKind.Method => ((IMethodSymbol)symbol).ExplicitInterfaceImplementations, SymbolKind.Event => ((IEventSymbol)symbol).ExplicitInterfaceImplementations, SymbolKind.Property => ((IPropertySymbol)symbol).ExplicitInterfaceImplementations, _ => null, }; } private static async Task<Document> MakeContainingTypeSealedAsync(Document document, IMethodSymbol methodSymbol, CancellationToken cancellationToken) { SymbolEditor editor = SymbolEditor.Create(document); await editor.EditAllDeclarationsAsync(methodSymbol.ContainingType, (docEditor, declaration) => { DeclarationModifiers modifiers = docEditor.Generator.GetModifiers(declaration); docEditor.SetModifiers(declaration, modifiers + DeclarationModifiers.Sealed); }, cancellationToken).ConfigureAwait(false); return editor.GetChangedDocuments().First(); } private class MyCodeAction : DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey) : base(title, createChangedDocument, equivalenceKey) { } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Cosmos.Table; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; using Orleans.Configuration; using Orleans.Configuration.Overrides; using Orleans.Persistence.AzureStorage; using Orleans.Providers.Azure; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Serialization; using LogLevel = Microsoft.Extensions.Logging.LogLevel; namespace Orleans.Storage { /// <summary> /// Simple storage for writing grain state data to Azure table storage. /// </summary> public class AzureTableGrainStorage : IGrainStorage, IRestExceptionDecoder, ILifecycleParticipant<ISiloLifecycle> { private readonly AzureTableStorageOptions options; private readonly ClusterOptions clusterOptions; private readonly SerializationManager serializationManager; private readonly IGrainFactory grainFactory; private readonly ITypeResolver typeResolver; private readonly ILoggerFactory loggerFactory; private readonly ILogger logger; private GrainStateTableDataManager tableDataManager; private JsonSerializerSettings JsonSettings; // each property can hold 64KB of data and each entity can take 1MB in total, so 15 full properties take // 15 * 64 = 960 KB leaving room for the primary key, timestamp etc private const int MAX_DATA_CHUNK_SIZE = 64 * 1024; private const int MAX_STRING_PROPERTY_LENGTH = 32 * 1024; private const int MAX_DATA_CHUNKS_COUNT = 15; private const string BINARY_DATA_PROPERTY_NAME = "Data"; private const string STRING_DATA_PROPERTY_NAME = "StringData"; private string name; /// <summary> Default constructor </summary> public AzureTableGrainStorage(string name, AzureTableStorageOptions options, IOptions<ClusterOptions> clusterOptions, SerializationManager serializationManager, IGrainFactory grainFactory, ITypeResolver typeResolver, ILoggerFactory loggerFactory) { this.options = options; this.clusterOptions = clusterOptions.Value; this.name = name; this.serializationManager = serializationManager; this.grainFactory = grainFactory; this.typeResolver = typeResolver; this.loggerFactory = loggerFactory; var loggerName = $"{typeof(AzureTableGrainStorageFactory).FullName}.{name}"; this.logger = this.loggerFactory.CreateLogger(loggerName); } /// <summary> Read state data function for this storage provider. </summary> /// <see cref="IGrainStorage.ReadStateAsync"/> public async Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { if (tableDataManager == null) throw new ArgumentException("GrainState-Table property not initialized"); string pk = GetKeyString(grainReference); if(logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_ReadingData, "Reading: GrainType={0} Pk={1} Grainid={2} from Table={3}", grainType, pk, grainReference, this.options.TableName); string partitionKey = pk; string rowKey = grainType; GrainStateRecord record = await tableDataManager.Read(partitionKey, rowKey).ConfigureAwait(false); if (record != null) { var entity = record.Entity; if (entity != null) { var loadedState = ConvertFromStorageFormat(entity, grainState.Type); grainState.State = loadedState ?? Activator.CreateInstance(grainState.Type); grainState.ETag = record.ETag; } } // Else leave grainState in previous default condition } /// <summary> Write state data function for this storage provider. </summary> /// <see cref="IGrainStorage.WriteStateAsync"/> public async Task WriteStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { if (tableDataManager == null) throw new ArgumentException("GrainState-Table property not initialized"); string pk = GetKeyString(grainReference); if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_WritingData, "Writing: GrainType={0} Pk={1} Grainid={2} ETag={3} to Table={4}", grainType, pk, grainReference, grainState.ETag, this.options.TableName); var entity = new DynamicTableEntity(pk, grainType); ConvertToStorageFormat(grainState.State, entity); var record = new GrainStateRecord { Entity = entity, ETag = grainState.ETag }; try { await DoOptimisticUpdate(() => tableDataManager.Write(record), grainType, grainReference, this.options.TableName, grainState.ETag).ConfigureAwait(false); grainState.ETag = record.ETag; } catch (Exception exc) { logger.Error((int)AzureProviderErrorCode.AzureTableProvider_WriteError, $"Error Writing: GrainType={grainType} Grainid={grainReference} ETag={grainState.ETag} to Table={this.options.TableName} Exception={exc.Message}", exc); throw; } } /// <summary> Clear / Delete state data function for this storage provider. </summary> /// <remarks> /// If the <c>DeleteStateOnClear</c> is set to <c>true</c> then the table row /// for this grain will be deleted / removed, otherwise the table row will be /// cleared by overwriting with default / null values. /// </remarks> /// <see cref="IGrainStorage.ClearStateAsync"/> public async Task ClearStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { if (tableDataManager == null) throw new ArgumentException("GrainState-Table property not initialized"); string pk = GetKeyString(grainReference); if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_WritingData, "Clearing: GrainType={0} Pk={1} Grainid={2} ETag={3} DeleteStateOnClear={4} from Table={5}", grainType, pk, grainReference, grainState.ETag, this.options.DeleteStateOnClear, this.options.TableName); var entity = new DynamicTableEntity(pk, grainType); var record = new GrainStateRecord { Entity = entity, ETag = grainState.ETag }; string operation = "Clearing"; try { if (this.options.DeleteStateOnClear) { operation = "Deleting"; await DoOptimisticUpdate(() => tableDataManager.Delete(record), grainType, grainReference, this.options.TableName, grainState.ETag).ConfigureAwait(false); } else { await DoOptimisticUpdate(() => tableDataManager.Write(record), grainType, grainReference, this.options.TableName, grainState.ETag).ConfigureAwait(false); } grainState.ETag = record.ETag; // Update in-memory data to the new ETag } catch (Exception exc) { logger.Error((int)AzureProviderErrorCode.AzureTableProvider_DeleteError, string.Format("Error {0}: GrainType={1} Grainid={2} ETag={3} from Table={4} Exception={5}", operation, grainType, grainReference, grainState.ETag, this.options.TableName, exc.Message), exc); throw; } } private static async Task DoOptimisticUpdate(Func<Task> updateOperation, string grainType, GrainReference grainReference, string tableName, string currentETag) { try { await updateOperation.Invoke().ConfigureAwait(false); } catch (StorageException ex) when (ex.IsPreconditionFailed() || ex.IsConflict()) { throw new TableStorageUpdateConditionNotSatisfiedException(grainType, grainReference, tableName, "Unknown", currentETag, ex); } } /// <summary> /// Serialize to Azure storage format in either binary or JSON format. /// </summary> /// <param name="grainState">The grain state data to be serialized</param> /// <param name="entity">The Azure table entity the data should be stored in</param> /// <remarks> /// See: /// http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx /// for more on the JSON serializer. /// </remarks> internal void ConvertToStorageFormat(object grainState, DynamicTableEntity entity) { int dataSize; IEnumerable<EntityProperty> properties; string basePropertyName; if (this.options.UseJson) { // http://james.newtonking.com/json/help/index.html?topic=html/T_Newtonsoft_Json_JsonConvert.htm string data = Newtonsoft.Json.JsonConvert.SerializeObject(grainState, this.JsonSettings); if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Writing JSON data size = {0} for grain id = Partition={1} / Row={2}", data.Length, entity.PartitionKey, entity.RowKey); // each Unicode character takes 2 bytes dataSize = data.Length * 2; properties = SplitStringData(data).Select(t => new EntityProperty(t)); basePropertyName = STRING_DATA_PROPERTY_NAME; } else { // Convert to binary format byte[] data = this.serializationManager.SerializeToByteArray(grainState); if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Writing binary data size = {0} for grain id = Partition={1} / Row={2}", data.Length, entity.PartitionKey, entity.RowKey); dataSize = data.Length; properties = SplitBinaryData(data).Select(t => new EntityProperty(t)); basePropertyName = BINARY_DATA_PROPERTY_NAME; } CheckMaxDataSize(dataSize, MAX_DATA_CHUNK_SIZE * MAX_DATA_CHUNKS_COUNT); foreach (var keyValuePair in properties.Zip(GetPropertyNames(basePropertyName), (property, name) => new KeyValuePair<string, EntityProperty>(name, property))) { entity.Properties.Add(keyValuePair); } } private void CheckMaxDataSize(int dataSize, int maxDataSize) { if (dataSize > maxDataSize) { var msg = string.Format("Data too large to write to Azure table. Size={0} MaxSize={1}", dataSize, maxDataSize); logger.Error(0, msg); throw new ArgumentOutOfRangeException("GrainState.Size", msg); } } private static IEnumerable<string> SplitStringData(string stringData) { var startIndex = 0; while (startIndex < stringData.Length) { var chunkSize = Math.Min(MAX_STRING_PROPERTY_LENGTH, stringData.Length - startIndex); yield return stringData.Substring(startIndex, chunkSize); startIndex += chunkSize; } } private static IEnumerable<byte[]> SplitBinaryData(byte[] binaryData) { var startIndex = 0; while (startIndex < binaryData.Length) { var chunkSize = Math.Min(MAX_DATA_CHUNK_SIZE, binaryData.Length - startIndex); var chunk = new byte[chunkSize]; Array.Copy(binaryData, startIndex, chunk, 0, chunkSize); yield return chunk; startIndex += chunkSize; } } private static IEnumerable<string> GetPropertyNames(string basePropertyName) { yield return basePropertyName; for (var i = 1; i < MAX_DATA_CHUNKS_COUNT; ++i) { yield return basePropertyName + i; } } private static IEnumerable<byte[]> ReadBinaryDataChunks(DynamicTableEntity entity) { foreach (var binaryDataPropertyName in GetPropertyNames(BINARY_DATA_PROPERTY_NAME)) { EntityProperty dataProperty; if (entity.Properties.TryGetValue(binaryDataPropertyName, out dataProperty)) { switch (dataProperty.PropertyType) { // if TablePayloadFormat.JsonNoMetadata is used case EdmType.String: var stringValue = dataProperty.StringValue; if (!string.IsNullOrEmpty(stringValue)) { yield return Convert.FromBase64String(stringValue); } break; // if any payload type providing metadata is used case EdmType.Binary: var binaryValue = dataProperty.BinaryValue; if (binaryValue != null && binaryValue.Length > 0) { yield return binaryValue; } break; } } } } private static byte[] ReadBinaryData(DynamicTableEntity entity) { var dataChunks = ReadBinaryDataChunks(entity).ToArray(); var dataSize = dataChunks.Select(d => d.Length).Sum(); var result = new byte[dataSize]; var startIndex = 0; foreach (var dataChunk in dataChunks) { Array.Copy(dataChunk, 0, result, startIndex, dataChunk.Length); startIndex += dataChunk.Length; } return result; } private static IEnumerable<string> ReadStringDataChunks(DynamicTableEntity entity) { foreach (var stringDataPropertyName in GetPropertyNames(STRING_DATA_PROPERTY_NAME)) { EntityProperty dataProperty; if (entity.Properties.TryGetValue(stringDataPropertyName, out dataProperty)) { var data = dataProperty.StringValue; if (!string.IsNullOrEmpty(data)) { yield return data; } } } } private static string ReadStringData(DynamicTableEntity entity) { return string.Join(string.Empty, ReadStringDataChunks(entity)); } /// <summary> /// Deserialize from Azure storage format /// </summary> /// <param name="entity">The Azure table entity the stored data</param> /// <param name="stateType">The state type</param> internal object ConvertFromStorageFormat(DynamicTableEntity entity, Type stateType) { var binaryData = ReadBinaryData(entity); var stringData = ReadStringData(entity); object dataValue = null; try { if (binaryData.Length > 0) { // Rehydrate dataValue = this.serializationManager.DeserializeFromByteArray<object>(binaryData); } else if (!string.IsNullOrEmpty(stringData)) { dataValue = Newtonsoft.Json.JsonConvert.DeserializeObject(stringData, stateType, this.JsonSettings); } // Else, no data found } catch (Exception exc) { var sb = new StringBuilder(); if (binaryData.Length > 0) { sb.AppendFormat("Unable to convert from storage format GrainStateEntity.Data={0}", binaryData); } else if (!string.IsNullOrEmpty(stringData)) { sb.AppendFormat("Unable to convert from storage format GrainStateEntity.StringData={0}", stringData); } if (dataValue != null) { sb.AppendFormat("Data Value={0} Type={1}", dataValue, dataValue.GetType()); } logger.Error(0, sb.ToString(), exc); throw new AggregateException(sb.ToString(), exc); } return dataValue; } private string GetKeyString(GrainReference grainReference) { var key = String.Format("{0}_{1}", this.clusterOptions.ServiceId, grainReference.ToKeyString()); return AzureTableUtils.SanitizeTableProperty(key); } internal class GrainStateRecord { public string ETag { get; set; } public DynamicTableEntity Entity { get; set; } } private class GrainStateTableDataManager { public string TableName { get; private set; } private readonly AzureTableDataManager<DynamicTableEntity> tableManager; private readonly ILogger logger; public GrainStateTableDataManager(string tableName, string storageConnectionString, ILoggerFactory loggerFactory) { this.logger = loggerFactory.CreateLogger<GrainStateTableDataManager>(); TableName = tableName; tableManager = new AzureTableDataManager<DynamicTableEntity>(tableName, storageConnectionString, loggerFactory); } public Task InitTableAsync() { return tableManager.InitTableAsync(); } public async Task<GrainStateRecord> Read(string partitionKey, string rowKey) { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_Storage_Reading, "Reading: PartitionKey={0} RowKey={1} from Table={2}", partitionKey, rowKey, TableName); try { Tuple<DynamicTableEntity, string> data = await tableManager.ReadSingleTableEntryAsync(partitionKey, rowKey).ConfigureAwait(false); if (data == null || data.Item1 == null) { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_DataNotFound, "DataNotFound reading: PartitionKey={0} RowKey={1} from Table={2}", partitionKey, rowKey, TableName); return null; } DynamicTableEntity stateEntity = data.Item1; var record = new GrainStateRecord { Entity = stateEntity, ETag = data.Item2 }; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_Storage_DataRead, "Read: PartitionKey={0} RowKey={1} from Table={2} with ETag={3}", stateEntity.PartitionKey, stateEntity.RowKey, TableName, record.ETag); return record; } catch (Exception exc) { if (AzureTableUtils.TableStorageDataNotFound(exc)) { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_DataNotFound, "DataNotFound reading (exception): PartitionKey={0} RowKey={1} from Table={2} Exception={3}", partitionKey, rowKey, TableName, LogFormatter.PrintException(exc)); return null; // No data } throw; } } public async Task Write(GrainStateRecord record) { var entity = record.Entity; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_Storage_Writing, "Writing: PartitionKey={0} RowKey={1} to Table={2} with ETag={3}", entity.PartitionKey, entity.RowKey, TableName, record.ETag); string eTag = String.IsNullOrEmpty(record.ETag) ? await tableManager.CreateTableEntryAsync(entity).ConfigureAwait(false) : await tableManager.UpdateTableEntryAsync(entity, record.ETag).ConfigureAwait(false); record.ETag = eTag; } public async Task Delete(GrainStateRecord record) { var entity = record.Entity; if (record.ETag == null) { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_DataNotFound, "Not attempting to delete non-existent persistent state: PartitionKey={0} RowKey={1} from Table={2} with ETag={3}", entity.PartitionKey, entity.RowKey, TableName, record.ETag); return; } if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_Storage_Writing, "Deleting: PartitionKey={0} RowKey={1} from Table={2} with ETag={3}", entity.PartitionKey, entity.RowKey, TableName, record.ETag); await tableManager.DeleteTableEntryAsync(entity, record.ETag).ConfigureAwait(false); record.ETag = null; } } /// <summary> Decodes Storage exceptions.</summary> public bool DecodeException(Exception e, out HttpStatusCode httpStatusCode, out string restStatus, bool getRESTErrors = false) { return AzureTableUtils.EvaluateException(e, out httpStatusCode, out restStatus, getRESTErrors); } private async Task Init(CancellationToken ct) { var stopWatch = Stopwatch.StartNew(); try { this.logger.LogInformation((int)AzureProviderErrorCode.AzureTableProvider_InitProvider, $"AzureTableGrainStorage {name} initializing: {this.options.ToString()}"); this.logger.LogInformation((int)AzureProviderErrorCode.AzureTableProvider_ParamConnectionString, $"AzureTableGrainStorage {name} is using DataConnectionString: {ConfigUtilities.RedactConnectionStringInfo(this.options.ConnectionString)}"); this.JsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(this.typeResolver, this.grainFactory), this.options.UseFullAssemblyNames, this.options.IndentJson, this.options.TypeNameHandling); this.options.ConfigureJsonSerializerSettings?.Invoke(this.JsonSettings); this.tableDataManager = new GrainStateTableDataManager(this.options.TableName, this.options.ConnectionString, this.loggerFactory); await this.tableDataManager.InitTableAsync(); stopWatch.Stop(); this.logger.LogInformation((int)AzureProviderErrorCode.AzureTableProvider_InitProvider, $"Initializing provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} took {stopWatch.ElapsedMilliseconds} Milliseconds."); } catch (Exception ex) { stopWatch.Stop(); this.logger.LogError((int)ErrorCode.Provider_ErrorFromInit, $"Initialization failed for provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} in {stopWatch.ElapsedMilliseconds} Milliseconds.", ex); throw; } } private Task Close(CancellationToken ct) { this.tableDataManager = null; return Task.CompletedTask; } public void Participate(ISiloLifecycle lifecycle) { lifecycle.Subscribe(OptionFormattingUtilities.Name<AzureTableGrainStorage>(this.name), this.options.InitStage, Init, Close); } } public static class AzureTableGrainStorageFactory { public static IGrainStorage Create(IServiceProvider services, string name) { var optionsSnapshot = services.GetRequiredService<IOptionsMonitor<AzureTableStorageOptions>>(); var clusterOptions = services.GetProviderClusterOptions(name); return ActivatorUtilities.CreateInstance<AzureTableGrainStorage>(services, name, optionsSnapshot.Get(name), clusterOptions); } } }
// 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 BlendVariableUInt16() { var test = new SimpleTernaryOpTest__BlendVariableUInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__BlendVariableUInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(UInt16[] inArray1, UInt16[] inArray2, UInt16[] inArray3, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = 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.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<UInt16, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<UInt16> _fld1; public Vector128<UInt16> _fld2; public Vector128<UInt16> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (((i % 2) == 0) ? Convert.ToUInt16("0xFFFF", 16) : (ushort)0); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld3), ref Unsafe.As<UInt16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__BlendVariableUInt16 testClass) { var result = Sse41.BlendVariable(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__BlendVariableUInt16 testClass) { fixed (Vector128<UInt16>* pFld1 = &_fld1) fixed (Vector128<UInt16>* pFld2 = &_fld2) fixed (Vector128<UInt16>* pFld3 = &_fld3) { var result = Sse41.BlendVariable( Sse2.LoadVector128((UInt16*)(pFld1)), Sse2.LoadVector128((UInt16*)(pFld2)), Sse2.LoadVector128((UInt16*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static UInt16[] _data3 = new UInt16[Op3ElementCount]; private static Vector128<UInt16> _clsVar1; private static Vector128<UInt16> _clsVar2; private static Vector128<UInt16> _clsVar3; private Vector128<UInt16> _fld1; private Vector128<UInt16> _fld2; private Vector128<UInt16> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__BlendVariableUInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (((i % 2) == 0) ? Convert.ToUInt16("0xFFFF", 16) : (ushort)0); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar3), ref Unsafe.As<UInt16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); } public SimpleTernaryOpTest__BlendVariableUInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (((i % 2) == 0) ? Convert.ToUInt16("0xFFFF", 16) : (ushort)0); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld3), ref Unsafe.As<UInt16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (((i % 2) == 0) ? Convert.ToUInt16("0xFFFF", 16) : (ushort)0); } _dataTable = new DataTable(_data1, _data2, _data3, new UInt16[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.BlendVariable( Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.BlendVariable( Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)), Sse2.LoadVector128((UInt16*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.BlendVariable( Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)), Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)), Sse2.LoadVector128((UInt16*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)), Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.BlendVariable( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt16>* pClsVar1 = &_clsVar1) fixed (Vector128<UInt16>* pClsVar2 = &_clsVar2) fixed (Vector128<UInt16>* pClsVar3 = &_clsVar3) { var result = Sse41.BlendVariable( Sse2.LoadVector128((UInt16*)(pClsVar1)), Sse2.LoadVector128((UInt16*)(pClsVar2)), Sse2.LoadVector128((UInt16*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray3Ptr); var result = Sse41.BlendVariable(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)); var op3 = Sse2.LoadVector128((UInt16*)(_dataTable.inArray3Ptr)); var result = Sse41.BlendVariable(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)); var op3 = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray3Ptr)); var result = Sse41.BlendVariable(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__BlendVariableUInt16(); var result = Sse41.BlendVariable(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__BlendVariableUInt16(); fixed (Vector128<UInt16>* pFld1 = &test._fld1) fixed (Vector128<UInt16>* pFld2 = &test._fld2) fixed (Vector128<UInt16>* pFld3 = &test._fld3) { var result = Sse41.BlendVariable( Sse2.LoadVector128((UInt16*)(pFld1)), Sse2.LoadVector128((UInt16*)(pFld2)), Sse2.LoadVector128((UInt16*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.BlendVariable(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt16>* pFld1 = &_fld1) fixed (Vector128<UInt16>* pFld2 = &_fld2) fixed (Vector128<UInt16>* pFld3 = &_fld3) { var result = Sse41.BlendVariable( Sse2.LoadVector128((UInt16*)(pFld1)), Sse2.LoadVector128((UInt16*)(pFld2)), Sse2.LoadVector128((UInt16*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.BlendVariable(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse41.BlendVariable( Sse2.LoadVector128((UInt16*)(&test._fld1)), Sse2.LoadVector128((UInt16*)(&test._fld2)), Sse2.LoadVector128((UInt16*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _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(Vector128<UInt16> op1, Vector128<UInt16> op2, Vector128<UInt16> op3, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] inArray3 = new UInt16[Op3ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] inArray3 = new UInt16[Op3ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(UInt16[] firstOp, UInt16[] secondOp, UInt16[] thirdOp, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((thirdOp[0] != 0) ? secondOp[0] != result[0] : firstOp[0] != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((thirdOp[i] != 0) ? secondOp[i] != result[i] : firstOp[i] != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.BlendVariable)}<UInt16>(Vector128<UInt16>, Vector128<UInt16>, Vector128<UInt16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using OpenTK; using OpenTK.Graphics; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.MathUtils; using osu.Framework.Testing; namespace osu.Framework.Tests.Visual { public class TestCaseGridContainer : TestCase { private readonly GridContainer grid; public TestCaseGridContainer() { Add(new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Both, Size = new Vector2(0.5f), Masking = true, BorderColour = Color4.White, BorderThickness = 2, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Alpha = 0, AlwaysPresent = true }, grid = new GridContainer { RelativeSizeAxes = Axes.Both } } }); AddStep("Blank grid", reset); AddStep("1-cell (auto)", () => { reset(); grid.Content = new[] { new Drawable[] { new FillBox() } }; }); AddStep("1-cell (absolute)", () => { reset(); grid.Content = new[] { new Drawable[] { new FillBox() } }; grid.RowDimensions = grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.Absolute, 100) }; }); AddStep("1-cell (relative)", () => { reset(); grid.Content = new [] { new Drawable[] { new FillBox() } }; grid.RowDimensions = grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.Relative, 0.5f) }; }); AddStep("1-cell (mixed)", () => { reset(); grid.Content = new [] { new Drawable[] { new FillBox() } }; grid.RowDimensions = new[] { new Dimension(GridSizeMode.Absolute, 100) }; grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.Relative, 0.5f) }; }); AddStep("1-cell (mixed) 2", () => { reset(); grid.Content = new [] { new Drawable[] { new FillBox() } }; grid.RowDimensions = new [] { new Dimension(GridSizeMode.Relative, 0.5f) }; }); AddStep("3-cell row (auto)", () => { reset(); grid.Content = new [] { new Drawable[] { new FillBox(), new FillBox(), new FillBox() } }; }); AddStep("3-cell row (absolute)", () => { reset(); grid.Content = new [] { new Drawable[] { new FillBox(), new FillBox(), new FillBox() } }; grid.RowDimensions = grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.Absolute, 50), new Dimension(GridSizeMode.Absolute, 100), new Dimension(GridSizeMode.Absolute, 150) }; }); AddStep("3-cell row (relative)", () => { reset(); grid.Content = new [] { new Drawable[] { new FillBox(), new FillBox(), new FillBox() } }; grid.RowDimensions = grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.Relative, 0.1f), new Dimension(GridSizeMode.Relative, 0.2f), new Dimension(GridSizeMode.Relative, 0.3f) }; }); AddStep("3-cell row (mixed)", () => { reset(); grid.Content = new [] { new Drawable[] { new FillBox(), new FillBox(), new FillBox() } }; grid.RowDimensions = grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.Absolute, 50), new Dimension(GridSizeMode.Relative, 0.2f) }; }); AddStep("3-cell column (auto)", () => { reset(); grid.Content = new[] { new Drawable[] { new FillBox() }, new Drawable[] { new FillBox() }, new Drawable[] { new FillBox() } }; }); AddStep("3-cell column (absolute)", () => { reset(); grid.Content = new[] { new Drawable[] { new FillBox() }, new Drawable[] { new FillBox() }, new Drawable[] { new FillBox() } }; grid.RowDimensions = grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.Absolute, 50), new Dimension(GridSizeMode.Absolute, 100), new Dimension(GridSizeMode.Absolute, 150) }; }); AddStep("3-cell column (relative)", () => { reset(); grid.Content = new[] { new Drawable[] { new FillBox() }, new Drawable[] { new FillBox() }, new Drawable[] { new FillBox() } }; grid.RowDimensions = grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.Relative, 0.1f), new Dimension(GridSizeMode.Relative, 0.2f), new Dimension(GridSizeMode.Relative, 0.3f) }; }); AddStep("3-cell column (mixed)", () => { reset(); grid.Content = new[] { new Drawable[] { new FillBox() }, new Drawable[] { new FillBox() }, new Drawable[] { new FillBox() } }; grid.RowDimensions = grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.Absolute, 50), new Dimension(GridSizeMode.Relative, 0.2f) }; }); AddStep("3x3-cell (auto)", () => { reset(); grid.Content = new[] { new Drawable[] { new FillBox(), new FillBox(), new FillBox() }, new Drawable[] { new FillBox(), new FillBox(), new FillBox() }, new Drawable[] { new FillBox(), new FillBox(), new FillBox() } }; }); AddStep("3x3-cell (absolute)", () => { reset(); grid.Content = new[] { new Drawable[] { new FillBox(), new FillBox(), new FillBox() }, new Drawable[] { new FillBox(), new FillBox(), new FillBox() }, new Drawable[] { new FillBox(), new FillBox(), new FillBox() } }; grid.RowDimensions = grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.Absolute, 50), new Dimension(GridSizeMode.Absolute, 100), new Dimension(GridSizeMode.Absolute, 150) }; }); AddStep("3x3-cell (relative)", () => { reset(); grid.Content = new[] { new Drawable[] { new FillBox(), new FillBox(), new FillBox() }, new Drawable[] { new FillBox(), new FillBox(), new FillBox() }, new Drawable[] { new FillBox(), new FillBox(), new FillBox() } }; grid.RowDimensions = grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.Relative, 0.1f), new Dimension(GridSizeMode.Relative, 0.2f), new Dimension(GridSizeMode.Relative, 0.3f) }; }); AddStep("3x3-cell (mixed)", () => { reset(); grid.Content = new[] { new Drawable[] { new FillBox(), new FillBox(), new FillBox() }, new Drawable[] { new FillBox(), new FillBox(), new FillBox() }, new Drawable[] { new FillBox(), new FillBox(), new FillBox() } }; grid.RowDimensions = grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.Absolute, 50), new Dimension(GridSizeMode.Relative, 0.2f) }; }); AddStep("Larger sides", () => { reset(); grid.Content = new[] { new Drawable[] { new FillBox(), new FillBox(), new FillBox() }, new Drawable[] { new FillBox(), new FillBox(), new FillBox() }, new Drawable[] { new FillBox(), new FillBox(), new FillBox() } }; grid.ColumnDimensions = grid.RowDimensions = new[] { new Dimension(GridSizeMode.Relative, 0.4f), new Dimension(), new Dimension(GridSizeMode.Relative, 0.4f) }; }); AddStep("Separated", () => { reset(); grid.Content = new[] { new Drawable[] { new FillBox(), null, new FillBox() }, null, new Drawable[] { new FillBox(), null, new FillBox() } }; }); AddStep("Separated 2", () => { reset(); grid.Content = new[] { new Drawable[] { new FillBox(), null, new FillBox(), null }, null, new Drawable[] { new FillBox(), null, new FillBox(), null }, null }; }); AddStep("Nested grids", () => { reset(); grid.Content = new[] { new Drawable[] { new FillBox(), new GridContainer { RelativeSizeAxes = Axes.Both, Content = new[] { new Drawable[] { new FillBox(), new FillBox() }, new Drawable[] { new FillBox(), new GridContainer { RelativeSizeAxes = Axes.Both, Content = new[] { new Drawable[] { new FillBox(), new FillBox() }, new Drawable[] { new FillBox(), new FillBox() } } } } } }, new FillBox() } }; }); AddStep("Auto size", () => { reset(); grid.Content = new[] { new Drawable[] { new Box { Size = new Vector2(30) }, new FillBox(), new FillBox() }, new Drawable[] { new FillBox(), new FillBox(), new FillBox() }, new Drawable[] { new FillBox(), new FillBox(), new FillBox() } }; grid.RowDimensions = new[] { new Dimension(GridSizeMode.AutoSize), new Dimension(GridSizeMode.Relative, 0.5f) }; grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.AutoSize), new Dimension(GridSizeMode.Relative, 0.5f) }; }); AddStep("Autosizing child", () => { reset(); grid.Content = new[] { new Drawable[] { new FillFlowContainer { AutoSizeAxes = Axes.Both, Child = new Box { Size = new Vector2(100, 50) } }, new FillBox() } }; grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.AutoSize) }; }); } private void reset() { grid.ClearInternal(); grid.RowDimensions = grid.ColumnDimensions = new Dimension[] { }; } private class FillBox : Box { public FillBox() { RelativeSizeAxes = Axes.Both; Colour = new Color4(RNG.NextSingle(1), RNG.NextSingle(1), RNG.NextSingle(1), 1); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using System.Web; using System.Web.Script.Serialization; using DotNetNuke.Entities.Portals; using DotNetNuke.Services.FileSystem; using DNNConnect.CKEditorProvider.Objects; using DNNConnect.CKEditorProvider.Utilities; namespace DNNConnect.CKEditorProvider.Browser { /// <summary> /// The File Upload Handler /// </summary> public class FileUploader : IHttpHandler { /// <summary> /// The JavaScript Serializer /// </summary> private readonly JavaScriptSerializer js = new JavaScriptSerializer(); /// <summary> /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler" /> instance. /// </summary> public bool IsReusable { get { return false; } } /// <summary> /// Gets a value indicating whether [override files]. /// </summary> /// <value> /// <c>true</c> if [override files]; otherwise, <c>false</c>. /// </value> private bool OverrideFiles { get { return HttpContext.Current.Request["overrideFiles"].Equals("1") || HttpContext.Current.Request["overrideFiles"].Equals( "true", StringComparison.InvariantCultureIgnoreCase); } } /// <summary> /// Gets the storage folder. /// </summary> /// <value> /// The storage folder. /// </value> private IFolderInfo StorageFolder { get { return FolderManager.Instance.GetFolder(Convert.ToInt32(HttpContext.Current.Request["storageFolderID"])); } } /* /// <summary> /// Gets the storage folder. /// </summary> /// <value> /// The storage folder. /// </value> private PortalSettings PortalSettings { get { return new PortalSettings(Convert.ToInt32(HttpContext.Current.Request["portalID"])); } }*/ /// <summary> /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler" /> interface. /// </summary> /// <param name="context">An <see cref="T:System.Web.HttpContext" /> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param> public void ProcessRequest(HttpContext context) { context.Response.AddHeader("Pragma", "no-cache"); context.Response.AddHeader("Cache-Control", "private, no-cache"); this.HandleMethod(context); } /// <summary> /// Returns the options. /// </summary> /// <param name="context">The context.</param> private static void ReturnOptions(HttpContext context) { context.Response.AddHeader("Allow", "DELETE,GET,HEAD,POST,PUT,OPTIONS"); context.Response.StatusCode = 200; } /// <summary> /// Handle request based on method /// </summary> /// <param name="context">The context.</param> private void HandleMethod(HttpContext context) { switch (context.Request.HttpMethod) { case "HEAD": case "GET": /*if (GivenFilename(context)) { this.DeliverFile(context); } else { ListCurrentFiles(context); }*/ break; case "POST": case "PUT": this.UploadFile(context); break; case "OPTIONS": ReturnOptions(context); break; default: context.Response.ClearHeaders(); context.Response.StatusCode = 405; break; } } /// <summary> /// Uploads the file. /// </summary> /// <param name="context">The context.</param> private void UploadFile(HttpContext context) { var statuses = new List<FilesUploadStatus>(); this.UploadWholeFile(context, statuses); this.WriteJsonIframeSafe(context, statuses); } /// <summary> /// Uploads the whole file. /// </summary> /// <param name="context">The context.</param> /// <param name="statuses">The statuses.</param> private void UploadWholeFile(HttpContext context, List<FilesUploadStatus> statuses) { for (int i = 0; i < context.Request.Files.Count; i++) { var file = context.Request.Files[i]; var fileName = Path.GetFileName(file.FileName); if (!string.IsNullOrEmpty(fileName)) { // Replace dots in the name with underscores (only one dot can be there... security issue). fileName = Regex.Replace(fileName, @"\.(?![^.]*$)", "_", RegexOptions.None); // Check for Illegal Chars if (Utility.ValidateFileName(fileName)) { fileName = Utility.CleanFileName(fileName); } // Convert Unicode Chars fileName = Utility.ConvertUnicodeChars(fileName); } else { throw new HttpRequestValidationException("File does not have a name"); } if (fileName.Length > 220) { fileName = fileName.Substring(fileName.Length - 220); } var fileNameNoExtenstion = Path.GetFileNameWithoutExtension(fileName); // Rename File if Exists if (!this.OverrideFiles) { var counter = 0; while (File.Exists(Path.Combine(this.StorageFolder.PhysicalPath, fileName))) { counter++; fileName = string.Format( "{0}_{1}{2}", fileNameNoExtenstion, counter, Path.GetExtension(file.FileName)); } } FileManager.Instance.AddFile(this.StorageFolder, fileName, file.InputStream, this.OverrideFiles); var fullName = Path.GetFileName(fileName); statuses.Add(new FilesUploadStatus(fullName, file.ContentLength)); } } /// <summary> /// Writes the JSON iFrame safe. /// </summary> /// <param name="context">The context.</param> /// <param name="statuses">The statuses.</param> private void WriteJsonIframeSafe(HttpContext context, List<FilesUploadStatus> statuses) { context.Response.AddHeader("Vary", "Accept"); try { context.Response.ContentType = context.Request["HTTP_ACCEPT"].Contains("application/json") ? "application/json" : "text/plain"; } catch { context.Response.ContentType = "text/plain"; } var jsonObj = this.js.Serialize(statuses.ToArray()); context.Response.Write(jsonObj); } } }
using Shouldly; using System; using Xunit; namespace Valit.Tests.Float { public class Float_IsLessThan_Tests { [Fact] public void Float_IsLessThan_For_Not_Nullable_Values_Throws_When_Null_Rule_Is_Given() { var exception = Record.Exception(() => { ((IValitRule<Model, float>)null) .IsLessThan(1); }); exception.ShouldBeOfType(typeof(ValitException)); } [Fact] public void Float_IsLessThan_For_Not_Nullable_Value_And_Nullable_Value_Throws_When_Null_Rule_Is_Given() { var exception = Record.Exception(() => { ((IValitRule<Model, float>)null) .IsLessThan((float?)1); }); exception.ShouldBeOfType(typeof(ValitException)); } [Theory] [InlineData(11, false)] [InlineData(Single.NaN, false)] public void Float_IsLessThan_Returns_Proper_Results_For_NaN_And_Value(float value, bool expected) { IValitResult result = ValitRules<Model> .Create() .Ensure(m => m.NaN, _ => _ .IsLessThan(value)) .For(_model) .Validate(); result.Succeeded.ShouldBe(expected); } [Theory] [InlineData(11, false)] [InlineData(Single.NaN, false)] public void Float_IsLessThan_Returns_Proper_Results_For_NaN_And_NullableValue(float? value, bool expected) { IValitResult result = ValitRules<Model> .Create() .Ensure(m => m.NaN, _ => _ .IsLessThan(value)) .For(_model) .Validate(); result.Succeeded.ShouldBe(expected); } [Theory] [InlineData(11, false)] [InlineData(Single.NaN, false)] public void Float_IsLessThan_Returns_Proper_Results_For_NullableNaN_And_Value(float value, bool expected) { IValitResult result = ValitRules<Model> .Create() .Ensure(m => m.NullableNaN, _ => _ .IsLessThan(value)) .For(_model) .Validate(); result.Succeeded.ShouldBe(expected); } [Theory] [InlineData(11, false)] [InlineData(Single.NaN, false)] public void Float_IsLessThan_Returns_Proper_Results_For_NullableNaN_And_NullableValue(float? value, bool expected) { IValitResult result = ValitRules<Model> .Create() .Ensure(m => m.NullableNaN, _ => _ .IsLessThan(value)) .For(_model) .Validate(); result.Succeeded.ShouldBe(expected); } [Fact] public void Float_IsLessThan_For_Nullable_Value_And_Not_Nullable_Value_Throws_When_Null_Rule_Is_Given() { var exception = Record.Exception(() => { ((IValitRule<Model, float?>)null) .IsLessThan(1); }); exception.ShouldBeOfType(typeof(ValitException)); } [Fact] public void Float_IsLessThan_For_Nullable_Values_Throws_When_Null_Rule_Is_Given() { var exception = Record.Exception(() => { ((IValitRule<Model, float?>)null) .IsLessThan((float?)1); }); exception.ShouldBeOfType(typeof(ValitException)); } [Theory] [InlineData(11, true)] [InlineData(10, false)] [InlineData(9, false)] [InlineData(Single.NaN, false)] public void Float_IsLessThan_Returns_Proper_Results_For_Not_Nullable_Values(float value, bool expected) { IValitResult result = ValitRules<Model> .Create() .Ensure(m => m.Value, _ => _ .IsLessThan(value)) .For(_model) .Validate(); result.Succeeded.ShouldBe(expected); } [Theory] [InlineData((float)11, true)] [InlineData((float)10, false)] [InlineData((float)9, false)] [InlineData(Single.NaN, false)] [InlineData(null, false)] public void Float_IsLessThan_Returns_Proper_Results_For_Not_Nullable_Value_And_Nullable_Value(float? value, bool expected) { IValitResult result = ValitRules<Model> .Create() .Ensure(m => m.Value, _ => _ .IsLessThan(value)) .For(_model) .Validate(); result.Succeeded.ShouldBe(expected); } [Theory] [InlineData(false, 11, true)] [InlineData(false, 10, false)] [InlineData(false, 9, false)] [InlineData(true, 10, false)] [InlineData(false, Single.NaN, false)] [InlineData(true, Single.NaN, false)] public void Float_IsLessThan_Returns_Proper_Results_For_Nullable_Value_And_Not_Nullable_Value(bool useNullValue, float value, bool expected) { IValitResult result = ValitRules<Model> .Create() .Ensure(m => useNullValue ? m.NullValue : m.NullableValue, _ => _ .IsLessThan(value)) .For(_model) .Validate(); result.Succeeded.ShouldBe(expected); } [Theory] [InlineData(false, (float)11, true)] [InlineData(false, (float)10, false)] [InlineData(false, (float)9, false)] [InlineData(false, Single.NaN, false)] [InlineData(false, null, false)] [InlineData(true, (float)10, false)] [InlineData(true, Single.NaN, false)] [InlineData(true, null, false)] public void Float_IsLessThan_Returns_Proper_Results_For_Nullable_Values(bool useNullValue, float? value, bool expected) { IValitResult result = ValitRules<Model> .Create() .Ensure(m => useNullValue ? m.NullValue : m.NullableValue, _ => _ .IsLessThan(value)) .For(_model) .Validate(); result.Succeeded.ShouldBe(expected); } #region ARRANGE public Float_IsLessThan_Tests() { _model = new Model(); } private readonly Model _model; class Model { public float Value => 10; public float NaN => Single.NaN; public float? NullableValue => 10; public float? NullValue => null; public float? NullableNaN => Single.NaN; } #endregion } }
// // Mono.System.Xml.XmlDocument // // Authors: // Daniel Weber ([email protected]) // Kral Ferch <[email protected]> // Jason Diamond <[email protected]> // Miguel de Icaza ([email protected]) // Duncan Mak ([email protected]) // Atsushi Enomoto ([email protected]) // // (C) 2001 Daniel Weber // (C) 2002 Kral Ferch, Jason Diamond, Miguel de Icaza, Duncan Mak, // Atsushi Enomoto // Copyright (C) 2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Globalization; using System.IO; using System.Security.Permissions; using System.Text; using Mono.System.Xml.XPath; using System.Diagnostics; using System.Collections; using Mono.Xml; #if NET_2_0 using Mono.System.Xml.Schema; //using Mono.Xml.XPath; #endif namespace Mono.System.Xml { public class XmlDocument : XmlNode, IHasXmlChildNode { #region Fields static readonly Type [] optimal_create_types = new Type [] {typeof (string), typeof (string), typeof (string)}; bool optimal_create_element, optimal_create_attribute; XmlNameTable nameTable; string baseURI = String.Empty; XmlImplementation implementation; bool preserveWhitespace = false; XmlResolver resolver; Hashtable idTable = new Hashtable (); XmlNameEntryCache nameCache; XmlLinkedNode lastLinkedChild; XmlAttribute nsNodeXml; #if NET_2_0 XmlSchemaSet schemas; IXmlSchemaInfo schemaInfo; #endif // MS.NET rejects undeclared entities _only_ during Load(), // while ReadNode() never rejects such node. So it signs // whether we are on Load() or not (MS.NET uses Loader class, // but we don't have to implement Load() as such) bool loadMode; #endregion #region Constructors public XmlDocument () : this (null, null) { } protected internal XmlDocument (XmlImplementation imp) : this (imp, null) { } public XmlDocument (XmlNameTable nt) : this (null, nt) { } XmlDocument (XmlImplementation impl, XmlNameTable nt) : base (null) { if (impl == null) implementation = new XmlImplementation (); else implementation = impl; nameTable = (nt != null) ? nt : implementation.InternalNameTable; nameCache = new XmlNameEntryCache (nameTable); AddDefaultNameTableKeys (); resolver = new XmlUrlResolver (); Type type = GetType (); optimal_create_element = type.GetMethod ("CreateElement", optimal_create_types).DeclaringType == typeof (XmlDocument); optimal_create_attribute = type.GetMethod ("CreateAttribute", optimal_create_types).DeclaringType == typeof (XmlDocument); } #endregion #region Events public event XmlNodeChangedEventHandler NodeChanged; public event XmlNodeChangedEventHandler NodeChanging; public event XmlNodeChangedEventHandler NodeInserted; public event XmlNodeChangedEventHandler NodeInserting; public event XmlNodeChangedEventHandler NodeRemoved; public event XmlNodeChangedEventHandler NodeRemoving; #endregion #region Properties internal XmlAttribute NsNodeXml { get { if (nsNodeXml == null) { nsNodeXml = CreateAttribute ("xmlns", "xml", "http://www.w3.org/2000/xmlns/"); nsNodeXml.Value = "http://www.w3.org/XML/1998/namespace"; } return nsNodeXml; } } XmlLinkedNode IHasXmlChildNode.LastLinkedChild { get { return lastLinkedChild; } set { lastLinkedChild = value; } } public override string BaseURI { get { return baseURI; } } public XmlElement DocumentElement { get { XmlNode node = FirstChild; while (node != null) { if (node is XmlElement) break; node = node.NextSibling; } return node != null ? node as XmlElement : null; } } public virtual XmlDocumentType DocumentType { get { for (XmlNode n = FirstChild; n != null; n = n.NextSibling) { if (n.NodeType == XmlNodeType.DocumentType) return (XmlDocumentType) n; else if (n.NodeType == XmlNodeType.Element) // document element return null; } return null; } } public XmlImplementation Implementation { get { return implementation; } } #if NET_4_0 public override string InnerText { set { throw new InvalidOperationException (); } } #endif public override string InnerXml { get { return base.InnerXml; } set { // reason for overriding this.LoadXml (value); } } public override bool IsReadOnly { get { return false; } } internal bool IsStandalone { get { return FirstChild != null && FirstChild.NodeType == XmlNodeType.XmlDeclaration && ((XmlDeclaration) this.FirstChild).Standalone == "yes"; } } public override string LocalName { get { return "#document"; } } public override string Name { get { return "#document"; } } internal XmlNameEntryCache NameCache { get { return nameCache; } } public XmlNameTable NameTable { get { return nameTable; } } public override XmlNodeType NodeType { get { return XmlNodeType.Document; } } internal override XPathNodeType XPathNodeType { get { return XPathNodeType.Root; } } public override XmlDocument OwnerDocument { get { return null; } } public bool PreserveWhitespace { get { return preserveWhitespace; } set { preserveWhitespace = value; } } internal XmlResolver Resolver { get { return resolver; } } internal override string XmlLang { get { return String.Empty; } } public virtual XmlResolver XmlResolver { set { resolver = value; } } internal override XmlSpace XmlSpace { get { return XmlSpace.None; } } internal Encoding TextEncoding { get { XmlDeclaration dec = FirstChild as XmlDeclaration; if (dec == null || dec.Encoding == "") return null; return Encoding.GetEncoding (dec.Encoding); } } #if NET_2_0 public override XmlNode ParentNode { get { return null; } } public XmlSchemaSet Schemas { get { if (schemas == null) schemas = new XmlSchemaSet (); return schemas; } set { schemas = value; } } public override IXmlSchemaInfo SchemaInfo { get { return schemaInfo; } internal set { schemaInfo = value; } } #endif #endregion #region Methods internal void AddIdenticalAttribute (XmlAttribute attr) { idTable [attr.Value] = attr; } public override XmlNode CloneNode (bool deep) { XmlDocument doc = implementation != null ? implementation.CreateDocument () : new XmlDocument (); doc.baseURI = baseURI; if(deep) { for (XmlNode n = FirstChild; n != null; n = n.NextSibling) doc.AppendChild (doc.ImportNode (n, deep), false); } return doc; } public XmlAttribute CreateAttribute (string name) { string prefix; string localName; string namespaceURI = String.Empty; ParseName (name, out prefix, out localName); if (prefix == "xmlns" || (prefix == "" && localName == "xmlns")) namespaceURI = XmlNamespaceManager.XmlnsXmlns; else if (prefix == "xml") namespaceURI = XmlNamespaceManager.XmlnsXml; return CreateAttribute (prefix, localName, namespaceURI ); } public XmlAttribute CreateAttribute (string qualifiedName, string namespaceURI) { string prefix; string localName; ParseName (qualifiedName, out prefix, out localName); return CreateAttribute (prefix, localName, namespaceURI); } public virtual XmlAttribute CreateAttribute (string prefix, string localName, string namespaceURI) { if ((localName == null) || (localName == String.Empty)) throw new ArgumentException ("The attribute local name cannot be empty."); return new XmlAttribute (prefix, localName, namespaceURI, this, false, true); } internal XmlAttribute CreateAttribute (string prefix, string localName, string namespaceURI, bool atomizedNames, bool checkNamespace) { if (optimal_create_attribute) return new XmlAttribute (prefix, localName, namespaceURI, this, atomizedNames, checkNamespace); else return CreateAttribute (prefix, localName, namespaceURI); } public virtual XmlCDataSection CreateCDataSection (string data) { return new XmlCDataSection (data, this); } public virtual XmlComment CreateComment (string data) { return new XmlComment (data, this); } protected internal virtual XmlAttribute CreateDefaultAttribute (string prefix, string localName, string namespaceURI) { XmlAttribute attr = CreateAttribute (prefix, localName, namespaceURI); attr.isDefault = true; return attr; } public virtual XmlDocumentFragment CreateDocumentFragment () { return new XmlDocumentFragment (this); } [PermissionSet (SecurityAction.InheritanceDemand, Unrestricted = true)] public virtual XmlDocumentType CreateDocumentType (string name, string publicId, string systemId, string internalSubset) { return new XmlDocumentType (name, publicId, systemId, internalSubset, this); } private XmlDocumentType CreateDocumentType (DTDObjectModel dtd) { return new XmlDocumentType (dtd, this); } public XmlElement CreateElement (string name) { return CreateElement (name, String.Empty); } public XmlElement CreateElement ( string qualifiedName, string namespaceURI) { string prefix; string localName; ParseName (qualifiedName, out prefix, out localName); return CreateElement (prefix, localName, namespaceURI); } public virtual XmlElement CreateElement ( string prefix, string localName, string namespaceURI) { // LAMESPEC: MS.NET has a weird behavior that they can Load() from XmlTextReader // whose Namespaces = false, but their CreateElement() never allows qualified name. // I leave it as it is. return new XmlElement (prefix != null ? prefix : String.Empty, localName, namespaceURI != null ? namespaceURI : String.Empty, this, false); } internal XmlElement CreateElement ( string prefix, string localName, string namespaceURI, bool nameAtomized) { if ((localName == null) || (localName == String.Empty)) throw new ArgumentException ("The local name for elements or attributes cannot be null or an empty string."); if (optimal_create_element) // LAMESPEC: MS.NET has a weird behavior that they can Load() from XmlTextReader // whose Namespaces = false, but their CreateElement() never allows qualified name. // I leave it as it is. return new XmlElement (prefix != null ? prefix : String.Empty, localName, namespaceURI != null ? namespaceURI : String.Empty, this, nameAtomized); else return CreateElement (prefix, localName, namespaceURI); } public virtual XmlEntityReference CreateEntityReference (string name) { return new XmlEntityReference (name, this); } #if NET_2_0 //public override XPathNavigator CreateNavigator () //{ // return CreateNavigator (this); //} #endif //protected internal virtual XPathNavigator CreateNavigator (XmlNode node) //{ #if NET_2_0 // return new XPathEditableDocument (node).CreateNavigator (); #else // return new XmlDocumentNavigator (node); #endif //} public virtual XmlNode CreateNode ( string nodeTypeString, string name, string namespaceURI) { return CreateNode (GetNodeTypeFromString (nodeTypeString), name, namespaceURI); } public virtual XmlNode CreateNode ( XmlNodeType type, string name, string namespaceURI) { string prefix = null; string localName = name; if ((type == XmlNodeType.Attribute) || (type == XmlNodeType.Element) || (type == XmlNodeType.EntityReference)) ParseName (name, out prefix, out localName); return CreateNode (type, prefix, localName, namespaceURI); } public virtual XmlNode CreateNode ( XmlNodeType type, string prefix, string name, string namespaceURI) { switch (type) { case XmlNodeType.Attribute: return CreateAttribute (prefix, name, namespaceURI); case XmlNodeType.CDATA: return CreateCDataSection (null); case XmlNodeType.Comment: return CreateComment (null); case XmlNodeType.Document: return new XmlDocument (); case XmlNodeType.DocumentFragment: return CreateDocumentFragment (); case XmlNodeType.DocumentType: return CreateDocumentType (null, null, null, null); case XmlNodeType.Element: return CreateElement (prefix, name, namespaceURI); case XmlNodeType.EntityReference: return CreateEntityReference (null); case XmlNodeType.ProcessingInstruction: return CreateProcessingInstruction (null, null); case XmlNodeType.SignificantWhitespace: return CreateSignificantWhitespace (String.Empty); case XmlNodeType.Text: return CreateTextNode (null); case XmlNodeType.Whitespace: return CreateWhitespace (String.Empty); case XmlNodeType.XmlDeclaration: return CreateXmlDeclaration ("1.0", null, null); default: #if NET_2_0 throw new ArgumentException ( #else // makes less sense throw new ArgumentOutOfRangeException ( #endif String.Format("{0}\nParameter name: {1}", "Specified argument was out of the range of valid values", type.ToString ())); } } public virtual XmlProcessingInstruction CreateProcessingInstruction ( string target, string data) { return new XmlProcessingInstruction (target, data, this); } public virtual XmlSignificantWhitespace CreateSignificantWhitespace (string text) { if (!XmlChar.IsWhitespace (text)) throw new ArgumentException ("Invalid whitespace characters."); return new XmlSignificantWhitespace (text, this); } public virtual XmlText CreateTextNode (string text) { return new XmlText (text, this); } public virtual XmlWhitespace CreateWhitespace (string text) { if (!XmlChar.IsWhitespace (text)) throw new ArgumentException ("Invalid whitespace characters."); return new XmlWhitespace (text, this); } public virtual XmlDeclaration CreateXmlDeclaration (string version, string encoding, string standalone) { if (version != "1.0") throw new ArgumentException ("version string is not correct."); if ((standalone != null && standalone != String.Empty) && !((standalone == "yes") || (standalone == "no"))) throw new ArgumentException ("standalone string is not correct."); return new XmlDeclaration (version, encoding, standalone, this); } // FIXME: Currently XmlAttributeCollection.SetNamedItem() does // add to the identity table, but in fact I delayed identity // check on GetIdenticalAttribute. To make such way complete, // we have to use MultiMap, not Hashtable. // // Well, MS.NET is also fragile around here. public virtual XmlElement GetElementById (string elementId) { XmlAttribute attr = GetIdenticalAttribute (elementId); return attr != null ? attr.OwnerElement : null; } public virtual XmlNodeList GetElementsByTagName (string name) { ArrayList nodeArrayList = new ArrayList (); this.SearchDescendantElements (name, name == "*", nodeArrayList); return new XmlNodeArrayList (nodeArrayList); } public virtual XmlNodeList GetElementsByTagName (string localName, string namespaceURI) { ArrayList nodeArrayList = new ArrayList (); this.SearchDescendantElements (localName, localName == "*", namespaceURI, namespaceURI == "*", nodeArrayList); return new XmlNodeArrayList (nodeArrayList); } private XmlNodeType GetNodeTypeFromString (string nodeTypeString) { #if NET_2_0 // actually should be done in any version if (nodeTypeString == null) throw new ArgumentNullException ("nodeTypeString"); #endif switch (nodeTypeString) { case "attribute": return XmlNodeType.Attribute; case "cdatasection": return XmlNodeType.CDATA; case "comment": return XmlNodeType.Comment; case "document": return XmlNodeType.Document; case "documentfragment": return XmlNodeType.DocumentFragment; case "documenttype": return XmlNodeType.DocumentType; case "element": return XmlNodeType.Element; case "entityreference": return XmlNodeType.EntityReference; case "processinginstruction": return XmlNodeType.ProcessingInstruction; case "significantwhitespace": return XmlNodeType.SignificantWhitespace; case "text": return XmlNodeType.Text; case "whitespace": return XmlNodeType.Whitespace; default: throw new ArgumentException(String.Format("The string doesn't represent any node type : {0}.", nodeTypeString)); } } internal XmlAttribute GetIdenticalAttribute (string id) { XmlAttribute attr = this.idTable [id] as XmlAttribute; if (attr == null) return null; if (attr.OwnerElement == null || !attr.OwnerElement.IsRooted) { // idTable.Remove (id); return null; } return attr; } public virtual XmlNode ImportNode (XmlNode node, bool deep) { if (node == null) throw new NullReferenceException ("Null node cannot be imported."); switch (node.NodeType) { case XmlNodeType.Attribute: XmlAttribute srcAtt = node as XmlAttribute; XmlAttribute dstAtt = this.CreateAttribute (srcAtt.Prefix, srcAtt.LocalName, srcAtt.NamespaceURI); for (XmlNode n = srcAtt.FirstChild; n != null; n = n.NextSibling) dstAtt.AppendChild (this.ImportNode (n, deep)); return dstAtt; case XmlNodeType.CDATA: return this.CreateCDataSection (node.Value); case XmlNodeType.Comment: return this.CreateComment (node.Value); case XmlNodeType.Document: throw new XmlException ("Document cannot be imported."); case XmlNodeType.DocumentFragment: XmlDocumentFragment df = this.CreateDocumentFragment (); if(deep) for (XmlNode n = node.FirstChild; n != null; n = n.NextSibling) df.AppendChild (this.ImportNode (n, deep)); return df; case XmlNodeType.DocumentType: return ((XmlDocumentType) node).CloneNode (deep); case XmlNodeType.Element: XmlElement src = (XmlElement)node; XmlElement dst = this.CreateElement (src.Prefix, src.LocalName, src.NamespaceURI); for (int i = 0; i < src.Attributes.Count; i++) { XmlAttribute attr = src.Attributes [i]; if(attr.Specified) // copies only specified attributes dst.SetAttributeNode ((XmlAttribute) this.ImportNode (attr, deep)); } if(deep) for (XmlNode n = src.FirstChild; n != null; n = n.NextSibling) dst.AppendChild (this.ImportNode (n, deep)); return dst; case XmlNodeType.EndElement: throw new XmlException ("Illegal ImportNode call for NodeType.EndElement"); case XmlNodeType.EndEntity: throw new XmlException ("Illegal ImportNode call for NodeType.EndEntity"); case XmlNodeType.EntityReference: return this.CreateEntityReference (node.Name); case XmlNodeType.None: throw new XmlException ("Illegal ImportNode call for NodeType.None"); case XmlNodeType.ProcessingInstruction: XmlProcessingInstruction pi = node as XmlProcessingInstruction; return this.CreateProcessingInstruction (pi.Target, pi.Data); case XmlNodeType.SignificantWhitespace: return this.CreateSignificantWhitespace (node.Value); case XmlNodeType.Text: return this.CreateTextNode (node.Value); case XmlNodeType.Whitespace: return this.CreateWhitespace (node.Value); case XmlNodeType.XmlDeclaration: XmlDeclaration srcDecl = node as XmlDeclaration; return this.CreateXmlDeclaration (srcDecl.Version, srcDecl.Encoding, srcDecl.Standalone); default: throw new InvalidOperationException ("Cannot import specified node type: " + node.NodeType); } } public virtual void Load (Stream inStream) { XmlTextReader reader = new XmlTextReader (inStream, NameTable); reader.XmlResolver = resolver; XmlValidatingReader vr = new XmlValidatingReader (reader); vr.EntityHandling = EntityHandling.ExpandCharEntities; vr.ValidationType = ValidationType.None; Load (vr); } public virtual void Load (string filename) { XmlTextReader xr = null; try { xr = new XmlTextReader (filename, NameTable); xr.XmlResolver = resolver; XmlValidatingReader vr = new XmlValidatingReader (xr); vr.EntityHandling = EntityHandling.ExpandCharEntities; vr.ValidationType = ValidationType.None; Load (vr); } finally { if (xr != null) xr.Close (); } } public virtual void Load (TextReader txtReader) { XmlTextReader xr = new XmlTextReader (txtReader, NameTable); XmlValidatingReader vr = new XmlValidatingReader (xr); vr.EntityHandling = EntityHandling.ExpandCharEntities; vr.ValidationType = ValidationType.None; xr.XmlResolver = resolver; Load (vr); } public virtual void Load (XmlReader reader) { // Reset our document // For now this just means removing all our children but later this // may turn out o need to call a private method that resets other things // like properties we have, etc. RemoveAll (); this.baseURI = reader.BaseURI; // create all contents with use of ReadNode() try { loadMode = true; do { XmlNode n = ReadNode (reader); if (n == null) break; if (preserveWhitespace || n.NodeType != XmlNodeType.Whitespace) AppendChild (n, false); } while (reader.NodeType != XmlNodeType.EndElement); #if NET_2_0 if (reader.Settings != null) schemas = reader.Settings.Schemas; #endif } finally { loadMode = false; } } public virtual void LoadXml (string xml) { XmlTextReader xmlReader = new XmlTextReader ( xml, XmlNodeType.Document, new XmlParserContext (NameTable, new XmlNamespaceManager (NameTable), null, XmlSpace.None)); try { xmlReader.XmlResolver = resolver; Load (xmlReader); } finally { xmlReader.Close (); } } internal void onNodeChanged (XmlNode node, XmlNode parent, string oldValue, string newValue) { if (NodeChanged != null) NodeChanged (node, new XmlNodeChangedEventArgs (node, parent, parent, oldValue, newValue, XmlNodeChangedAction.Change)); } internal void onNodeChanging(XmlNode node, XmlNode parent, string oldValue, string newValue) { if (node.IsReadOnly) throw new ArgumentException ("Node is read-only."); if (NodeChanging != null) NodeChanging (node, new XmlNodeChangedEventArgs (node, parent, parent, oldValue, newValue, XmlNodeChangedAction.Change)); } internal void onNodeInserted (XmlNode node, XmlNode newParent) { if (NodeInserted != null) NodeInserted (node, new XmlNodeChangedEventArgs (node, null, newParent, null, null, XmlNodeChangedAction.Insert)); } internal void onNodeInserting (XmlNode node, XmlNode newParent) { if (NodeInserting != null) NodeInserting (node, new XmlNodeChangedEventArgs (node, null, newParent, null, null, XmlNodeChangedAction.Insert)); } internal void onNodeRemoved (XmlNode node, XmlNode oldParent) { if (NodeRemoved != null) NodeRemoved (node, new XmlNodeChangedEventArgs (node, oldParent, null, null, null, XmlNodeChangedAction.Remove)); } internal void onNodeRemoving (XmlNode node, XmlNode oldParent) { if (NodeRemoving != null) NodeRemoving (node, new XmlNodeChangedEventArgs (node, oldParent, null, null, null, XmlNodeChangedAction.Remove)); } private void ParseName (string name, out string prefix, out string localName) { int indexOfColon = name.IndexOf (':'); if (indexOfColon != -1) { prefix = name.Substring (0, indexOfColon); localName = name.Substring (indexOfColon + 1); } else { prefix = ""; localName = name; } } // Reads XmlReader and creates Attribute Node. private XmlAttribute ReadAttributeNode (XmlReader reader) { if (reader.NodeType == XmlNodeType.Element) reader.MoveToFirstAttribute (); else if (reader.NodeType != XmlNodeType.Attribute) throw new InvalidOperationException (MakeReaderErrorMessage ("bad position to read attribute.", reader)); XmlAttribute attribute = CreateAttribute (reader.Prefix, reader.LocalName, reader.NamespaceURI); #if NET_2_0 if (reader.SchemaInfo != null) SchemaInfo = reader.SchemaInfo; #endif bool isDefault = reader.IsDefault; ReadAttributeNodeValue (reader, attribute); if (isDefault) attribute.SetDefault (); return attribute; } // Reads attribute from XmlReader and then creates attribute value children. XmlAttribute also uses this. internal void ReadAttributeNodeValue (XmlReader reader, XmlAttribute attribute) { while (reader.ReadAttributeValue ()) { if (reader.NodeType == XmlNodeType.EntityReference) attribute.AppendChild (CreateEntityReference (reader.Name), false); // omit node type check else // Children of Attribute is restricted to CharacterData and EntityReference (Comment is not allowed). attribute.AppendChild (CreateTextNode (reader.Value), false); // omit node type check } } [PermissionSet (SecurityAction.InheritanceDemand, Unrestricted = true)] public virtual XmlNode ReadNode (XmlReader reader) { if (PreserveWhitespace) return ReadNodeCore (reader); XmlTextReader xtr = reader as XmlTextReader; if (xtr != null && xtr.WhitespaceHandling == WhitespaceHandling.All) { try { xtr.WhitespaceHandling = WhitespaceHandling.Significant; return ReadNodeCore (reader); } finally { xtr.WhitespaceHandling = WhitespaceHandling.All; } } else return ReadNodeCore (reader); } XmlNode ReadNodeCore (XmlReader reader) { switch (reader.ReadState) { case ReadState.Interactive: break; case ReadState.Initial: #if NET_2_0 if (reader.SchemaInfo != null) SchemaInfo = reader.SchemaInfo; #endif reader.Read (); break; default: return null; } XmlNode n; switch (reader.NodeType) { case XmlNodeType.Attribute: string localName = reader.LocalName; string ns = reader.NamespaceURI; n = ReadAttributeNode (reader); // Keep the current reader position on attribute. reader.MoveToAttribute (localName, ns); return n; case XmlNodeType.CDATA: n = CreateCDataSection (reader.Value); break; case XmlNodeType.Comment: n = CreateComment (reader.Value); break; case XmlNodeType.Element: XmlElement element = CreateElement (reader.Prefix, reader.LocalName, reader.NamespaceURI, reader.NameTable == this.NameTable); #if NET_2_0 if (reader.SchemaInfo != null) SchemaInfo = reader.SchemaInfo; #endif element.IsEmpty = reader.IsEmptyElement; // set the element's attributes. for (int i = 0; i < reader.AttributeCount; i++) { reader.MoveToAttribute (i); element.SetAttributeNode ( ReadAttributeNode (reader)); reader.MoveToElement (); } // FIXME: the code below should be fine and // in some XmlReaders it is much faster, but // caused some breakage in sys.data test. /* if (reader.MoveToFirstAttribute ()) { do { element.SetAttributeNode (ReadAttributeNode (reader)); } while (reader.MoveToNextAttribute ()); reader.MoveToElement (); } */ reader.MoveToElement (); int depth = reader.Depth; if (reader.IsEmptyElement) { n = element; break; } reader.Read (); while (reader.Depth > depth) { n = ReadNodeCore (reader); if (preserveWhitespace || n.NodeType != XmlNodeType.Whitespace) element.AppendChild (n, false); } n = element; break; case XmlNodeType.ProcessingInstruction: n = CreateProcessingInstruction (reader.Name, reader.Value); break; case XmlNodeType.Text: n = CreateTextNode (reader.Value); break; case XmlNodeType.XmlDeclaration: n = CreateXmlDeclaration ("1.0" , String.Empty, String.Empty); n.Value = reader.Value; break; case XmlNodeType.DocumentType: DTDObjectModel dtd = null; IHasXmlParserContext ctxReader = reader as IHasXmlParserContext; if (ctxReader != null) dtd = ctxReader.ParserContext.Dtd; if (dtd != null) n = CreateDocumentType (dtd); else n = CreateDocumentType (reader.Name, reader ["PUBLIC"], reader ["SYSTEM"], reader.Value); break; case XmlNodeType.EntityReference: if (this.loadMode && this.DocumentType != null && DocumentType.Entities.GetNamedItem (reader.Name) == null) throw new XmlException ("Reference to undeclared entity was found."); n = CreateEntityReference (reader.Name); // IF argument XmlReader can resolve entity, // ReadNode() also fills children _from it_. // In this case, it is not from doctype node. // (it is kind of sucky design, but it happens // anyways when we modify doctype node). // // It does not happen when !CanResolveEntity. // (In such case AppendChild() will resolve // entity content, as XmlEntityReference does.) if (reader.CanResolveEntity) { reader.ResolveEntity (); reader.Read (); for (XmlNode child; reader.NodeType != XmlNodeType.EndEntity && (child = ReadNode (reader)) != null;) n.InsertBefore (child, null, false, false); } break; case XmlNodeType.SignificantWhitespace: n = CreateSignificantWhitespace (reader.Value); break; case XmlNodeType.Whitespace: n = CreateWhitespace (reader.Value); break; case XmlNodeType.None: return null; default: // No idea why MS does throw NullReferenceException ;-P throw new NullReferenceException ("Unexpected node type " + reader.NodeType + "."); } reader.Read (); return n; } private string MakeReaderErrorMessage (string message, XmlReader reader) { IXmlLineInfo li = reader as IXmlLineInfo; if (li != null) return String.Format (CultureInfo.InvariantCulture, "{0} Line number = {1}, Inline position = {2}.", message, li.LineNumber, li.LinePosition); else return message; } internal void RemoveIdenticalAttribute (string id) { idTable.Remove (id); } public virtual void Save (Stream outStream) { XmlTextWriter xmlWriter = new XmlTextWriter (outStream, TextEncoding); if (!PreserveWhitespace) xmlWriter.Formatting = Formatting.Indented; WriteContentTo (xmlWriter); xmlWriter.Flush (); } public virtual void Save (string filename) { XmlTextWriter xmlWriter = new XmlTextWriter (filename, TextEncoding); try { if (!PreserveWhitespace) xmlWriter.Formatting = Formatting.Indented; WriteContentTo (xmlWriter); } finally { xmlWriter.Close (); } } public virtual void Save (TextWriter writer) { XmlTextWriter xmlWriter = new XmlTextWriter (writer); if (!PreserveWhitespace) xmlWriter.Formatting = Formatting.Indented; if (FirstChild != null && FirstChild.NodeType != XmlNodeType.XmlDeclaration) xmlWriter.WriteStartDocument (); WriteContentTo (xmlWriter); xmlWriter.WriteEndDocument (); xmlWriter.Flush (); } public virtual void Save (XmlWriter w) { // // This should preserve white space if PreserveWhiteSpace is true // bool autoXmlDecl = FirstChild != null && FirstChild.NodeType != XmlNodeType.XmlDeclaration; if (autoXmlDecl) w.WriteStartDocument (); WriteContentTo (w); if (autoXmlDecl) w.WriteEndDocument (); w.Flush (); } public override void WriteContentTo (XmlWriter xw) { for (XmlNode n = FirstChild; n != null; n = n.NextSibling) n.WriteTo (xw); } public override void WriteTo (XmlWriter w) { WriteContentTo (w); } private void AddDefaultNameTableKeys () { // The following keys are default of MS .NET Framework nameTable.Add ("#text"); nameTable.Add ("xml"); nameTable.Add ("xmlns"); nameTable.Add ("#entity"); nameTable.Add ("#document-fragment"); nameTable.Add ("#comment"); nameTable.Add ("space"); nameTable.Add ("id"); nameTable.Add ("#whitespace"); nameTable.Add ("http://www.w3.org/2000/xmlns/"); nameTable.Add ("#cdata-section"); nameTable.Add ("lang"); nameTable.Add ("#document"); nameTable.Add ("#significant-whitespace"); } internal void CheckIdTableUpdate (XmlAttribute attr, string oldValue, string newValue) { if (idTable [oldValue] == attr) { idTable.Remove (oldValue); idTable [newValue] = attr; } } #if NET_2_0 public void Validate (ValidationEventHandler validationEventHandler) { Validate (validationEventHandler, this, XmlSchemaValidationFlags.ProcessIdentityConstraints); } public void Validate (ValidationEventHandler validationEventHandler, XmlNode nodeToValidate) { Validate (validationEventHandler, nodeToValidate, XmlSchemaValidationFlags.ProcessIdentityConstraints); } private void Validate (ValidationEventHandler handler, XmlNode node, XmlSchemaValidationFlags flags) { XmlReaderSettings settings = new XmlReaderSettings (); settings.NameTable = NameTable; settings.Schemas = schemas; settings.Schemas.XmlResolver = resolver; settings.XmlResolver = resolver; settings.ValidationFlags = flags; settings.ValidationType = ValidationType.Schema; XmlReader r = XmlReader.Create ( new XmlNodeReader (node), settings); while (!r.EOF) r.Read (); } #endif #endregion } }
// FormProcessor V0.1 - Josh Gough http://www.ultravioletconsulting.com // This code references Simon Mourier's HtmlAgilityPack http://smourier.blogspot.com using System; using System.Net; using System.Reflection; using System.Text; using System.Xml; using System.Xml.Xsl; using System.Xml.XPath; using System.IO; using System.Collections; using HtmlAgilityPack; namespace HtmlAgilityPack.AddOns.FormProcessor { /// <summary> /// Interface that defines methods for implementhing a custom login handler /// that can be detected when the HtmlWeb.PostResponse event is raised. It should /// detect whether the has sent the client to a different URI than the /// one requested, and process the redirection accordingly if so. /// </summary> public interface ILoginRedirectHandler { HtmlWeb Web { get; set; } void DetectLoginRedirect(HttpWebRequest request, HttpWebResponse response); void ProcessRedirectPage(HtmlDocument doc); } /// <summary> /// <para> /// Interface that defines methods for implementhing a custom login handler /// piror to HtmlDocument handling. It is the responsibility of this method /// to inspect the document's contents and determine whether the expected /// page was returned. If it instead determines that a login page was /// returned, it should process this page accordingly. /// </para> /// <para> /// In most cases, this means that the client cannot detect that the server /// has sent the client to a different URI than the requested one, /// possibly because it used Server.Transfer, Server.Execute, or the /// equivalent on other environments. /// </para> /// </summary> public interface ILoginPageHandler { HtmlWeb Web { get; set; } void DetectAndProcessLoginPage(HtmlDocument doc); } /// <summary> /// Lightweight extension to HtmlWeb that provides cookie support by /// storing the cookies retrieved in each request in the same /// CookieContainer object. This enables dynamic sessions and navigation /// through a site. /// </summary> public class FormProcessorWeb : HtmlWeb { private Uri _lastRequestUri; /// <summary> /// Contains the cookies to enable persistence across calls /// </summary> private System.Net.CookieContainer _cookieContainer = null; private ILoginRedirectHandler _loginRedirectHandler = null; /// <summary> /// Assign this to provide login page redirection logic when /// the PostResponse event is raised. /// </summary> public ILoginRedirectHandler LoginRedirectHandler { get { return _loginRedirectHandler; } set { if (this._loginRedirectHandler == null && value != null) { // The login redirect detector will assign a // PreHandleDocumentHandler callback to the // PreHandleDocument if the redirection is detected // inside of this callback: this._loginRedirectHandler = value; this.PostResponse += this._loginRedirectHandler.DetectLoginRedirect; } } } private ILoginPageHandler _loginPageHandler = null; /// <summary> /// Assign this to provide login page detection logic when /// the PreHandleDocument event is raised. /// </summary> public ILoginPageHandler LoginPageHandler { get { return _loginPageHandler; } set { _loginPageHandler = value; } } private bool _persistCookiesAcrossRequests; /// <summary> /// Indicates whether to use the same CookieCollection from /// one request to the next. If set, then you can expect /// to collect cookies on an initial request, and then post /// them back to the site when requesting an additional URI. /// </summary> public bool PersistCookiesAcrossRequests { get { return _persistCookiesAcrossRequests; } set { bool currentVal = _persistCookiesAcrossRequests; _persistCookiesAcrossRequests = value; // If the callback is not yet assigned, assign it: if (currentVal == false && value == true) { // Instantiate the container if it's null if (this._cookieContainer == null) this.ResetCookies(); this.PreRequest += preRequestAssignCookies; } // Unregister it if turning it off if (value == false && currentVal == true) { this.PreRequest -= preRequestAssignCookies; } } } /// <summary> /// Assigns the private _cookieContainer to the outbound request, /// assuring that the same collection is passed across calls. /// </summary> /// <param name="target">The target.</param> /// <returns></returns> private bool preRequestAssignCookies(System.Net.HttpWebRequest target) { // Hyves switches from http://www.hyves.nl to https://secure.hyves.org, send along the cookies that we have //if (_lastRequestUri != null && _lastRequestUri.Scheme != target.RequestUri.Scheme) //{ // foreach (Cookie cookie in _cookieContainer.GetCookies(_lastRequestUri)) // { // _cookieContainer.SetCookies(target.RequestUri, cookie.ToString()); // } //} target.CookieContainer = this._cookieContainer; _lastRequestUri = target.RequestUri; return true; } /// <summary> /// Clears the current cookie collection /// </summary> public void ResetCookies() { this._cookieContainer = new System.Net.CookieContainer(); } /// <summary> /// Default constructor calls Init(). /// </summary> public FormProcessorWeb() { this.Init(); } /// <summary> /// Constructor that specifies whether to use cookies across multiple requests. /// </summary> /// <param name="persistCookiesAcrossRequest">if set to <c>true</c> [persist cookies across request].</param> public FormProcessorWeb(bool persistCookiesAcrossRequest) { this.PersistCookiesAcrossRequests = persistCookiesAcrossRequest; this.Init(); } /// <summary> /// Assigns the callback handler for the login page redirect /// detection, if assigned. /// </summary> private void Init() { this.PreHandleDocument += new PreHandleDocumentHandler(OnPreHandleDocument); } /* TODO: revise how this is done so the processor is not dependent upon HtmlDOMElementFactory this.PreCreateElement += new PreCreateElementEventHandler(HtmlDOMElementFactory.DefaultOnCreateElement); */ /// <summary> /// Calls the configured ILoginPageHandler if it has been set. /// </summary> /// <param name="doc"></param> protected void OnPreHandleDocument(HtmlDocument doc) { if (this._loginPageHandler != null) { this._loginPageHandler.DetectAndProcessLoginPage(doc); } } /// <summary> /// Loads an XML document from a URL, converting HTML into XML. /// </summary> /// <param name="url">The URL.</param> /// <param name="format">The format.</param> /// <param name="absolutizeLinks">if set to <c>true</c> [absolutize links].</param> /// <returns></returns> public XmlDocument LoadHtmlAsXml(string url, string format, bool absolutizeLinks) { XmlDocument xdoc = HtmlHelper.LoadHtmlAsXml(this, url, format, absolutizeLinks); return xdoc; } } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using InstallerLib; using System.IO; using dotNetUnitTestsRunner; namespace dotNetInstallerUnitTests { [TestFixture] public class CabUnitTests { [Test] public void TestCabPathAutoDeleteFalse() { Console.WriteLine("TestCabPathAutoDeleteFalse"); ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); setupConfiguration.cab_path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); setupConfiguration.cab_path_autodelete = false; Console.WriteLine("Creating '{0}'", setupConfiguration.cab_path); Directory.CreateDirectory(setupConfiguration.cab_path); string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", configFilename); configFile.SaveAs(configFilename); // execute dotNetInstaller Assert.AreEqual(0, dotNetInstallerExeUtils.Run(configFilename)); File.Delete(configFilename); Assert.IsTrue(Directory.Exists(setupConfiguration.cab_path)); Directory.Delete(setupConfiguration.cab_path); } [Test] public void TestCabPathAutoDeleteTrue() { Console.WriteLine("TestCabPathAutoDeleteTrue"); ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); setupConfiguration.cab_path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); setupConfiguration.cab_path_autodelete = true; Console.WriteLine("Creating '{0}'", setupConfiguration.cab_path); Directory.CreateDirectory(setupConfiguration.cab_path); File.WriteAllText(Path.Combine(setupConfiguration.cab_path, Guid.NewGuid().ToString()), Guid.NewGuid().ToString()); string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", configFilename); configFile.SaveAs(configFilename); // execute dotNetInstaller Assert.AreEqual(0, dotNetInstallerExeUtils.Run(configFilename)); File.Delete(configFilename); Assert.IsFalse(Directory.Exists(setupConfiguration.cab_path)); } [Test] public void TestExtractCab() { Console.WriteLine("TestExtractCab"); // create a self-extracting bootstrapper ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); InstallerLinkerArguments args = new InstallerLinkerArguments(); args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", args.config); configFile.SaveAs(args.config); args.embed = true; args.apppath = Path.GetTempPath(); args.embedFiles = new string[]{ Path.GetFileName(args.config) }; args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe"); args.template = dotNetInstallerExeUtils.Executable; Console.WriteLine("Linking '{0}'", args.output); InstallerLinkerExeUtils.CreateInstaller(args); Assert.IsTrue(File.Exists(args.output)); // execute dotNetInstaller Assert.AreEqual(0, dotNetInstallerExeUtils.Run(args.output, "/ExtractCab")); // this should have created a directory called SupportFiles in the current directory string supportFilesPath = Path.Combine(Path.GetDirectoryName(args.output), "SupportFiles"); Console.WriteLine("Checking {0}", supportFilesPath); Assert.IsTrue(Directory.Exists(supportFilesPath), string.Format("Missing {0}", supportFilesPath)); File.Delete(args.config); File.Delete(args.output); Directory.Delete(supportFilesPath, true); } [Test] public void TestExtractCabPerComponent() { Console.WriteLine("TestExtractCabPerComponent"); InstallerLinkerArguments args = new InstallerLinkerArguments(); args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", args.config); args.embed = true; args.apppath = Path.GetTempPath(); args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe"); args.template = dotNetInstallerExeUtils.Executable; // create a self-extracting bootstrapper ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); ComponentCmd component = new ComponentCmd(); setupConfiguration.Children.Add(component); EmbedFile embedfile = new EmbedFile(); embedfile.sourcefilepath = args.config; embedfile.targetfilepath = Path.GetFileName(args.config); component.Children.Add(embedfile); configFile.SaveAs(args.config); Console.WriteLine("Linking '{0}'", args.output); InstallerLinkerExeUtils.CreateInstaller(args); Assert.IsTrue(File.Exists(args.output)); // execute dotNetInstaller Assert.AreEqual(0, dotNetInstallerExeUtils.Run(args.output, "/ExtractCab")); // this should have created a directory called SupportFiles in the current directory string supportFilesPath = Path.Combine(Path.GetDirectoryName(args.output), "SupportFiles"); Console.WriteLine("Checking {0}", supportFilesPath); Assert.IsTrue(Directory.Exists(supportFilesPath), string.Format("Missing {0}", supportFilesPath)); File.Delete(args.config); File.Delete(args.output); Directory.Delete(supportFilesPath, true); } [Test] public void TestExtractAndRunCabPerComponent() { Console.WriteLine("TestExtractAndRunCabPerComponent"); InstallerLinkerArguments args = new InstallerLinkerArguments(); args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", args.config); args.embed = true; args.apppath = Path.GetTempPath(); args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe"); args.template = dotNetInstallerExeUtils.Executable; // create a self-extracting bootstrapper ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); setupConfiguration.cab_path = Path.Combine(Path.GetTempPath(), "testExtractAndRunCabPerComponent"); setupConfiguration.cab_path_autodelete = false; configFile.Children.Add(setupConfiguration); ComponentCmd component = new ComponentCmd(); component.command = "cmd.exe /C copy \"#CABPATH\\component\\before.xml\" \"#CABPATH\\component\\after.xml\""; component.required_install = true; setupConfiguration.Children.Add(component); EmbedFile embedfile = new EmbedFile(); embedfile.sourcefilepath = args.config; embedfile.targetfilepath = @"component\before.xml"; component.Children.Add(embedfile); configFile.SaveAs(args.config); Console.WriteLine("Linking '{0}'", args.output); InstallerLinkerExeUtils.CreateInstaller(args); Assert.IsTrue(File.Exists(args.output)); // execute dotNetInstaller string logfile = Path.Combine(Path.GetTempPath(), "testExtractAndRunCabPerComponent.log"); Console.WriteLine("Log: {0}", logfile); Assert.AreEqual(0, dotNetInstallerExeUtils.Run(args.output, string.Format("/qb /log /logfile \"{0}\"", logfile))); string extractedComponentPath = Path.Combine(setupConfiguration.cab_path, "component"); Console.WriteLine("Checking {0}", extractedComponentPath); Assert.IsTrue(Directory.Exists(extractedComponentPath), string.Format("Missing {0}", extractedComponentPath)); Assert.IsTrue(File.Exists(Path.Combine(Path.GetTempPath(), @"testExtractAndRunCabPerComponent\component\before.xml"))); Assert.IsTrue(File.Exists(Path.Combine(Path.GetTempPath(), @"testExtractAndRunCabPerComponent\component\after.xml"))); File.Delete(args.config); File.Delete(args.output); Directory.Delete(setupConfiguration.cab_path, true); File.Delete(logfile); } [Test] public void TestDisplayCab() { Console.WriteLine("TestDisplayCab"); // create a self-extracting bootstrapper ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); InstallerLinkerArguments args = new InstallerLinkerArguments(); args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", args.config); configFile.SaveAs(args.config); args.embed = true; args.apppath = Path.GetTempPath(); // args.embedFiles = new string[] { Path.GetFileName(args.config) }; args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe"); args.template = dotNetInstallerExeUtils.Executable; Console.WriteLine("Linking '{0}'", args.output); InstallerLinkerExeUtils.CreateInstaller(args); Assert.IsTrue(File.Exists(args.output)); // execute dotNetInstaller Assert.AreEqual(0, dotNetInstallerExeUtils.Run(args.output, "/DisplayCab /qb")); File.Delete(args.config); File.Delete(args.output); } [Test] public void TestExtractCabTwoComponentsSameName() { Console.WriteLine("TestExtractCabTwoComponentsSameName"); InstallerLinkerArguments args = new InstallerLinkerArguments(); args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", args.config); args.embed = true; args.apppath = Path.GetTempPath(); args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe"); args.template = dotNetInstallerExeUtils.Executable; // create a self-extracting bootstrapper ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); for (int i = 0; i < 2; i++) { ComponentCmd component = new ComponentCmd(); component.id = "component"; setupConfiguration.Children.Add(component); EmbedFile embedfile = new EmbedFile(); embedfile.sourcefilepath = args.config; embedfile.targetfilepath = string.Format("component{0}\\file.xml", i); component.Children.Add(embedfile); } configFile.SaveAs(args.config); Console.WriteLine("Linking '{0}'", args.output); InstallerLinkerExeUtils.CreateInstaller(args); Assert.IsTrue(File.Exists(args.output)); // execute dotNetInstaller Assert.AreEqual(0, dotNetInstallerExeUtils.Run(args.output, "/ExtractCab")); // this should have created a directory called SupportFiles in the current directory string supportFilesPath = Path.Combine(Path.GetDirectoryName(args.output), "SupportFiles"); Console.WriteLine("Checking {0}", supportFilesPath); Assert.IsTrue(Directory.Exists(supportFilesPath), string.Format("Missing {0}", supportFilesPath)); Assert.IsTrue(Directory.Exists(supportFilesPath + @"\component0")); Assert.IsTrue(File.Exists(supportFilesPath + @"\component0\file.xml")); Assert.IsTrue(Directory.Exists(supportFilesPath + @"\component1")); Assert.IsTrue(File.Exists(supportFilesPath + @"\component1\file.xml")); File.Delete(args.config); File.Delete(args.output); Directory.Delete(supportFilesPath, true); } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Backoffice_Registrasi_RADAddBaru : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } int UserId = (int)Session["SIMRS.UserId"]; if (Session["RegistrasiRAD"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx"); } btnSave.Text = "<center><img alt=\"" + Resources.GetString("", "Save") + "\" src=\"" + Request.ApplicationPath + "/images/save_f2.gif\" align=\"middle\" border=\"0\" name=\"save\" value=\"save\"><center>"; btnCancel.Text = "<center><img alt=\"" + Resources.GetString("", "Cancel") + "\" src=\"" + Request.ApplicationPath + "/images/cancel_f2.gif\" align=\"middle\" border=\"0\" name=\"cancel\" value=\"cancel\"><center>"; GetListStatus(); GetListStatusPerkawinan(); GetListAgama(); GetListPendidikan(); GetListJenisPenjamin(); GetListHubungan(); txtTanggalRegistrasi.Text = DateTime.Now.ToString("dd/MM/yyyy"); GetNomorRegistrasi(); GetNomorTunggu(); GetListKelompokPemeriksaan(); GetListSatuanKerja(); GetListSatuanKerjaPenjamin(); } } public void GetListStatus() { string StatusId = ""; SIMRS.DataAccess.RS_Status myObj = new SIMRS.DataAccess.RS_Status(); DataTable dt = myObj.GetList(); cmbStatusPasien.Items.Clear(); int i = 0; cmbStatusPasien.Items.Add(""); cmbStatusPasien.Items[i].Text = ""; cmbStatusPasien.Items[i].Value = ""; cmbStatusPenjamin.Items.Add(""); cmbStatusPenjamin.Items[i].Text = ""; cmbStatusPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbStatusPasien.Items.Add(""); cmbStatusPasien.Items[i].Text = dr["Nama"].ToString(); cmbStatusPasien.Items[i].Value = dr["Id"].ToString(); cmbStatusPenjamin.Items.Add(""); cmbStatusPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbStatusPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == StatusId) { cmbStatusPasien.SelectedIndex = i; cmbStatusPenjamin.SelectedIndex = i; } i++; } } public void GetListPangkatPasien() { string PangkatId = ""; SIMRS.DataAccess.RS_Pangkat myObj = new SIMRS.DataAccess.RS_Pangkat(); if (cmbStatusPasien.SelectedIndex > 0) myObj.StatusId = int.Parse(cmbStatusPasien.SelectedItem.Value); DataTable dt = myObj.GetListByStatusId(); cmbPangkatPasien.Items.Clear(); int i = 0; cmbPangkatPasien.Items.Add(""); cmbPangkatPasien.Items[i].Text = ""; cmbPangkatPasien.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbPangkatPasien.Items.Add(""); cmbPangkatPasien.Items[i].Text = dr["Nama"].ToString(); cmbPangkatPasien.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == PangkatId) { cmbPangkatPasien.SelectedIndex = i; } i++; } } public void GetListPangkatPenjamin() { string PangkatId = ""; SIMRS.DataAccess.RS_Pangkat myObj = new SIMRS.DataAccess.RS_Pangkat(); if (cmbStatusPenjamin.SelectedIndex > 0) myObj.StatusId = int.Parse(cmbStatusPenjamin.SelectedItem.Value); DataTable dt = myObj.GetListByStatusId(); cmbPangkatPenjamin.Items.Clear(); int i = 0; cmbPangkatPenjamin.Items.Add(""); cmbPangkatPenjamin.Items[i].Text = ""; cmbPangkatPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbPangkatPenjamin.Items.Add(""); cmbPangkatPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbPangkatPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == PangkatId) { cmbPangkatPenjamin.SelectedIndex = i; } i++; } } public void GetNomorTunggu() { SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); myObj.PoliklinikId = 41; // RAD myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); txtNomorTunggu.Text = myObj.GetNomorTunggu().ToString(); } public void GetListStatusPerkawinan() { string StatusPerkawinanId = ""; BkNet.DataAccess.StatusPerkawinan myObj = new BkNet.DataAccess.StatusPerkawinan(); DataTable dt = myObj.GetList(); cmbStatusPerkawinan.Items.Clear(); int i = 0; cmbStatusPerkawinan.Items.Add(""); cmbStatusPerkawinan.Items[i].Text = ""; cmbStatusPerkawinan.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbStatusPerkawinan.Items.Add(""); cmbStatusPerkawinan.Items[i].Text = dr["Nama"].ToString(); cmbStatusPerkawinan.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == StatusPerkawinanId) cmbStatusPerkawinan.SelectedIndex = i; i++; } } public void GetListAgama() { string AgamaId = ""; BkNet.DataAccess.Agama myObj = new BkNet.DataAccess.Agama(); DataTable dt = myObj.GetList(); cmbAgama.Items.Clear(); int i = 0; cmbAgama.Items.Add(""); cmbAgama.Items[i].Text = ""; cmbAgama.Items[i].Value = ""; cmbAgamaPenjamin.Items.Add(""); cmbAgamaPenjamin.Items[i].Text = ""; cmbAgamaPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbAgama.Items.Add(""); cmbAgama.Items[i].Text = dr["Nama"].ToString(); cmbAgama.Items[i].Value = dr["Id"].ToString(); cmbAgamaPenjamin.Items.Add(""); cmbAgamaPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbAgamaPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == AgamaId) cmbAgama.SelectedIndex = i; i++; } } public void GetListPendidikan() { string PendidikanId = ""; BkNet.DataAccess.Pendidikan myObj = new BkNet.DataAccess.Pendidikan(); DataTable dt = myObj.GetList(); cmbPendidikan.Items.Clear(); int i = 0; cmbPendidikan.Items.Add(""); cmbPendidikan.Items[i].Text = ""; cmbPendidikan.Items[i].Value = ""; cmbPendidikanPenjamin.Items.Add(""); cmbPendidikanPenjamin.Items[i].Text = ""; cmbPendidikanPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbPendidikan.Items.Add(""); cmbPendidikan.Items[i].Text = "[" + dr["Kode"].ToString() + "] " + dr["Nama"].ToString(); cmbPendidikan.Items[i].Value = dr["Id"].ToString(); cmbPendidikanPenjamin.Items.Add(""); cmbPendidikanPenjamin.Items[i].Text = "[" + dr["Kode"].ToString() + "] " + dr["Nama"].ToString(); cmbPendidikanPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == PendidikanId) cmbPendidikan.SelectedIndex = i; i++; } } public void GetListJenisPenjamin() { string JenisPenjaminId = ""; SIMRS.DataAccess.RS_JenisPenjamin myObj = new SIMRS.DataAccess.RS_JenisPenjamin(); DataTable dt = myObj.GetList(); cmbJenisPenjamin.Items.Clear(); int i = 0; foreach (DataRow dr in dt.Rows) { cmbJenisPenjamin.Items.Add(""); cmbJenisPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbJenisPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == JenisPenjaminId) cmbJenisPenjamin.SelectedIndex = i; i++; } } public void GetListHubungan() { string HubunganId = ""; SIMRS.DataAccess.RS_Hubungan myObj = new SIMRS.DataAccess.RS_Hubungan(); DataTable dt = myObj.GetList(); cmbHubungan.Items.Clear(); int i = 0; cmbHubungan.Items.Add(""); cmbHubungan.Items[i].Text = ""; cmbHubungan.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbHubungan.Items.Add(""); cmbHubungan.Items[i].Text = dr["Nama"].ToString(); cmbHubungan.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == HubunganId) cmbHubungan.SelectedIndex = i; i++; } } public void GetNomorRegistrasi() { SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); myObj.PoliklinikId = 41;//RAD myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); txtNoRegistrasi.Text = myObj.GetNomorRegistrasi(); } public void GetListKelompokPemeriksaan() { SIMRS.DataAccess.RS_KelompokPemeriksaan myObj = new SIMRS.DataAccess.RS_KelompokPemeriksaan(); myObj.JenisPemeriksaanId = 2;//RAD DataTable dt = myObj.GetListByJenisPemeriksaanId(); cmbKelompokPemeriksaan.Items.Clear(); int i = 0; foreach (DataRow dr in dt.Rows) { cmbKelompokPemeriksaan.Items.Add(""); cmbKelompokPemeriksaan.Items[i].Text = dr["Nama"].ToString(); cmbKelompokPemeriksaan.Items[i].Value = dr["Id"].ToString(); i++; } cmbKelompokPemeriksaan.SelectedIndex = 0; GetListPemeriksaan(); } public DataSet GetDataPemeriksaan() { DataSet ds = new DataSet(); if (Session["dsLayananRAD"] != null) ds = (DataSet)Session["dsLayananRAD"]; else { SIMRS.DataAccess.RS_Layanan myObj = new SIMRS.DataAccess.RS_Layanan(); myObj.PoliklinikId = 41;// RAD DataTable myData = myObj.SelectAllWPoliklinikIdLogic(); ds.Tables.Add(myData); Session.Add("dsLayananRAD", ds); } return ds; } public void GetListPemeriksaan() { DataSet ds = new DataSet(); ds = GetDataPemeriksaan(); lstRefPemeriksaan.DataTextField = "Nama"; lstRefPemeriksaan.DataValueField = "Id"; DataView dv = ds.Tables[0].DefaultView; dv.RowFilter = " KelompokPemeriksaanId = " + cmbKelompokPemeriksaan.SelectedItem.Value; lstRefPemeriksaan.DataSource = dv; lstRefPemeriksaan.DataBind(); } public void OnSave(Object sender, EventArgs e) { lblError.Text = ""; if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } int UserId = (int)Session["SIMRS.UserId"]; if (!Page.IsValid) { return; } string noRM1 = txtNoRM.Text.Replace("_",""); string noRM2 = noRM1.Replace(".",""); if (noRM2 == "") { lblError.Text = "Nomor Rekam Medis Harus diisi"; return; } else if (noRM2.Length < 5) { lblError.Text = "Nomor Rekam Medis Harus diisi dengan benar"; return; } //if(noRM1.Substring(noRM1.LastIndexOf(".")) == "") SIMRS.DataAccess.RS_Pasien myPasien = new SIMRS.DataAccess.RS_Pasien(); //txtNoRM.Text = txtNoRM1.Text + "." + txtNoRM2.Text + "." + txtNoRM3.Text; myPasien.PasienId = 0; myPasien.NoRM = txtNoRM.Text.Replace("_", ""); myPasien.Nama = txtNama.Text; if (cmbStatusPasien.SelectedIndex > 0) myPasien.StatusId = int.Parse(cmbStatusPasien.SelectedItem.Value); if (cmbPangkatPasien.SelectedIndex > 0) myPasien.PangkatId = int.Parse(cmbPangkatPasien.SelectedItem.Value); myPasien.NoAskes = txtNoASKES.Text; myPasien.NoKTP = txtNoKTP.Text; myPasien.GolDarah = txtGolDarah.Text; myPasien.NRP = txtNrpPasien.Text; myPasien.Jabatan = txtJabatanPasien.Text; //myPasien.Kesatuan = txtKesatuanPasien.Text; myPasien.Kesatuan = cmbSatuanKerja.SelectedItem.ToString(); myPasien.AlamatKesatuan = txtAlamatKesatuanPasien.Text; myPasien.TempatLahir = txtTempatLahir.Text; if (txtTanggalLahir.Text != "") myPasien.TanggalLahir = DateTime.Parse(txtTanggalLahir.Text); myPasien.Alamat = txtAlamatPasien.Text; myPasien.Telepon = txtTeleponPasien.Text; if (cmbJenisKelamin.SelectedIndex > 0) myPasien.JenisKelamin = cmbJenisKelamin.SelectedItem.Value; if (cmbStatusPerkawinan.SelectedIndex > 0) myPasien.StatusPerkawinanId = int.Parse(cmbStatusPerkawinan.SelectedItem.Value); if (cmbAgama.SelectedIndex > 0) myPasien.AgamaId = int.Parse(cmbAgama.SelectedItem.Value); if (cmbPendidikan.SelectedIndex > 0) myPasien.PendidikanId = int.Parse(cmbPendidikan.SelectedItem.Value); myPasien.Pekerjaan = txtPekerjaan.Text; myPasien.AlamatKantor = txtAlamatKantorPasien.Text; myPasien.TeleponKantor = txtTeleponKantorPasien.Text; myPasien.Keterangan = txtKeteranganPasien.Text; myPasien.CreatedBy = UserId; myPasien.CreatedDate = DateTime.Now; if (myPasien.IsExist()) { lblError.Text = myPasien.ErrorMessage.ToString(); return; } else { myPasien.Insert(); int PenjaminId = 0; if (cmbJenisPenjamin.SelectedIndex > 0) { //Input Data Penjamin SIMRS.DataAccess.RS_Penjamin myPenj = new SIMRS.DataAccess.RS_Penjamin(); myPenj.PenjaminId = 0; if (cmbJenisPenjamin.SelectedIndex == 1) { myPenj.Nama = txtNamaPenjamin.Text; if (cmbHubungan.SelectedIndex > 0) myPenj.HubunganId = int.Parse(cmbHubungan.SelectedItem.Value); myPenj.Umur = txtUmurPenjamin.Text; myPenj.Alamat = txtAlamatPenjamin.Text; myPenj.Telepon = txtTeleponPenjamin.Text; if (cmbAgamaPenjamin.SelectedIndex > 0) myPenj.AgamaId = int.Parse(cmbAgamaPenjamin.SelectedItem.Value); if (cmbPendidikanPenjamin.SelectedIndex > 0) myPenj.PendidikanId = int.Parse(cmbPendidikanPenjamin.SelectedItem.Value); if (cmbPangkatPenjamin.SelectedIndex > 0) myPenj.PangkatId = int.Parse(cmbPangkatPenjamin.SelectedItem.Value); myPenj.NoKTP = txtNoKTPPenjamin.Text; myPenj.GolDarah = txtGolDarahPenjamin.Text; myPenj.NRP = txtNRPPenjamin.Text; //myPenj.Kesatuan = txtKesatuanPenjamin.Text; myPenj.Kesatuan = cmbSatuanKerjaPenjamin.SelectedItem.ToString(); myPenj.AlamatKesatuan = txtAlamatKesatuanPenjamin.Text; myPenj.Keterangan = txtKeteranganPenjamin.Text; } else { myPenj.Nama = txtNamaPerusahaan.Text; myPenj.NamaKontak = txtNamaKontak.Text; myPenj.Alamat = txtAlamatPerusahaan.Text; myPenj.Telepon = txtTeleponPerusahaan.Text; myPenj.Fax = txtFAXPerusahaan.Text; } myPenj.CreatedBy = UserId; myPenj.CreatedDate = DateTime.Now; myPenj.Insert(); PenjaminId = (int)myPenj.PenjaminId; } //Input Data Registrasi SIMRS.DataAccess.RS_Registrasi myReg = new SIMRS.DataAccess.RS_Registrasi(); myReg.RegistrasiId = 0; myReg.PasienId = myPasien.PasienId; GetNomorRegistrasi(); myReg.NoRegistrasi = txtNoRegistrasi.Text; myReg.JenisRegistrasiId = 1; myReg.TanggalRegistrasi = DateTime.Parse(txtTanggalRegistrasi.Text); myReg.JenisPenjaminId = int.Parse(cmbJenisPenjamin.SelectedItem.Value); if (PenjaminId != 0) myReg.PenjaminId = PenjaminId; myReg.CreatedBy = UserId; myReg.CreatedDate = DateTime.Now; //myReg.NoUrut = txtNoUrut.Text; myReg.Insert(); //Input Data Rawat Jalan SIMRS.DataAccess.RS_RawatJalan myRJ = new SIMRS.DataAccess.RS_RawatJalan(); myRJ.RawatJalanId = 0; myRJ.RegistrasiId = myReg.RegistrasiId; myRJ.PoliklinikId = 41;// RAD myRJ.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); GetNomorTunggu(); if (txtNomorTunggu.Text != "" ) myRJ.NomorTunggu = int.Parse(txtNomorTunggu.Text); myRJ.Status = 0;//Baru daftar myRJ.CreatedBy = UserId; myRJ.CreatedDate = DateTime.Now; myRJ.Insert(); ////Input Data Layanan SIMRS.DataAccess.RS_RJLayanan myLayanan = new SIMRS.DataAccess.RS_RJLayanan(); SIMRS.DataAccess.RS_Layanan myTarif = new SIMRS.DataAccess.RS_Layanan(); if (lstPemeriksaan.Items.Count > 0) { string[] kellay; string[] Namakellay; DataTable dt; for (int i = 0; i < lstPemeriksaan.Items.Count; i++) { myLayanan.RJLayananId = 0; myLayanan.RawatJalanId = myRJ.RawatJalanId; myLayanan.JenisLayananId = 3; kellay = lstPemeriksaan.Items[i].Value.Split('|'); Namakellay = lstPemeriksaan.Items[i].Text.Split(':'); myLayanan.KelompokLayananId = 2; myLayanan.LayananId = int.Parse(kellay[1]); myLayanan.NamaLayanan = Namakellay[1]; myTarif.Id = int.Parse(kellay[1]); dt = myTarif.GetTarifRIByLayananId(0); if (dt.Rows.Count > 0) myLayanan.Tarif = dt.Rows[0]["Tarif"].ToString() != "" ? (Decimal)dt.Rows[0]["Tarif"] : 0; else myLayanan.Tarif = 0; myLayanan.JumlahSatuan = double.Parse("1"); myLayanan.Discount = 0; myLayanan.BiayaTambahan = 0; myLayanan.JumlahTagihan = myLayanan.Tarif; myLayanan.Keterangan = ""; myLayanan.CreatedBy = UserId; myLayanan.CreatedDate = DateTime.Now; myLayanan.Insert(); } } //================= string CurrentPage = ""; if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") CurrentPage = Request.QueryString["CurrentPage"].ToString(); Response.Redirect("RADView.aspx?CurrentPage=" + CurrentPage + "&RawatJalanId=" + myRJ.RawatJalanId); } } public void OnCancel(Object sender, EventArgs e) { string CurrentPage = ""; if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") CurrentPage = Request.QueryString["CurrentPage"].ToString(); Response.Redirect("RADList.aspx?CurrentPage=" + CurrentPage); } protected void cmbJenisPenjamin_SelectedIndexChanged(object sender, EventArgs e) { if (cmbJenisPenjamin.SelectedIndex == 1) { tblPenjaminKeluarga.Visible = true; tblPenjaminPerusahaan.Visible = false; } else if (cmbJenisPenjamin.SelectedIndex == 2 || cmbJenisPenjamin.SelectedIndex == 3) { tblPenjaminKeluarga.Visible = false; tblPenjaminPerusahaan.Visible = true; } else { tblPenjaminKeluarga.Visible = false; tblPenjaminPerusahaan.Visible = false; } } protected void txtTanggalRegistrasi_TextChanged(object sender, EventArgs e) { GetNomorTunggu(); GetNomorRegistrasi(); } protected void cmbStatusPasien_SelectedIndexChanged(object sender, EventArgs e) { GetListPangkatPasien(); } protected void cmbStatusPenjamin_SelectedIndexChanged(object sender, EventArgs e) { GetListPangkatPenjamin(); } protected void cmbKelompokPemeriksaan_SelectedIndexChanged(object sender, EventArgs e) { GetListPemeriksaan(); } protected void btnAddPemeriksaan_Click(object sender, EventArgs e) { if (lstRefPemeriksaan.SelectedIndex != -1) { int i = lstPemeriksaan.Items.Count; bool exist = false; string selectValue = cmbKelompokPemeriksaan.SelectedItem.Value + "|" + lstRefPemeriksaan.SelectedItem.Value; for (int j = 0; j < i; j++) { if (lstPemeriksaan.Items[j].Value == selectValue) { exist = true; break; } } if (!exist) { ListItem newItem = new ListItem(); newItem.Text = cmbKelompokPemeriksaan.SelectedItem.Text + ": " + lstRefPemeriksaan.SelectedItem.Text; newItem.Value = cmbKelompokPemeriksaan.SelectedItem.Value + "|" + lstRefPemeriksaan.SelectedItem.Value; lstPemeriksaan.Items.Add(newItem); } } } protected void btnRemovePemeriksaan_Click(object sender, EventArgs e) { if (lstPemeriksaan.SelectedIndex != -1) { lstPemeriksaan.Items.RemoveAt(lstPemeriksaan.SelectedIndex); } } protected void btnCek_Click(object sender, EventArgs e) { SIMRS.DataAccess.RS_Pasien myPasien = new SIMRS.DataAccess.RS_Pasien(); myPasien.NoRM = txtNoRM.Text.Replace("_", ""); if (myPasien.IsExistRM()) { lblCek.Text = "No.RM sudah terpakai"; return; } else { lblCek.Text = "No.RM belum terpakai"; return; } } public void GetListSatuanKerja() { string SatuanKerjaId = ""; SIMRS.DataAccess.RS_SatuanKerja myObj = new SIMRS.DataAccess.RS_SatuanKerja(); DataTable dt = myObj.GetList(); cmbSatuanKerja.Items.Clear(); int i = 0; cmbSatuanKerja.Items.Add(""); cmbSatuanKerja.Items[i].Text = ""; cmbSatuanKerja.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbSatuanKerja.Items.Add(""); cmbSatuanKerja.Items[i].Text = dr["NamaSatker"].ToString(); cmbSatuanKerja.Items[i].Value = dr["IdSatuanKerja"].ToString(); if (dr["IdSatuanKerja"].ToString() == SatuanKerjaId) cmbSatuanKerja.SelectedIndex = i; i++; } } public void GetListSatuanKerjaPenjamin() { string SatuanKerjaId = ""; SIMRS.DataAccess.RS_SatuanKerja myObj = new SIMRS.DataAccess.RS_SatuanKerja(); DataTable dt = myObj.GetList(); cmbSatuanKerjaPenjamin.Items.Clear(); int i = 0; cmbSatuanKerjaPenjamin.Items.Add(""); cmbSatuanKerjaPenjamin.Items[i].Text = ""; cmbSatuanKerjaPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbSatuanKerjaPenjamin.Items.Add(""); cmbSatuanKerjaPenjamin.Items[i].Text = dr["NamaSatker"].ToString(); cmbSatuanKerjaPenjamin.Items[i].Value = dr["IdSatuanKerja"].ToString(); if (dr["IdSatuanKerja"].ToString() == SatuanKerjaId) cmbSatuanKerjaPenjamin.SelectedIndex = i; i++; } } }
/* * 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 Nini.Config; using Mono.Addins; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.PhysicsModules.SharedBase; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Region.PhysicsModule.BasicPhysics { /// <summary> /// This is an incomplete extremely basic physics implementation /// </summary> /// <remarks> /// Not useful for anything at the moment apart from some regression testing in other components where some form /// of physics plugin is needed. /// </remarks> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "BasicPhysicsScene")] public class BasicScene : PhysicsScene, INonSharedRegionModule { private List<BasicActor> _actors = new List<BasicActor>(); private List<BasicPhysicsPrim> _prims = new List<BasicPhysicsPrim>(); private float[] _heightMap; private Vector3 m_regionExtent; private bool m_Enabled = false; //protected internal string sceneIdentifier; #region INonSharedRegionModule public string Name { get { return "basicphysics"; } } public string Version { get { return "1.0"; } } public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { // TODO: Move this out of Startup IConfig config = source.Configs["Startup"]; if (config != null) { string physics = config.GetString("physics", string.Empty); if (physics == Name) m_Enabled = true; } } public void Close() { } public void AddRegion(Scene scene) { if (!m_Enabled) return; EngineType = Name; PhysicsSceneName = EngineType + "/" + scene.RegionInfo.RegionName; EngineName = Name + " " + Version; scene.RegisterModuleInterface<PhysicsScene>(this); m_regionExtent = new Vector3(scene.RegionInfo.RegionSizeX, scene.RegionInfo.RegionSizeY, scene.RegionInfo.RegionSizeZ); base.Initialise(scene.PhysicsRequestAsset, (scene.Heightmap != null ? scene.Heightmap.GetFloatsSerialised() : new float[scene.RegionInfo.RegionSizeX * scene.RegionInfo.RegionSizeY]), (float)scene.RegionInfo.RegionSettings.WaterHeight); } public void RemoveRegion(Scene scene) { if (!m_Enabled) return; } public void RegionLoaded(Scene scene) { if (!m_Enabled) return; } #endregion public override void Dispose() {} public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position, Vector3 size, Quaternion rotation, bool isPhysical, uint localid) { BasicPhysicsPrim prim = new BasicPhysicsPrim(primName, localid, position, size, rotation, pbs); prim.IsPhysical = isPhysical; _prims.Add(prim); return prim; } public override PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 velocity, Vector3 size, bool isFlying) { BasicActor act = new BasicActor(size); act.Position = position; act.Velocity = velocity; act.Flying = isFlying; _actors.Add(act); return act; } public override void RemovePrim(PhysicsActor actor) { BasicPhysicsPrim prim = (BasicPhysicsPrim)actor; if (_prims.Contains(prim)) _prims.Remove(prim); } public override void RemoveAvatar(PhysicsActor actor) { BasicActor act = (BasicActor)actor; if (_actors.Contains(act)) _actors.Remove(act); } public override void AddPhysicsActorTaint(PhysicsActor prim) { } public override float Simulate(float timeStep) { // Console.WriteLine("Simulating"); float fps = 0; for (int i = 0; i < _actors.Count; ++i) { BasicActor actor = _actors[i]; Vector3 actorPosition = actor.Position; Vector3 actorVelocity = actor.Velocity; //Console.WriteLine( // "Processing actor {0}, starting pos {1}, starting vel {2}", i, actorPosition, actorVelocity); actorPosition.X += actor.Velocity.X * timeStep; actorPosition.Y += actor.Velocity.Y * timeStep; if (actor.Position.Y < 0) { actorPosition.Y = 0.1F; } else if (actor.Position.Y >= m_regionExtent.Y) { actorPosition.Y = (m_regionExtent.Y - 0.1f); } if (actor.Position.X < 0) { actorPosition.X = 0.1F; } else if (actor.Position.X >= m_regionExtent.X) { actorPosition.X = (m_regionExtent.X - 0.1f); } float terrainHeight = 0; if (_heightMap != null) terrainHeight = _heightMap[(int)actor.Position.Y * (int)m_regionExtent.Y + (int)actor.Position.X]; float height = terrainHeight + actor.Size.Z; // Console.WriteLine("height {0}, actorPosition {1}", height, actorPosition); if (actor.Flying) { if (actor.Position.Z + (actor.Velocity.Z * timeStep) < terrainHeight + 2) { actorPosition.Z = height; actorVelocity.Z = 0; actor.IsColliding = true; } else { actorPosition.Z += actor.Velocity.Z * timeStep; actor.IsColliding = false; } } else { actorPosition.Z = height; actorVelocity.Z = 0; actor.IsColliding = true; } actor.Position = actorPosition; actor.Velocity = actorVelocity; } return 1.0f; } public override void GetResults() { } public override bool IsThreaded { get { return (false); // for now we won't be multithreaded } } public override void SetTerrain(float[] heightMap) { _heightMap = heightMap; } public override void DeleteTerrain() { } public override void SetWaterLevel(float baseheight) { } public override Dictionary<uint, float> GetTopColliders() { Dictionary<uint, float> returncolliders = new Dictionary<uint, float>(); return returncolliders; } } }
// // Copyright (c) 2014 .NET Foundation // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Copyright (c) 2014 Couchbase, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. //using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using Apache.Http.Client; using Apache.Http.Entity.Mime; using Apache.Http.Entity.Mime.Content; using Couchbase.Lite; using Couchbase.Lite.Internal; using Couchbase.Lite.Replicator; using Couchbase.Lite.Support; using Couchbase.Lite.Util; using Sharpen; namespace Couchbase.Lite.Replicator { /// <exclude></exclude> public sealed class Pusher : Replication, Database.ChangeListener { private bool createTarget; private bool creatingTarget; private bool observing; private ReplicationFilter filter; private bool dontSendMultipart = false; internal ICollection<long> pendingSequences; internal long maxPendingSequence; /// <summary>Constructor</summary> [InterfaceAudience.Private] public Pusher(Database db, Uri remote, bool continuous, ScheduledExecutorService workExecutor) : this(db, remote, continuous, null, workExecutor) { } /// <summary>Constructor</summary> [InterfaceAudience.Private] public Pusher(Database db, Uri remote, bool continuous, HttpClientFactory clientFactory , ScheduledExecutorService workExecutor) : base(db, remote, continuous, clientFactory , workExecutor) { createTarget = false; observing = false; } [InterfaceAudience.Public] public override bool IsPull() { return false; } [InterfaceAudience.Public] public override bool ShouldCreateTarget() { return createTarget; } [InterfaceAudience.Public] public override void SetCreateTarget(bool createTarget) { this.createTarget = createTarget; } [InterfaceAudience.Public] public override void Stop() { StopObserving(); base.Stop(); } /// <summary>Adds a local revision to the "pending" set that are awaiting upload:</summary> [InterfaceAudience.Private] private void AddPending(RevisionInternal revisionInternal) { long seq = revisionInternal.GetSequence(); pendingSequences.AddItem(seq); if (seq > maxPendingSequence) { maxPendingSequence = seq; } } /// <summary>Removes a revision from the "pending" set after it's been uploaded.</summary> /// <remarks>Removes a revision from the "pending" set after it's been uploaded. Advances checkpoint. /// </remarks> [InterfaceAudience.Private] private void RemovePending(RevisionInternal revisionInternal) { long seq = revisionInternal.GetSequence(); if (pendingSequences == null || pendingSequences.Count == 0) { Log.W(Log.TagSync, "%s: removePending() called w/ rev: %s, but pendingSequences empty" , this, revisionInternal); return; } bool wasFirst = (seq == pendingSequences.First()); if (!pendingSequences.Contains(seq)) { Log.W(Log.TagSync, "%s: removePending: sequence %s not in set, for rev %s", this, seq, revisionInternal); } pendingSequences.Remove(seq); if (wasFirst) { // If I removed the first pending sequence, can advance the checkpoint: long maxCompleted; if (pendingSequences.Count == 0) { maxCompleted = maxPendingSequence; } else { maxCompleted = pendingSequences.First(); --maxCompleted; } SetLastSequence(System.Convert.ToString(maxCompleted)); } } [InterfaceAudience.Private] internal override void MaybeCreateRemoteDB() { if (!createTarget) { return; } creatingTarget = true; Log.V(Log.TagSync, "Remote db might not exist; creating it..."); Log.V(Log.TagSync, "%s | %s: maybeCreateRemoteDB() calling asyncTaskStarted()", this , Sharpen.Thread.CurrentThread()); AsyncTaskStarted(); SendAsyncRequest("PUT", string.Empty, null, new _RemoteRequestCompletionBlock_152 (this)); } private sealed class _RemoteRequestCompletionBlock_152 : RemoteRequestCompletionBlock { public _RemoteRequestCompletionBlock_152(Pusher _enclosing) { this._enclosing = _enclosing; } public void OnCompletion(object result, Exception e) { try { this._enclosing.creatingTarget = false; if (e != null && e is HttpResponseException && ((HttpResponseException)e).GetStatusCode () != 412) { Log.E(Log.TagSync, this + ": Failed to create remote db", e); this._enclosing.SetError(e); this._enclosing.Stop(); } else { // this is fatal: no db to push to! Log.V(Log.TagSync, "%s: Created remote db", this); this._enclosing.createTarget = false; this._enclosing.BeginReplicating(); } } finally { Log.V(Log.TagSync, "%s | %s: maybeCreateRemoteDB.sendAsyncRequest() calling asyncTaskFinished()" , this, Sharpen.Thread.CurrentThread()); this._enclosing.AsyncTaskFinished(1); } } private readonly Pusher _enclosing; } [InterfaceAudience.Private] public override void BeginReplicating() { Log.D(Log.TagSync, "%s: beginReplicating() called", this); // If we're still waiting to create the remote db, do nothing now. (This method will be // re-invoked after that request finishes; see maybeCreateRemoteDB() above.) if (creatingTarget) { Log.D(Log.TagSync, "%s: creatingTarget == true, doing nothing", this); return; } pendingSequences = Sharpen.Collections.SynchronizedSortedSet(new TreeSet<long>()); try { maxPendingSequence = long.Parse(lastSequence); } catch (FormatException) { Log.W(Log.TagSync, "Error converting lastSequence: %s to long. Using 0", lastSequence ); maxPendingSequence = System.Convert.ToInt64(0); } if (filterName != null) { filter = db.GetFilter(filterName); } if (filterName != null && filter == null) { Log.W(Log.TagSync, "%s: No ReplicationFilter registered for filter '%s'; ignoring" , this, filterName); } // Process existing changes since the last push: long lastSequenceLong = 0; if (lastSequence != null) { lastSequenceLong = long.Parse(lastSequence); } ChangesOptions options = new ChangesOptions(); options.SetIncludeConflicts(true); RevisionList changes = db.ChangesSince(lastSequenceLong, options, filter); if (changes.Count > 0) { batcher.QueueObjects(changes); batcher.Flush(); } // Now listen for future changes (in continuous mode): if (continuous) { observing = true; db.AddChangeListener(this); } } [InterfaceAudience.Private] private void StopObserving() { if (observing) { observing = false; db.RemoveChangeListener(this); } } [InterfaceAudience.Private] public void Changed(Database.ChangeEvent @event) { IList<DocumentChange> changes = @event.GetChanges(); foreach (DocumentChange change in changes) { // Skip revisions that originally came from the database I'm syncing to: Uri source = change.GetSourceUrl(); if (source != null && source.Equals(remote)) { return; } RevisionInternal rev = change.GetAddedRevision(); IDictionary<string, object> paramsFixMe = null; // TODO: these should not be null if (GetLocalDatabase().RunFilter(filter, paramsFixMe, rev)) { AddToInbox(rev); } } } [InterfaceAudience.Private] protected internal override void ProcessInbox(RevisionList changes) { // Generate a set of doc/rev IDs in the JSON format that _revs_diff wants: // <http://wiki.apache.org/couchdb/HttpPostRevsDiff> IDictionary<string, IList<string>> diffs = new Dictionary<string, IList<string>>( ); foreach (RevisionInternal rev in changes) { string docID = rev.GetDocId(); IList<string> revs = diffs.Get(docID); if (revs == null) { revs = new AList<string>(); diffs.Put(docID, revs); } revs.AddItem(rev.GetRevId()); AddPending(rev); } // Call _revs_diff on the target db: Log.V(Log.TagSync, "%s: posting to /_revs_diff", this); Log.V(Log.TagSync, "%s | %s: processInbox() calling asyncTaskStarted()", this, Sharpen.Thread .CurrentThread()); AsyncTaskStarted(); SendAsyncRequest("POST", "/_revs_diff", diffs, new _RemoteRequestCompletionBlock_280 (this, changes)); } private sealed class _RemoteRequestCompletionBlock_280 : RemoteRequestCompletionBlock { public _RemoteRequestCompletionBlock_280(Pusher _enclosing, RevisionList changes) { this._enclosing = _enclosing; this.changes = changes; } public void OnCompletion(object response, Exception e) { try { Log.V(Log.TagSync, "%s: got /_revs_diff response"); IDictionary<string, object> results = (IDictionary<string, object>)response; if (e != null) { this._enclosing.SetError(e); this._enclosing.RevisionFailed(); } else { if (results.Count != 0) { // Go through the list of local changes again, selecting the ones the destination server // said were missing and mapping them to a JSON dictionary in the form _bulk_docs wants: IList<object> docsToSend = new AList<object>(); RevisionList revsToSend = new RevisionList(); foreach (RevisionInternal rev in changes) { // Is this revision in the server's 'missing' list? IDictionary<string, object> properties = null; IDictionary<string, object> revResults = (IDictionary<string, object>)results.Get (rev.GetDocId()); if (revResults == null) { continue; } IList<string> revs = (IList<string>)revResults.Get("missing"); if (revs == null || !revs.Contains(rev.GetRevId())) { this._enclosing.RemovePending(rev); continue; } // Get the revision's properties: EnumSet<Database.TDContentOptions> contentOptions = EnumSet.Of(Database.TDContentOptions .TDIncludeAttachments); if (!this._enclosing.dontSendMultipart && this._enclosing.revisionBodyTransformationBlock == null) { contentOptions.AddItem(Database.TDContentOptions.TDBigAttachmentsFollow); } RevisionInternal loadedRev; try { loadedRev = this._enclosing.db.LoadRevisionBody(rev, contentOptions); properties = new Dictionary<string, object>(rev.GetProperties()); } catch (CouchbaseLiteException) { Log.W(Log.TagSync, "%s Couldn't get local contents of %s", rev, this._enclosing); this._enclosing.RevisionFailed(); continue; } RevisionInternal populatedRev = this._enclosing.TransformRevision(loadedRev); IList<string> possibleAncestors = (IList<string>)revResults.Get("possible_ancestors" ); properties = new Dictionary<string, object>(populatedRev.GetProperties()); IDictionary<string, object> revisions = this._enclosing.db.GetRevisionHistoryDictStartingFromAnyAncestor (populatedRev, possibleAncestors); properties.Put("_revisions", revisions); populatedRev.SetProperties(properties); // Strip any attachments already known to the target db: if (properties.ContainsKey("_attachments")) { // Look for the latest common ancestor and stub out older attachments: int minRevPos = Couchbase.Lite.Replicator.Pusher.FindCommonAncestor(populatedRev, possibleAncestors); Database.StubOutAttachmentsInRevBeforeRevPos(populatedRev, minRevPos + 1, false); properties = populatedRev.GetProperties(); if (!this._enclosing.dontSendMultipart && this._enclosing.UploadMultipartRevision (populatedRev)) { continue; } } if (properties == null || !properties.ContainsKey("_id")) { throw new InvalidOperationException("properties must contain a document _id"); } revsToSend.AddItem(rev); docsToSend.AddItem(properties); } //TODO: port this code from iOS // Post the revisions to the destination: this._enclosing.UploadBulkDocs(docsToSend, revsToSend); } else { // None of the revisions are new to the remote foreach (RevisionInternal revisionInternal in changes) { this._enclosing.RemovePending(revisionInternal); } } } } finally { Log.V(Log.TagSync, "%s | %s: processInbox.sendAsyncRequest() calling asyncTaskFinished()" , this, Sharpen.Thread.CurrentThread()); this._enclosing.AsyncTaskFinished(1); } } private readonly Pusher _enclosing; private readonly RevisionList changes; } /// <summary>Post the revisions to the destination.</summary> /// <remarks> /// Post the revisions to the destination. "new_edits":false means that the server should /// use the given _rev IDs instead of making up new ones. /// </remarks> [InterfaceAudience.Private] protected internal void UploadBulkDocs(IList<object> docsToSend, RevisionList changes ) { int numDocsToSend = docsToSend.Count; if (numDocsToSend == 0) { return; } Log.V(Log.TagSync, "%s: POSTing " + numDocsToSend + " revisions to _bulk_docs: %s" , this, docsToSend); AddToChangesCount(numDocsToSend); IDictionary<string, object> bulkDocsBody = new Dictionary<string, object>(); bulkDocsBody.Put("docs", docsToSend); bulkDocsBody.Put("new_edits", false); Log.V(Log.TagSync, "%s | %s: uploadBulkDocs() calling asyncTaskStarted()", this, Sharpen.Thread.CurrentThread()); AsyncTaskStarted(); SendAsyncRequest("POST", "/_bulk_docs", bulkDocsBody, new _RemoteRequestCompletionBlock_414 (this, changes, numDocsToSend)); } private sealed class _RemoteRequestCompletionBlock_414 : RemoteRequestCompletionBlock { public _RemoteRequestCompletionBlock_414(Pusher _enclosing, RevisionList changes, int numDocsToSend) { this._enclosing = _enclosing; this.changes = changes; this.numDocsToSend = numDocsToSend; } public void OnCompletion(object result, Exception e) { try { if (e == null) { ICollection<string> failedIDs = new HashSet<string>(); // _bulk_docs response is really an array, not a dictionary! IList<IDictionary<string, object>> items = (IList)result; foreach (IDictionary<string, object> item in items) { Status status = this._enclosing.StatusFromBulkDocsResponseItem(item); if (status.IsError()) { // One of the docs failed to save. Log.W(Log.TagSync, "%s: _bulk_docs got an error: %s", item, this); // 403/Forbidden means validation failed; don't treat it as an error // because I did my job in sending the revision. Other statuses are // actual replication errors. if (status.GetCode() != Status.Forbidden) { string docID = (string)item.Get("id"); failedIDs.AddItem(docID); } } } // TODO - port from iOS // NSURL* url = docID ? [_remote URLByAppendingPathComponent: docID] : nil; // error = CBLStatusToNSError(status, url); // Remove from the pending list all the revs that didn't fail: foreach (RevisionInternal revisionInternal in changes) { if (!failedIDs.Contains(revisionInternal.GetDocId())) { this._enclosing.RemovePending(revisionInternal); } } } if (e != null) { this._enclosing.SetError(e); this._enclosing.RevisionFailed(); } else { Log.V(Log.TagSync, "%s: POSTed to _bulk_docs", this._enclosing); } this._enclosing.AddToCompletedChangesCount(numDocsToSend); } finally { Log.V(Log.TagSync, "%s | %s: uploadBulkDocs.sendAsyncRequest() calling asyncTaskFinished()" , this, Sharpen.Thread.CurrentThread()); this._enclosing.AsyncTaskFinished(1); } } private readonly Pusher _enclosing; private readonly RevisionList changes; private readonly int numDocsToSend; } [InterfaceAudience.Private] private bool UploadMultipartRevision(RevisionInternal revision) { MultipartEntity multiPart = null; IDictionary<string, object> revProps = revision.GetProperties(); // TODO: refactor this to IDictionary<string, object> attachments = (IDictionary<string, object>)revProps.Get ("_attachments"); foreach (string attachmentKey in attachments.Keys) { IDictionary<string, object> attachment = (IDictionary<string, object>)attachments .Get(attachmentKey); if (attachment.ContainsKey("follows")) { if (multiPart == null) { multiPart = new MultipartEntity(); try { string json = Manager.GetObjectMapper().WriteValueAsString(revProps); Encoding utf8charset = Sharpen.Extensions.GetEncoding("UTF-8"); multiPart.AddPart("param1", new StringBody(json, "application/json", utf8charset) ); } catch (IOException e) { throw new ArgumentException(e); } } BlobStore blobStore = this.db.GetAttachments(); string base64Digest = (string)attachment.Get("digest"); BlobKey blobKey = new BlobKey(base64Digest); InputStream inputStream = blobStore.BlobStreamForKey(blobKey); if (inputStream == null) { Log.W(Log.TagSync, "Unable to find blob file for blobKey: %s - Skipping upload of multipart revision." , blobKey); multiPart = null; } else { string contentType = null; if (attachment.ContainsKey("content_type")) { contentType = (string)attachment.Get("content_type"); } else { if (attachment.ContainsKey("content-type")) { Log.W(Log.TagSync, "Found attachment that uses content-type" + " field name instead of content_type (see couchbase-lite-android" + " issue #80): %s", attachment); } } multiPart.AddPart(attachmentKey, new InputStreamBody(inputStream, contentType, attachmentKey )); } } } if (multiPart == null) { return false; } string path = string.Format("/%s?new_edits=false", revision.GetDocId()); Log.D(Log.TagSync, "Uploading multipart request. Revision: %s", revision); AddToChangesCount(1); Log.V(Log.TagSync, "%s | %s: uploadMultipartRevision() calling asyncTaskStarted()" , this, Sharpen.Thread.CurrentThread()); AsyncTaskStarted(); SendAsyncMultipartRequest("PUT", path, multiPart, new _RemoteRequestCompletionBlock_542 (this, revision)); // Server doesn't like multipart, eh? Fall back to JSON. //status 415 = "bad_content_type" return true; } private sealed class _RemoteRequestCompletionBlock_542 : RemoteRequestCompletionBlock { public _RemoteRequestCompletionBlock_542(Pusher _enclosing, RevisionInternal revision ) { this._enclosing = _enclosing; this.revision = revision; } public void OnCompletion(object result, Exception e) { try { if (e != null) { if (e is HttpResponseException) { if (((HttpResponseException)e).GetStatusCode() == 415) { this._enclosing.dontSendMultipart = true; this._enclosing.UploadJsonRevision(revision); } } else { Log.E(Log.TagSync, "Exception uploading multipart request", e); this._enclosing.SetError(e); this._enclosing.RevisionFailed(); } } else { Log.V(Log.TagSync, "Uploaded multipart request."); this._enclosing.RemovePending(revision); } } finally { this._enclosing.AddToCompletedChangesCount(1); Log.V(Log.TagSync, "%s | %s: uploadMultipartRevision() calling asyncTaskFinished()" , this, Sharpen.Thread.CurrentThread()); this._enclosing.AsyncTaskFinished(1); } } private readonly Pusher _enclosing; private readonly RevisionInternal revision; } // Fallback to upload a revision if uploadMultipartRevision failed due to the server's rejecting // multipart format. private void UploadJsonRevision(RevisionInternal rev) { // Get the revision's properties: if (!db.InlineFollowingAttachmentsIn(rev)) { error = new CouchbaseLiteException(Status.BadAttachment); RevisionFailed(); return; } Log.V(Log.TagSync, "%s | %s: uploadJsonRevision() calling asyncTaskStarted()", this , Sharpen.Thread.CurrentThread()); AsyncTaskStarted(); string path = string.Format("/%s?new_edits=false", URIUtils.Encode(rev.GetDocId() )); SendAsyncRequest("PUT", path, rev.GetProperties(), new _RemoteRequestCompletionBlock_594 (this, rev)); } private sealed class _RemoteRequestCompletionBlock_594 : RemoteRequestCompletionBlock { public _RemoteRequestCompletionBlock_594(Pusher _enclosing, RevisionInternal rev) { this._enclosing = _enclosing; this.rev = rev; } public void OnCompletion(object result, Exception e) { if (e != null) { this._enclosing.SetError(e); this._enclosing.RevisionFailed(); } else { Log.V(Log.TagSync, "%s: Sent %s (JSON), response=%s", this, rev, result); this._enclosing.RemovePending(rev); } Log.V(Log.TagSync, "%s | %s: uploadJsonRevision() calling asyncTaskFinished()", this , Sharpen.Thread.CurrentThread()); this._enclosing.AsyncTaskFinished(1); } private readonly Pusher _enclosing; private readonly RevisionInternal rev; } // Given a revision and an array of revIDs, finds the latest common ancestor revID // and returns its generation #. If there is none, returns 0. private static int FindCommonAncestor(RevisionInternal rev, IList<string> possibleRevIDs ) { if (possibleRevIDs == null || possibleRevIDs.Count == 0) { return 0; } IList<string> history = Database.ParseCouchDBRevisionHistory(rev.GetProperties()); //rev is missing _revisions property System.Diagnostics.Debug.Assert((history != null)); bool changed = history.RetainAll(possibleRevIDs); string ancestorID = history.Count == 0 ? null : history[0]; if (ancestorID == null) { return 0; } int generation = Database.ParseRevIDNumber(ancestorID); return generation; } } }
namespace SoxConvertCs { partial class MainForm { /// <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.ofdSoxPath = new System.Windows.Forms.OpenFileDialog(); this.tbSoxPath = new System.Windows.Forms.TextBox(); this.btnSoxPath = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.label3 = new System.Windows.Forms.Label(); this.btnOutput = new System.Windows.Forms.Button(); this.tbOutput = new System.Windows.Forms.TextBox(); this.cbType = new System.Windows.Forms.ComboBox(); this.btnConvert = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.btnInput = new System.Windows.Forms.Button(); this.tbInput = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.ofdInput = new System.Windows.Forms.OpenFileDialog(); this.sdOutput = new System.Windows.Forms.SaveFileDialog(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // tbSoxPath // this.tbSoxPath.Location = new System.Drawing.Point(11, 43); this.tbSoxPath.Name = "tbSoxPath"; this.tbSoxPath.Size = new System.Drawing.Size(367, 20); this.tbSoxPath.TabIndex = 0; // // btnSoxPath // this.btnSoxPath.Location = new System.Drawing.Point(384, 40); this.btnSoxPath.Name = "btnSoxPath"; this.btnSoxPath.Size = new System.Drawing.Size(37, 23); this.btnSoxPath.TabIndex = 1; this.btnSoxPath.Text = "..."; this.btnSoxPath.UseVisualStyleBackColor = true; this.btnSoxPath.Click += new System.EventHandler(this.btnSoxPath_Click); // // groupBox1 // this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.btnOutput); this.groupBox1.Controls.Add(this.tbOutput); this.groupBox1.Controls.Add(this.cbType); this.groupBox1.Controls.Add(this.btnConvert); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.btnInput); this.groupBox1.Controls.Add(this.tbInput); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.btnSoxPath); this.groupBox1.Controls.Add(this.tbSoxPath); this.groupBox1.Location = new System.Drawing.Point(12, 12); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(438, 241); this.groupBox1.TabIndex = 2; this.groupBox1.TabStop = false; this.groupBox1.Text = "Sox Convert"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(8, 152); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(88, 13); this.label3.TabIndex = 10; this.label3.Text = "Output Audio File"; // // btnOutput // this.btnOutput.Location = new System.Drawing.Point(384, 165); this.btnOutput.Name = "btnOutput"; this.btnOutput.Size = new System.Drawing.Size(37, 23); this.btnOutput.TabIndex = 9; this.btnOutput.Text = "..."; this.btnOutput.UseVisualStyleBackColor = true; this.btnOutput.Click += new System.EventHandler(this.btnOutput_Click); // // tbOutput // this.tbOutput.Location = new System.Drawing.Point(11, 168); this.tbOutput.Name = "tbOutput"; this.tbOutput.Size = new System.Drawing.Size(367, 20); this.tbOutput.TabIndex = 8; // // cbType // this.cbType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbType.FormattingEnabled = true; this.cbType.Location = new System.Drawing.Point(11, 122); this.cbType.Name = "cbType"; this.cbType.Size = new System.Drawing.Size(367, 21); this.cbType.TabIndex = 7; this.cbType.SelectedIndexChanged += new System.EventHandler(this.cbType_SelectedIndexChanged); // // btnConvert // this.btnConvert.Location = new System.Drawing.Point(11, 204); this.btnConvert.Name = "btnConvert"; this.btnConvert.Size = new System.Drawing.Size(410, 23); this.btnConvert.TabIndex = 6; this.btnConvert.Text = "Convert"; this.btnConvert.UseVisualStyleBackColor = true; this.btnConvert.Click += new System.EventHandler(this.btnConvert_Click); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(8, 69); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(80, 13); this.label2.TabIndex = 5; this.label2.Text = "Input Audio File"; // // btnInput // this.btnInput.Location = new System.Drawing.Point(384, 82); this.btnInput.Name = "btnInput"; this.btnInput.Size = new System.Drawing.Size(37, 23); this.btnInput.TabIndex = 4; this.btnInput.Text = "..."; this.btnInput.UseVisualStyleBackColor = true; this.btnInput.Click += new System.EventHandler(this.btnInput_Click); // // tbInput // this.tbInput.Location = new System.Drawing.Point(11, 85); this.tbInput.Name = "tbInput"; this.tbInput.Size = new System.Drawing.Size(367, 20); this.tbInput.TabIndex = 3; this.tbInput.TextChanged += new System.EventHandler(this.tbInput_TextChanged); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(8, 27); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(50, 13); this.label1.TabIndex = 2; this.label1.Text = "Sox Path"; // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(467, 268); this.Controls.Add(this.groupBox1); this.Name = "MainForm"; this.Text = "Sox Convert"; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.OpenFileDialog ofdSoxPath; private System.Windows.Forms.TextBox tbSoxPath; private System.Windows.Forms.Button btnSoxPath; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button btnOutput; private System.Windows.Forms.TextBox tbOutput; private System.Windows.Forms.ComboBox cbType; private System.Windows.Forms.Button btnConvert; private System.Windows.Forms.Label label2; private System.Windows.Forms.Button btnInput; private System.Windows.Forms.TextBox tbInput; private System.Windows.Forms.OpenFileDialog ofdInput; private System.Windows.Forms.SaveFileDialog sdOutput; } }
#if !SILVERLIGHT && !MONOTOUCH && !XBOX && !ANDROIDINDIE using System; using System.IO; using System.Net; using System.Xml; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; using ServiceStack.Common.Utils; using ServiceStack.ServiceHost; using ServiceStack.ServiceInterface.ServiceModel; namespace ServiceStack.ServiceClient.Web { /// <summary> /// Adds the singleton instance of <see cref="CookieManagerMessageInspector"/> to an endpoint on the client. /// </summary> /// <remarks> /// Based on http://megakemp.wordpress.com/2009/02/06/managing-shared-cookies-in-wcf/ /// </remarks> public class CookieManagerEndpointBehavior : IEndpointBehavior { public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { return; } /// <summary> /// Adds the singleton of the <see cref="ClientIdentityMessageInspector"/> class to the client endpoint's message inspectors. /// </summary> /// <param name="endpoint">The endpoint that is to be customized.</param> /// <param name="clientRuntime">The client runtime to be customized.</param> public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) { var cm = CookieManagerMessageInspector.Instance; cm.Uri = endpoint.ListenUri.AbsoluteUri; clientRuntime.MessageInspectors.Add(cm); } public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { return; } public void Validate(ServiceEndpoint endpoint) { return; } } /// <summary> /// Maintains a copy of the cookies contained in the incoming HTTP response received from any service /// and appends it to all outgoing HTTP requests. /// </summary> /// <remarks> /// This class effectively allows to send any received HTTP cookies to different services, /// reproducing the same functionality available in ASMX Web Services proxies with the <see cref="System.Net.CookieContainer"/> class. /// Based on http://megakemp.wordpress.com/2009/02/06/managing-shared-cookies-in-wcf/ /// </remarks> public class CookieManagerMessageInspector : IClientMessageInspector { private static CookieManagerMessageInspector instance; private CookieContainer cookieContainer; public string Uri { get; set; } /// <summary> /// Initializes a new instance of the <see cref="ClientIdentityMessageInspector"/> class. /// </summary> public CookieManagerMessageInspector() { cookieContainer = new CookieContainer(); Uri = "http://tempuri.org"; } public CookieManagerMessageInspector(string uri) { cookieContainer = new CookieContainer(); Uri = uri; } /// <summary> /// Gets the singleton <see cref="ClientIdentityMessageInspector" /> instance. /// </summary> public static CookieManagerMessageInspector Instance { get { if (instance == null) { instance = new CookieManagerMessageInspector(); } return instance; } } /// <summary> /// Inspects a message after a reply message is received but prior to passing it back to the client application. /// </summary> /// <param name="reply">The message to be transformed into types and handed back to the client application.</param> /// <param name="correlationState">Correlation state data.</param> public void AfterReceiveReply(ref Message reply, object correlationState) { var httpResponse = reply.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty; if (httpResponse != null) { string cookie = httpResponse.Headers[HttpResponseHeader.SetCookie]; if (!string.IsNullOrEmpty(cookie)) { cookieContainer.SetCookies(new System.Uri(Uri), cookie); } } } /// <summary> /// Inspects a message before a request message is sent to a service. /// </summary> /// <param name="request">The message to be sent to the service.</param> /// <param name="channel">The client object channel.</param> /// <returns> /// <strong>Null</strong> since no message correlation is used. /// </returns> public object BeforeSendRequest(ref Message request, IClientChannel channel) { HttpRequestMessageProperty httpRequest; // The HTTP request object is made available in the outgoing message only when // the Visual Studio Debugger is attacched to the running process if (!request.Properties.ContainsKey(HttpRequestMessageProperty.Name)) { request.Properties.Add(HttpRequestMessageProperty.Name, new HttpRequestMessageProperty()); } httpRequest = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name]; httpRequest.Headers.Add(HttpRequestHeader.Cookie, cookieContainer.GetCookieHeader(new System.Uri(Uri))); return null; } } public abstract class WcfServiceClient : IWcfServiceClient { const string XPATH_SOAP_FAULT = "/s:Fault"; const string XPATH_SOAP_FAULT_REASON = "/s:Fault/s:Reason"; const string NAMESPACE_SOAP = "http://www.w3.org/2003/05/soap-envelope"; const string NAMESPACE_SOAP_ALIAS = "s"; public string Uri { get; set; } public abstract void SetProxy(Uri proxyAddress); protected abstract MessageVersion MessageVersion { get; } protected abstract Binding Binding { get; } /// <summary> /// Specifies if cookies should be stored /// </summary> // CCB Custom public bool StoreCookies { get; set; } public WcfServiceClient() { // CCB Custom this.StoreCookies = true; } private static XmlNamespaceManager GetNamespaceManager(XmlDocument doc) { var nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace(NAMESPACE_SOAP_ALIAS, NAMESPACE_SOAP); return nsmgr; } private static Exception CreateException(Exception e, XmlReader reader) { var doc = new XmlDocument(); doc.Load(reader); var node = doc.SelectSingleNode(XPATH_SOAP_FAULT, GetNamespaceManager(doc)); if (node != null) { string errMsg = null; var nodeReason = doc.SelectSingleNode(XPATH_SOAP_FAULT_REASON, GetNamespaceManager(doc)); if (nodeReason != null) { errMsg = nodeReason.FirstChild.InnerXml; } return new Exception(string.Format("SOAP FAULT '{0}': {1}", errMsg, node.InnerXml), e); } return e; } private ServiceEndpoint SyncReply { get { var contract = new ContractDescription("ServiceStack.ServiceClient.Web.ISyncReply", "http://services.servicestack.net/"); var addr = new EndpointAddress(Uri); var endpoint = new ServiceEndpoint(contract, Binding, addr); return endpoint; } } public Message Send(object request) { return Send(request, request.GetType().Name); } public Message Send(object request, string action) { return Send(Message.CreateMessage(MessageVersion, action, request)); } public Message Send(XmlReader reader, string action) { return Send(Message.CreateMessage(MessageVersion, action, reader)); } public Message Send(Message message) { using (var client = new GenericProxy<ISyncReply>(SyncReply)) { // CCB Custom...add behavior to propagate cookies across SOAP method calls if (StoreCookies) client.ChannelFactory.Endpoint.Behaviors.Add(new CookieManagerEndpointBehavior()); var response = client.Proxy.Send(message); return response; } } public static T GetBody<T>(Message message) { var buffer = message.CreateBufferedCopy(int.MaxValue); try { return buffer.CreateMessage().GetBody<T>(); } catch (Exception ex) { throw CreateException(ex, buffer.CreateMessage().GetReaderAtBodyContents()); } } public T Send<T>(object request) { try { var responseMsg = Send(request); var response = responseMsg.GetBody<T>(); var responseStatus = GetResponseStatus(response); if (responseStatus != null && !string.IsNullOrEmpty(responseStatus.ErrorCode)) { throw new WebServiceException(responseStatus.Message, null) { StatusCode = 500, ResponseDto = response, StatusDescription = responseStatus.Message, }; } return response; } catch (WebServiceException webEx) { throw; } catch (Exception ex) { var webEx = ex as WebException ?? ex.InnerException as WebException; if (webEx == null) { throw new WebServiceException(ex.Message, ex) { StatusCode = 500, }; } var httpEx = webEx.Response as HttpWebResponse; throw new WebServiceException(webEx.Message, webEx) { StatusCode = httpEx != null ? (int)httpEx.StatusCode : 500 }; } } public TResponse Send<TResponse>(IReturn<TResponse> request) { return Send<TResponse>((object)request); } public void Send(IReturnVoid request) { throw new NotImplementedException(); } public ResponseStatus GetResponseStatus(object response) { if (response == null) return null; var hasResponseStatus = response as IHasResponseStatus; if (hasResponseStatus != null) return hasResponseStatus.ResponseStatus; var propertyInfo = response.GetType().GetProperty("ResponseStatus"); if (propertyInfo == null) return null; return ReflectionUtils.GetProperty(response, propertyInfo) as ResponseStatus; } public TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload, string mimeType) { throw new NotImplementedException(); } public TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, string mimeType) { throw new NotImplementedException(); } public void SendOneWay(object request) { SendOneWay(request, request.GetType().Name); } public void SendOneWay(string relativeOrAbsoluteUrl, object request) { SendOneWay(Message.CreateMessage(MessageVersion, relativeOrAbsoluteUrl, request)); } public void SendOneWay(object request, string action) { SendOneWay(Message.CreateMessage(MessageVersion, action, request)); } public void SendOneWay(XmlReader reader, string action) { SendOneWay(Message.CreateMessage(MessageVersion, action, reader)); } public void SendOneWay(Message message) { using (var client = new GenericProxy<IOneWay>(SyncReply)) { client.Proxy.SendOneWay(message); } } public void SendAsync<TResponse>(object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void SetCredentials(string userName, string password) { throw new NotImplementedException(); } public void GetAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void GetAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void DeleteAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void DeleteAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void PostAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void PostAsync<TResponse>(string relativeOrAbsoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void PutAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void PutAsync<TResponse>(string relativeOrAbsoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void CustomMethodAsync<TResponse>(string httpVerb, IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void CancelAsync() { throw new NotImplementedException(); } public void Dispose() { } public TResponse PostFileWithRequest<TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload, object request) { throw new NotImplementedException(); } public TResponse PostFileWithRequest<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, object request) { throw new NotImplementedException(); } } } #endif
namespace TreeviewPrinting { using System; using System.Drawing; using System.Drawing.Printing; using System.Globalization; using System.Runtime.InteropServices; using System.Windows.Forms; public class PrintHelper { #region Fields private readonly PrintDocument printDoc; private Image controlImage; private PrintDirection currentDir; private Point lastPrintPosition; private int nodeHeight; private int pageNumber; private int scrollBarHeight; private int scrollBarWidth; private string title = string.Empty; #endregion #region Constructors and Destructors public PrintHelper() { this.lastPrintPosition = new Point(0, 0); this.printDoc = new PrintDocument(); this.printDoc.BeginPrint += this.PrintDocBeginPrint; this.printDoc.PrintPage += this.PrintDocPrintPage; this.printDoc.EndPrint += this.PrintDocEndPrint; } #endregion #region Enums private enum PrintDirection { Horizontal, Vertical } #endregion #region Public Methods and Operators /// <summary> /// Shows a PrintPreview dialog displaying the Tree control passed in. /// </summary> /// <param name="tree">TreeView to print preview</param> /// <param name="reportTitle"></param> public void PrintPreviewTree(TreeView tree, string reportTitle) { this.title = reportTitle; this.PrepareTreeImage(tree); var pp = new PrintPreviewDialog { Document = this.printDoc }; pp.Show(); } /// <summary> /// Prints a tree /// </summary> /// <param name="tree">TreeView to print</param> /// <param name="reportTitle"></param> public void PrintTree(TreeView tree, string reportTitle) { this.title = reportTitle; this.PrepareTreeImage(tree); var pd = new PrintDialog { Document = this.printDoc }; if (pd.ShowDialog() == DialogResult.OK) { this.printDoc.Print(); } } #endregion #region Methods [DllImport("gdi32.dll")] private static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int width, int height); [DllImport("user32.dll")] private static extern IntPtr GetDC(IntPtr hWnd); [DllImport("user32.dll")] private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); [DllImport("user32.dll")] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, int lParam); // Returns an image of the specified width and height, of a control represented by handle. private Image GetImage(IntPtr handle, int width, int height) { IntPtr screenDC = GetDC(IntPtr.Zero); IntPtr hbm = CreateCompatibleBitmap(screenDC, width, height); Image image = Image.FromHbitmap(hbm); Graphics g = Graphics.FromImage(image); IntPtr hdc = g.GetHdc(); SendMessage(handle, 0x0318 /*WM_PRINTCLIENT*/, hdc, (0x00000010 | 0x00000004 | 0x00000002)); g.ReleaseHdc(hdc); ReleaseDC(IntPtr.Zero, screenDC); return image; } /// <summary> /// Gets an image that shows the entire tree, not just what is visible on the form /// </summary> /// <param name="tree"></param> private void PrepareTreeImage(TreeView tree) { this.scrollBarWidth = tree.Width - tree.ClientSize.Width; this.scrollBarHeight = tree.Height - tree.ClientSize.Height; tree.Nodes[0].EnsureVisible(); int height = tree.Nodes[0].Bounds.Height; this.nodeHeight = height; int width = tree.Nodes[0].Bounds.Right; TreeNode node = tree.Nodes[0].NextVisibleNode; while (node != null) { height += node.Bounds.Height; if (node.Bounds.Right > width) { width = node.Bounds.Right; } node = node.NextVisibleNode; } //keep track of the original tree settings int tempHeight = tree.Height; int tempWidth = tree.Width; BorderStyle tempBorder = tree.BorderStyle; bool tempScrollable = tree.Scrollable; TreeNode selectedNode = tree.SelectedNode; //setup the tree to take the snapshot tree.SelectedNode = null; DockStyle tempDock = tree.Dock; tree.Height = height + this.scrollBarHeight; tree.Width = width + this.scrollBarWidth; tree.BorderStyle = BorderStyle.None; tree.Dock = DockStyle.None; //get the image of the tree // .Net 2.0 supports drawing controls onto bitmaps natively now // However, the full tree didn't get drawn when I tried it, so I am // sticking with the P/Invoke calls //_controlImage = new Bitmap(height, width); //Bitmap bmp = _controlImage as Bitmap; //tree.DrawToBitmap(bmp, tree.Bounds); this.controlImage = this.GetImage(tree.Handle, tree.Width, tree.Height); //reset the tree to its original settings tree.BorderStyle = tempBorder; tree.Width = tempWidth; tree.Height = tempHeight; tree.Dock = tempDock; tree.Scrollable = tempScrollable; tree.SelectedNode = selectedNode; //give the window time to update Application.DoEvents(); } private void PrintDocEndPrint(object sender, PrintEventArgs e) { this.controlImage.Dispose(); } private void PrintDocBeginPrint(object sender, PrintEventArgs e) { this.lastPrintPosition = new Point(0, 0); this.currentDir = PrintDirection.Horizontal; this.pageNumber = 0; } private void PrintDocPrintPage(object sender, PrintPageEventArgs e) { this.pageNumber++; Graphics g = e.Graphics; var sourceRect = new Rectangle(this.lastPrintPosition, e.MarginBounds.Size); Rectangle destRect = e.MarginBounds; if ((sourceRect.Height % this.nodeHeight) > 0) { sourceRect.Height -= (sourceRect.Height % this.nodeHeight); } g.DrawImage(this.controlImage, destRect, sourceRect, GraphicsUnit.Pixel); //check to see if we need more pages if ((this.controlImage.Height - this.scrollBarHeight) > sourceRect.Bottom || (this.controlImage.Width - this.scrollBarWidth) > sourceRect.Right) { //need more pages e.HasMorePages = true; } if (this.currentDir == PrintDirection.Horizontal) { if (sourceRect.Right < (this.controlImage.Width - this.scrollBarWidth)) { //still need to print horizontally this.lastPrintPosition.X += (sourceRect.Width + 1); } else { this.lastPrintPosition.X = 0; this.lastPrintPosition.Y += (sourceRect.Height + 1); this.currentDir = PrintDirection.Vertical; } } else if (this.currentDir == PrintDirection.Vertical && sourceRect.Right < (this.controlImage.Width - this.scrollBarWidth)) { this.currentDir = PrintDirection.Horizontal; this.lastPrintPosition.X += (sourceRect.Width + 1); } else { this.lastPrintPosition.Y += (sourceRect.Height + 1); } //print footer Brush brush = new SolidBrush(Color.Black); string footer = this.pageNumber.ToString(NumberFormatInfo.CurrentInfo); var f = new Font(FontFamily.GenericSansSerif, 10f); SizeF footerSize = g.MeasureString(footer, f); var pageBottomCenter = new PointF(x: e.PageBounds.Width / 2, y: e.MarginBounds.Bottom + ((e.PageBounds.Bottom - e.MarginBounds.Bottom) / 2)); var footerLocation = new PointF( pageBottomCenter.X - (footerSize.Width / 2), pageBottomCenter.Y - (footerSize.Height / 2)); g.DrawString(footer, f, brush, footerLocation); //print header if (this.pageNumber == 1 && this.title.Length > 0) { var headerFont = new Font(FontFamily.GenericSansSerif, 24f, FontStyle.Bold, GraphicsUnit.Point); SizeF headerSize = g.MeasureString(this.title, headerFont); var headerLocation = new PointF(x: e.MarginBounds.Left, y: ((e.MarginBounds.Top - e.PageBounds.Top) / 2) - (headerSize.Height / 2)); g.DrawString(this.title, headerFont, brush, headerLocation); } } #endregion //External function declarations } }
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Tests.Core.Extensions; using Tests.Core.ManagedElasticsearch.Clusters; using Tests.Domain; using Tests.Framework.EndpointTests; using Tests.Framework.EndpointTests.TestState; namespace Tests.Document.Multiple; public class BulkApiTests : NdJsonApiIntegrationTestBase<WritableCluster, BulkResponse, BulkRequestDescriptor, BulkRequest> { public BulkApiTests(WritableCluster cluster, EndpointUsage usage) : base(cluster, usage) { } protected override bool ExpectIsValid => true; protected override IReadOnlyList<object> ExpectNdjson => new List<object> { new Dictionary<string, object> { { "index", new { _id = Project.Instance.Name, pipeline = "pipeline", routing = Project.Instance.Name } } }, Project.InstanceAnonymous, new Dictionary<string, object> { { "update", new { _id = Project.Instance.Name } } }, new { doc = new { leadDeveloper = new { firstName = "martijn" } } }, new Dictionary<string, object> { { "create", new { _id = Project.Instance.Name + "1", routing = Project.Instance.Name } } }, Project.InstanceAnonymous, new Dictionary<string, object> { { "delete", new { _id = Project.Instance.Name + "1", routing = Project.Instance.Name } } }, new Dictionary<string, object> { { "create", new { _id = Project.Instance.Name + "2", routing = Project.Instance.Name } } }, Project.InstanceAnonymous, new Dictionary<string, object> { { "update", new { _id = Project.Instance.Name + "2", routing = Project.Instance.Name } } }, new Dictionary<string, object> { { "script", new { source = "ctx._source.numberOfCommits = params.commits", @params = new { commits = 30 }, lang = "painless" } } } }; protected override int ExpectStatusCode => 200; protected override Action<BulkRequestDescriptor> Fluent => d => d .Index(CallIsolatedValue) .Pipeline("default-pipeline") .Index(Project.Instance, b => b.Pipeline("pipeline")) .Update<Project, object>(b => b.Doc(new { leadDeveloper = new { firstName = "martijn" } }).Id(Project.Instance.Name)) .Create(Project.Instance, b => b.Id(Project.Instance.Name + "1")) .Delete(b => b.Id(Project.Instance.Name + "1").Routing(Project.Instance.Name)) .Create(Project.Instance, b => b.Id(Project.Instance.Name + "2")) .Update<Project>(b => b .Id(Project.Instance.Name + "2") .Routing(Project.Instance.Name) .Script(s => s .Source("ctx._source.numberOfCommits = params.commits") .Params(p => p.Add("commits", 30)) .Language("painless") ) ); protected override HttpMethod HttpMethod => HttpMethod.POST; protected override BulkRequest Initializer => new(CallIsolatedValue) { Pipeline = "default-pipeline", Operations = new List<IBulkOperation> { new BulkIndexOperation<Project>(Project.Instance) { Pipeline = "pipeline" }, new BulkUpdateOperation<Project, object>(Project.Instance.Name) { Doc = new { leadDeveloper = new { firstName = "martijn" } } }, new BulkCreateOperation<Project>(Project.Instance) { Id = Project.Instance.Name + "1", }, new BulkDeleteOperation(Project.Instance.Name + "1") { Routing = Project.Instance.Name }, new BulkCreateOperation<Project>(Project.Instance) { Id = Project.Instance.Name + "2", }, new BulkUpdateOperation<Project, object>(Project.Instance.Name + "2") { Routing = Project.Instance.Name, Script = new InlineScript("ctx._source.numberOfCommits = params.commits") { Params = new Dictionary<string, object> { { "commits", 30 } }, Language = "painless" } } } }; protected override bool SupportsDeserialization => false; protected override string ExpectedUrlPathAndQuery => $"/{CallIsolatedValue}/_bulk?pipeline=default-pipeline"; protected override LazyResponses ClientUsage() => Calls( (client, f) => client.Bulk(f), (client, f) => client.BulkAsync(f), (client, r) => client.Bulk(r), (client, r) => client.BulkAsync(r) ); protected override void IntegrationSetup(IElasticsearchClient client, CallUniqueValues values) { // TODO - REPLACE WITH FLUENT var req = new { processors = new object[] { new Dictionary<string, object> { { "set", new { field = "description", value = "Default" } } } } }; _ = Client.Transport.Request<BytesResponse>(HttpMethod.PUT, $"_ingest/pipeline/default-pipeline", PostData.Serializable(req)); req = new { processors = new object[] { new Dictionary<string, object> { { "set", new { field = "description", value = "Overridden" } } } } }; _ = Client.Transport.Request<BytesResponse>(HttpMethod.PUT, $"_ingest/pipeline/pipeline", PostData.Serializable(req)); //var pipelineResponse = client.Ingest.PutPipeline(new IngestPutPipelineRequest("pipeline") //{ // Processors = new ProcessorContainer[] // { // new ProcessorContainer(new SetProcessor { Field = "description", Value = "Default" } ) // } //}); //pipelineResponse.ShouldBeValid("Failed to set up pipeline named 'default-pipeline' required for bulk {p"); //pipelineResponse = client.Ingest.PutPipeline(new IngestPutPipelineRequest("pipeline") //{ // Processors = new ProcessorContainer[] // { // new ProcessorContainer(new SetProcessor { Field = "description", Value = "Overridden" } ) // } //}); //pipelineResponse.ShouldBeValid($"Failed to set up pipeline named 'pipeline' required for bulk"); base.IntegrationSetup(client, values); } protected override void ExpectResponse(BulkResponse response) { response.Took.Should().BeGreaterThan(0); response.Errors.Should().BeFalse(); response.ItemsWithErrors.Should().NotBeNull().And.BeEmpty(); response.Items.Should().NotBeEmpty(); foreach (var item in response.Items) { item.Index.Should().Be(CallIsolatedValue); item.Status.Should().BeGreaterThan(100); item.Version.Should().BeGreaterThan(0); item.Id.Should().NotBeNullOrWhiteSpace(); item.IsValid.Should().BeTrue(); item.Shards.Should().NotBeNull(); item.Shards.Total.Should().BeGreaterThan(0); item.Shards.Successful.Should().BeGreaterThan(0); item.SeqNo.Should().BeGreaterOrEqualTo(0); item.PrimaryTerm.Should().BeGreaterThan(0); item.Result.Should().NotBeNullOrEmpty(); } // TODO - Re-enable once Source endpoint is generated and implemented var project1 = Client.Source<Project>(Project.Instance.Name, p => p.Index(CallIsolatedValue)).Body; project1.LeadDeveloper.FirstName.Should().Be("martijn"); project1.Description.Should().Be("Overridden"); var project2 = Client.Source<Project>(Project.Instance.Name + "2", p => p .Index(CallIsolatedValue) .Routing(Project.Instance.Name)).Body; project2.Description.Should().Be("Default"); project2.NumberOfCommits.Should().Be(30); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Reflection; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { /* * Define the different access levels that symbols can have. */ internal enum ACCESS { ACC_UNKNOWN, // Not yet determined. ACC_PRIVATE, ACC_INTERNAL, ACC_PROTECTED, ACC_INTERNALPROTECTED, // internal OR protected ACC_PUBLIC } // The kinds of aggregates. internal enum AggKindEnum { Unknown, Class, Delegate, Interface, Struct, Enum, Lim } ///////////////////////////////////////////////////////////////////////////////// // Special constraints. [Flags] internal enum SpecCons { None = 0x00, New = 0x01, Ref = 0x02, Val = 0x04 } // ---------------------------------------------------------------------------- // // Symbol - the base symbol. // // ---------------------------------------------------------------------------- internal abstract class Symbol { private SYMKIND _kind; // the symbol kind private ACCESS _access; // access level // If this is true, then we had an error the first time so do not give an error the second time. public Name name; // name of the symbol public ParentSymbol parent; // parent of the symbol public Symbol nextChild; // next child of this parent public Symbol nextSameName; // next child of this parent with same name. public ACCESS GetAccess() { Debug.Assert(_access != ACCESS.ACC_UNKNOWN); return _access; } public void SetAccess(ACCESS access) { _access = access; } public SYMKIND getKind() { return _kind; } public void setKind(SYMKIND kind) { _kind = kind; } public symbmask_t mask() { return (symbmask_t)(1 << (int)_kind); } public CType getType() { if (this is MethodOrPropertySymbol methProp) { return methProp.RetType; } if (this is FieldSymbol field) { return field.GetType(); } if (this is EventSymbol ev) { return ev.type; } return null; } public bool isStatic { get { if (this is FieldSymbol field) { return field.isStatic; } if (this is EventSymbol ev) { return ev.isStatic; } if (this is MethodOrPropertySymbol methProp) { return methProp.isStatic; } return this is AggregateSymbol; } } private Assembly GetAssembly() { switch (_kind) { case SYMKIND.SK_MethodSymbol: case SYMKIND.SK_PropertySymbol: case SYMKIND.SK_FieldSymbol: case SYMKIND.SK_EventSymbol: case SYMKIND.SK_TypeParameterSymbol: return ((AggregateSymbol)parent).AssociatedAssembly; case SYMKIND.SK_AggregateDeclaration: return ((AggregateDeclaration)this).GetAssembly(); case SYMKIND.SK_AggregateSymbol: return ((AggregateSymbol)this).AssociatedAssembly; default: // Should never call this with any other kind. Debug.Assert(false, "GetAssemblyID called on bad sym kind"); return null; } } /* * returns the assembly id for the declaration of this symbol */ private bool InternalsVisibleTo(Assembly assembly) { switch (_kind) { case SYMKIND.SK_MethodSymbol: case SYMKIND.SK_PropertySymbol: case SYMKIND.SK_FieldSymbol: case SYMKIND.SK_EventSymbol: case SYMKIND.SK_TypeParameterSymbol: return ((AggregateSymbol)parent).InternalsVisibleTo(assembly); case SYMKIND.SK_AggregateDeclaration: return ((AggregateDeclaration)this).Agg().InternalsVisibleTo(assembly); case SYMKIND.SK_AggregateSymbol: return ((AggregateSymbol)this).InternalsVisibleTo(assembly); default: // Should never call this with any other kind. Debug.Assert(false, "InternalsVisibleTo called on bad sym kind"); return false; } } public bool SameAssemOrFriend(Symbol sym) { Assembly assem = GetAssembly(); return assem == sym.GetAssembly() || sym.InternalsVisibleTo(assem); } /* Returns if the symbol is virtual. */ public bool IsVirtual() { switch (_kind) { case SYMKIND.SK_MethodSymbol: return ((MethodSymbol)this).isVirtual; case SYMKIND.SK_EventSymbol: MethodSymbol methAdd = ((EventSymbol)this).methAdd; return methAdd != null && methAdd.isVirtual; case SYMKIND.SK_PropertySymbol: PropertySymbol prop = ((PropertySymbol)this); MethodSymbol meth = prop.GetterMethod ?? prop.SetterMethod; return meth != null && meth.isVirtual; default: return false; } } public bool IsOverride() { switch (_kind) { case SYMKIND.SK_MethodSymbol: case SYMKIND.SK_PropertySymbol: return ((MethodOrPropertySymbol)this).isOverride; case SYMKIND.SK_EventSymbol: return ((EventSymbol)this).isOverride; default: return false; } } public bool IsHideByName() { switch (_kind) { case SYMKIND.SK_MethodSymbol: case SYMKIND.SK_PropertySymbol: return ((MethodOrPropertySymbol)this).isHideByName; case SYMKIND.SK_EventSymbol: MethodSymbol methAdd = ((EventSymbol)this).methAdd; return methAdd != null && methAdd.isHideByName; default: return true; } } // Returns the virtual that this sym overrides (if IsOverride() is true), null otherwise. public Symbol SymBaseVirtual() { return (this as MethodOrPropertySymbol)?.swtSlot.Sym; } /* * returns true if this symbol is a normal symbol visible to the user */ public bool isUserCallable() { return !(this is MethodSymbol methSym) || methSym.isUserCallable(); } } }
using System; using Csla; using Invoices.DataAccess; namespace Invoices.Business { /// <summary> /// SupplierInfoDetail (read only object).<br/> /// This is a generated <see cref="SupplierInfoDetail"/> business object. /// This class is a root object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="Products"/> of type <see cref="SupplierProductList"/> (1:M relation to <see cref="SupplierProductInfo"/>) /// </remarks> [Serializable] public partial class SupplierInfoDetail : ReadOnlyBase<SupplierInfoDetail> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="SupplierId"/> property. /// </summary> public static readonly PropertyInfo<int> SupplierIdProperty = RegisterProperty<int>(p => p.SupplierId, "Supplier Id"); /// <summary> /// For simplicity sake, use the VAT number (no auto increment here). /// </summary> /// <value>The Supplier Id.</value> public int SupplierId { get { return GetProperty(SupplierIdProperty); } } /// <summary> /// Maintains metadata about <see cref="Name"/> property. /// </summary> public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(p => p.Name, "Name"); /// <summary> /// Gets the Name. /// </summary> /// <value>The Name.</value> public string Name { get { return GetProperty(NameProperty); } } /// <summary> /// Maintains metadata about <see cref="AddressLine1"/> property. /// </summary> public static readonly PropertyInfo<string> AddressLine1Property = RegisterProperty<string>(p => p.AddressLine1, "Address Line1"); /// <summary> /// Gets the Address Line1. /// </summary> /// <value>The Address Line1.</value> public string AddressLine1 { get { return GetProperty(AddressLine1Property); } } /// <summary> /// Maintains metadata about <see cref="AddressLine2"/> property. /// </summary> public static readonly PropertyInfo<string> AddressLine2Property = RegisterProperty<string>(p => p.AddressLine2, "Address Line2"); /// <summary> /// Gets the Address Line2. /// </summary> /// <value>The Address Line2.</value> public string AddressLine2 { get { return GetProperty(AddressLine2Property); } } /// <summary> /// Maintains metadata about <see cref="ZipCode"/> property. /// </summary> public static readonly PropertyInfo<string> ZipCodeProperty = RegisterProperty<string>(p => p.ZipCode, "Zip Code"); /// <summary> /// Gets the Zip Code. /// </summary> /// <value>The Zip Code.</value> public string ZipCode { get { return GetProperty(ZipCodeProperty); } } /// <summary> /// Maintains metadata about <see cref="State"/> property. /// </summary> public static readonly PropertyInfo<string> StateProperty = RegisterProperty<string>(p => p.State, "State"); /// <summary> /// Gets the State. /// </summary> /// <value>The State.</value> public string State { get { return GetProperty(StateProperty); } } /// <summary> /// Maintains metadata about <see cref="Country"/> property. /// </summary> public static readonly PropertyInfo<byte?> CountryProperty = RegisterProperty<byte?>(p => p.Country, "Country"); /// <summary> /// Gets the Country. /// </summary> /// <value>The Country.</value> public byte? Country { get { return GetProperty(CountryProperty); } } /// <summary> /// Maintains metadata about child <see cref="Products"/> property. /// </summary> public static readonly PropertyInfo<SupplierProductList> ProductsProperty = RegisterProperty<SupplierProductList>(p => p.Products, "Products"); /// <summary> /// Gets the Products ("lazy load" child property). /// </summary> /// <value>The Products.</value> public SupplierProductList Products { get { #if ASYNC if (!FieldManager.FieldExists(ProductsProperty)) { LoadProperty(ProductsProperty, null); DataPortal.BeginFetch<SupplierProductList>(ReadProperty(SupplierIdProperty), (o, e) => { if (e.Error != null) throw e.Error; else { // set the property so OnPropertyChanged is raised Products = e.Object; } }); return null; } else { return GetProperty(ProductsProperty); } #else if (!FieldManager.FieldExists(ProductsProperty)) Products = DataPortal.Fetch<SupplierProductList>(ReadProperty(SupplierIdProperty)); return GetProperty(ProductsProperty); #endif } private set { LoadProperty(ProductsProperty, value); OnPropertyChanged(ProductsProperty); } } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="SupplierInfoDetail"/> object, based on given parameters. /// </summary> /// <param name="supplierId">The SupplierId parameter of the SupplierInfoDetail to fetch.</param> /// <returns>A reference to the fetched <see cref="SupplierInfoDetail"/> object.</returns> public static SupplierInfoDetail GetSupplierInfoDetail(int supplierId) { return DataPortal.Fetch<SupplierInfoDetail>(supplierId); } /// <summary> /// Factory method. Asynchronously loads a <see cref="SupplierInfoDetail"/> object, based on given parameters. /// </summary> /// <param name="supplierId">The SupplierId parameter of the SupplierInfoDetail to fetch.</param> /// <param name="callback">The completion callback method.</param> public static void GetSupplierInfoDetail(int supplierId, EventHandler<DataPortalResult<SupplierInfoDetail>> callback) { DataPortal.BeginFetch<SupplierInfoDetail>(supplierId, callback); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="SupplierInfoDetail"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public SupplierInfoDetail() { // Use factory methods and do not use direct creation. } #endregion #region Data Access /// <summary> /// Loads a <see cref="SupplierInfoDetail"/> object from the database, based on given criteria. /// </summary> /// <param name="supplierId">The Supplier Id.</param> protected void DataPortal_Fetch(int supplierId) { var args = new DataPortalHookArgs(supplierId); OnFetchPre(args); using (var dalManager = DalFactoryInvoices.GetManager()) { var dal = dalManager.GetProvider<ISupplierInfoDetailDal>(); var data = dal.Fetch(supplierId); Fetch(data); } OnFetchPost(args); } /// <summary> /// Loads a <see cref="SupplierInfoDetail"/> object from the given <see cref="SupplierInfoDetailDto"/>. /// </summary> /// <param name="data">The SupplierInfoDetailDto to use.</param> private void Fetch(SupplierInfoDetailDto data) { // Value properties LoadProperty(SupplierIdProperty, data.SupplierId); LoadProperty(NameProperty, data.Name); LoadProperty(AddressLine1Property, data.AddressLine1); LoadProperty(AddressLine2Property, data.AddressLine2); LoadProperty(ZipCodeProperty, data.ZipCode); LoadProperty(StateProperty, data.State); LoadProperty(CountryProperty, data.Country); var args = new DataPortalHookArgs(data); OnFetchRead(args); } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); #endregion } }
namespace ghostshockey.it.app.Droid { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Android.Graphics; using AdMaiora.AppKit.UI; using model.Poco; #pragma warning disable CS4014 public class MatchFragment : AdMaiora.AppKit.UI.App.Fragment { #region Inner Classes #endregion #region Constants and Fields private int _userId; private int _willDoIn; private Match _item; // This flag check if we are already calling the login REST service private bool _isRefereshingItem; // This cancellation token is used to cancel the rest send message request private CancellationTokenSource _cts0; #endregion #region Widgets [Widget] private RelativeLayout HomeLayout; [Widget] private RelativeLayout AwayLayout; [Widget] private RelativeLayout MatchLayout; [Widget] private View BlockLayout; [Widget] private TextView HomeLabel; [Widget] private TextView HomeScoreLabel; [Widget] private TextView AwayLabel; [Widget] private TextView AwayScoreLabel; [Widget] private TextView DateLabel; [Widget] private TextView CategoryLabel; [Widget] private TextView YearLabel; #endregion #region Constructors public MatchFragment() { } #endregion #region Properties #endregion #region Fragment Methods public override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); _willDoIn = 5; _userId = this.Arguments.GetInt("UserId"); _item = this.Arguments.GetObject<Match>("Item"); } public override void OnCreateView(LayoutInflater inflater, ViewGroup container) { base.OnCreateView(inflater, container); #region Desinger Stuff SetContentView(Resource.Layout.FragmentMatch, inflater, container); //SlideUpToShowKeyboard(); this.HasOptionsMenu = true; #endregion this.Title = "New Item"; //this.DescriptionLabel.Clickable = true; //this.DescriptionLabel.SetOnTouchListener(GestureListener.ForSingleTapUp(this.Activity, // (e) => // { // this.DismissKeyboard(); // var f = new TextInputFragment(); // f.ContentText = this.DescriptionText.Text; // f.TextInputDone += TextInputFragment_TextInputDone; // this.FragmentManager.BeginTransaction() // .AddToBackStack("BeforeTextInputFragment") // .Replace(Resource.Id.ContentLayout, f, "TextInputFragment") // .Commit(); // })); //this.DaysButton.Click += DaysButton_Click; if (_item != null) LoadItem(_item); this.BlockLayout.Visibility = _item == null ? ViewStates.Gone : ViewStates.Visible; } public override void OnCreateOptionsMenu(IMenu menu, MenuInflater inflater) { base.OnCreateOptionsMenu(menu, inflater); menu.Clear(); menu.Add(0, 1, 0, "Save").SetShowAsAction(ShowAsAction.Always); } public override bool OnOptionsItemSelected(IMenuItem item) { switch(item.ItemId) { case 1: var f = new MatchesFragment(); f.Arguments = new Bundle(); f.Arguments.PutObject("Item", _item.Tournament); this.FragmentManager.BeginTransaction() .AddToBackStack("BeforeTaskFragment") .Replace(Resource.Id.ContentLayout, f, "MatchesFragment") .Commit(); return true; default: return base.OnOptionsItemSelected(item); } } public override void OnDestroyView() { base.OnDestroyView(); if (_cts0 != null) _cts0.Cancel(); //this.DaysButton.Click -= DaysButton_Click; } #endregion #region Public Methods #endregion #region Methods private void LoadItem(Match match) { if (_isRefereshingItem) return; _isRefereshingItem = true; ((MainActivity)this.Activity).BlockUI(); _cts0 = new CancellationTokenSource(); AppController.GetMatch(match.MatchID, (item) => { this.HomeLabel.Text = item.HomeTeam.DisplayName; this.HomeScoreLabel.Text = item.HomeTeamScore.ToString(); this.AwayLabel.Text = item.AwayTeam.DisplayName; this.AwayScoreLabel.Text = item.AwayTeamScore.ToString(); this.DateLabel.Text = item.MatchDate.ToString(); this.CategoryLabel.Text = item.Tournament.Category.Name; this.YearLabel.Text = item.Tournament.Year.Name; }, (error) => { Toast.MakeText(this.Activity.ApplicationContext, error, ToastLength.Long).Show(); }, () => { _isRefereshingItem = false; ((MainActivity)this.Activity).UnblockUI(); }); //SetWillDoInDays(item.WillDoIn); //SetDescription(item.Description); } //private void SetDescription(string description) //{ // this.DescriptionLabel.Text = !String.IsNullOrWhiteSpace(description) ? String.Empty : "Write here some notes..."; // this.DescriptionText.Text = description; //} //private void SetWillDoInDays(int willDoIn) //{ // _willDoIn = willDoIn; // if (_willDoIn < 0) // _willDoIn = 5; // Color color = ViewBuilder.ColorFromARGB(AppController.Colors.Green); // if (_willDoIn < 2) // { // color = ViewBuilder.ColorFromARGB(AppController.Colors.Red); // } // else if (_willDoIn < 4) // { // color = ViewBuilder.ColorFromARGB(AppController.Colors.Orange); // } // this.DaysButton.Text = _willDoIn.ToString(); // this.DaysButton.SetTextColor(color); //} //private bool ValidateInput() //{ // var validator = new WidgetValidator() // .AddValidator(() => this.TitleText.Text, WidgetValidator.IsNotNullOrEmpty, "Please insert a title!") // .AddValidator(() => this.DescriptionText.Text, WidgetValidator.IsNotNullOrEmpty, "Please insert a description!") // .AddValidator(() => this.TagsText.Text, (string s) => String.IsNullOrWhiteSpace(s) || !s.Contains(" "), "Tags must be comma separated list, no blanks!"); // string errorMessage; // if (!validator.Validate(out errorMessage)) // { // Toast.MakeText(this.Activity.ApplicationContext, errorMessage, ToastLength.Long).Show(); // return false; // } // return true; //} //private void AddTodoItem() //{ // if (_isSendingTodoItem) // return; // if (!ValidateInput()) // return; // string title = this.TitleText.Text; // string description = this.DescriptionText.Text; // string tags = this.TagsText.Text; // _isSendingTodoItem = true; // ((MainActivity)this.Activity).BlockUI(); // _cts0 = new CancellationTokenSource(); // //AppController.AddTodoItem(_cts0, // // _userId, // // title, // // description, // // _willDoIn, // // tags, // // (todoItem) => // // { // // this.FragmentManager.PopBackStack(); // // }, // // (error) => // // { // // Toast.MakeText(this.Activity.ApplicationContext, error, ToastLength.Long).Show(); // // }, // // () => // // { // // _isSendingTodoItem = false; // // ((MainActivity)this.Activity).UnblockUI(); // // }); //} //private void UpdateTodoItem() //{ // if (_isSendingTodoItem) // return; // if (!ValidateInput()) // return; // string title = this.TitleText.Text; // string description = this.DescriptionText.Text; // string tags = this.TagsText.Text; // _isSendingTodoItem = true; // ((MainActivity)this.Activity).BlockUI(); // _cts0 = new CancellationTokenSource(); // //AppController.UpdateTodoItem(_cts0, // // _item.TodoItemId, // // title, // // description, // // _willDoIn, // // tags, // // (todoItem) => // // { // // this.FragmentManager.PopBackStack(); // // }, // // (error) => // // { // // Toast.MakeText(this.Activity.ApplicationContext, error, ToastLength.Long).Show(); // // }, // // () => // // { // // _isSendingTodoItem = false; // // ((MainActivity)this.Activity).UnblockUI(); // // }); //} #endregion #region Event Handlers //private void TextInputFragment_TextInputDone(object sender, TextInputDoneEventArgs e) //{ // SetDescription(e.Text); //} //private void DaysButton_Click(object sender, EventArgs e) //{ // SetWillDoInDays(_willDoIn - 1); //} #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////// // // // // Purpose: This class implements a set of methods for comparing // strings. // // //////////////////////////////////////////////////////////////////////////// using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Diagnostics.Contracts; namespace System.Globalization { [Flags] [System.Runtime.InteropServices.ComVisible(true)] public enum CompareOptions { None = 0x00000000, IgnoreCase = 0x00000001, IgnoreNonSpace = 0x00000002, IgnoreSymbols = 0x00000004, IgnoreKanaType = 0x00000008, // ignore kanatype IgnoreWidth = 0x00000010, // ignore width OrdinalIgnoreCase = 0x10000000, // This flag can not be used with other flags. StringSort = 0x20000000, // use string sort method Ordinal = 0x40000000, // This flag can not be used with other flags. } [System.Runtime.InteropServices.ComVisible(true)] public partial class CompareInfo { // Mask used to check if IndexOf()/LastIndexOf()/IsPrefix()/IsPostfix() has the right flags. private const CompareOptions ValidIndexMaskOffFlags = ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType); // Mask used to check if Compare() has the right flags. private const CompareOptions ValidCompareMaskOffFlags = ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort); // Mask used to check if GetHashCodeOfString() has the right flags. private const CompareOptions ValidHashCodeOfStringMaskOffFlags = ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType); // // CompareInfos have an interesting identity. They are attached to the locale that created them, // ie: en-US would have an en-US sort. For haw-US (custom), then we serialize it as haw-US. // The interesting part is that since haw-US doesn't have its own sort, it has to point at another // locale, which is what SCOMPAREINFO does. private readonly String _name; // The name used to construct this CompareInfo private readonly String _sortName; // The name that defines our behavior /*=================================GetCompareInfo========================== **Action: Get the CompareInfo for the specified culture. **Returns: The CompareInfo for the specified culture. **Arguments: ** name the name of the culture. **Exceptions: ** ArgumentException if name is invalid. ============================================================================*/ public static CompareInfo GetCompareInfo(String name) { if (name == null) { throw new ArgumentNullException("name"); } Contract.EndContractBlock(); return CultureInfo.GetCultureInfo(name).CompareInfo; } ///////////////////////////----- Name -----///////////////////////////////// // // Returns the name of the culture (well actually, of the sort). // Very important for providing a non-LCID way of identifying // what the sort is. // // Note that this name isn't dereferenced in case the CompareInfo is a different locale // which is consistent with the behaviors of earlier versions. (so if you ask for a sort // and the locale's changed behavior, then you'll get changed behavior, which is like // what happens for a version update) // //////////////////////////////////////////////////////////////////////// [System.Runtime.InteropServices.ComVisible(false)] public virtual String Name { get { Contract.Assert(_name != null, "CompareInfo.Name Expected m_name to be set"); if (_name == "zh-CHT" || _name == "zh-CHS") { return _name; } return _sortName; } } //////////////////////////////////////////////////////////////////////// // // Compare // // Compares the two strings with the given options. Returns 0 if the // two strings are equal, a number less than 0 if string1 is less // than string2, and a number greater than 0 if string1 is greater // than string2. // //////////////////////////////////////////////////////////////////////// public virtual int Compare(String string1, String string2) { return (Compare(string1, string2, CompareOptions.None)); } public unsafe virtual int Compare(String string1, String string2, CompareOptions options) { if (options == CompareOptions.OrdinalIgnoreCase) { return String.Compare(string1, string2, StringComparison.OrdinalIgnoreCase); } // Verify the options before we do any real comparison. if ((options & CompareOptions.Ordinal) != 0) { if (options != CompareOptions.Ordinal) { throw new ArgumentException(SR.Argument_CompareOptionOrdinal, "options"); } return String.CompareOrdinal(string1, string2); } if ((options & ValidCompareMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, "options"); } //Our paradigm is that null sorts less than any other string and //that two nulls sort as equal. if (string1 == null) { if (string2 == null) { return (0); // Equal } return (-1); // null < non-null } if (string2 == null) { return (1); // non-null > null } return CompareString(string1, 0, string1.Length, string2, 0, string2.Length, options); } //////////////////////////////////////////////////////////////////////// // // Compare // // Compares the specified regions of the two strings with the given // options. // Returns 0 if the two strings are equal, a number less than 0 if // string1 is less than string2, and a number greater than 0 if // string1 is greater than string2. // //////////////////////////////////////////////////////////////////////// public unsafe virtual int Compare(String string1, int offset1, int length1, String string2, int offset2, int length2) { return Compare(string1, offset1, length1, string2, offset2, length2, 0); } public unsafe virtual int Compare(String string1, int offset1, String string2, int offset2, CompareOptions options) { return Compare(string1, offset1, string1 == null ? 0 : string1.Length - offset1, string2, offset2, string2 == null ? 0 : string2.Length - offset2, options); } public unsafe virtual int Compare(String string1, int offset1, String string2, int offset2) { return Compare(string1, offset1, string2, offset2, 0); } public unsafe virtual int Compare(String string1, int offset1, int length1, String string2, int offset2, int length2, CompareOptions options) { if (options == CompareOptions.OrdinalIgnoreCase) { int result = String.Compare(string1, offset1, string2, offset2, length1 < length2 ? length1 : length2, StringComparison.OrdinalIgnoreCase); if ((length1 != length2) && result == 0) return (length1 > length2 ? 1 : -1); return (result); } // Verify inputs if (length1 < 0 || length2 < 0) { throw new ArgumentOutOfRangeException((length1 < 0) ? "length1" : "length2", SR.ArgumentOutOfRange_NeedPosNum); } if (offset1 < 0 || offset2 < 0) { throw new ArgumentOutOfRangeException((offset1 < 0) ? "offset1" : "offset2", SR.ArgumentOutOfRange_NeedPosNum); } if (offset1 > (string1 == null ? 0 : string1.Length) - length1) { throw new ArgumentOutOfRangeException("string1", SR.ArgumentOutOfRange_OffsetLength); } if (offset2 > (string2 == null ? 0 : string2.Length) - length2) { throw new ArgumentOutOfRangeException("string2", SR.ArgumentOutOfRange_OffsetLength); } if ((options & CompareOptions.Ordinal) != 0) { if (options != CompareOptions.Ordinal) { throw new ArgumentException(SR.Argument_CompareOptionOrdinal, "options"); } } else if ((options & ValidCompareMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, "options"); } // // Check for the null case. // if (string1 == null) { if (string2 == null) { return (0); } return (-1); } if (string2 == null) { return (1); } if (options == CompareOptions.Ordinal) { return CompareOrdinal(string1, offset1, length1, string2, offset2, length2); } return CompareString(string1, offset1, length1, string2, offset2, length2, options); } private static int CompareOrdinal(string string1, int offset1, int length1, string string2, int offset2, int length2) { int result = String.CompareOrdinal(string1, offset1, string2, offset2, (length1 < length2 ? length1 : length2)); if ((length1 != length2) && result == 0) { return (length1 > length2 ? 1 : -1); } return (result); } // // CompareOrdinalIgnoreCase compare two string oridnally with ignoring the case. // it assumes the strings are Ascii string till we hit non Ascii character in strA or strB and then we continue the comparison by // calling the OS. // internal static unsafe int CompareOrdinalIgnoreCase(string strA, int indexA, int lengthA, string strB, int indexB, int lengthB) { Contract.Assert(indexA + lengthA <= strA.Length); Contract.Assert(indexB + lengthB <= strB.Length); int length = Math.Min(lengthA, lengthB); int range = length; fixed (char* ap = strA) fixed (char* bp = strB) { char* a = ap + indexA; char* b = bp + indexB; while (length != 0 && (*a <= 0x80) && (*b <= 0x80)) { int charA = *a; int charB = *b; if (charA == charB) { a++; b++; length--; continue; } // uppercase both chars - notice that we need just one compare per char if ((uint)(charA - 'a') <= (uint)('z' - 'a')) charA -= 0x20; if ((uint)(charB - 'a') <= (uint)('z' - 'a')) charB -= 0x20; //Return the (case-insensitive) difference between them. if (charA != charB) return charA - charB; // Next char a++; b++; length--; } if (length == 0) return lengthA - lengthB; range -= length; return CompareStringOrdinalIgnoreCase(a, lengthA - range, b, lengthB - range); } } //////////////////////////////////////////////////////////////////////// // // IsPrefix // // Determines whether prefix is a prefix of string. If prefix equals // String.Empty, true is returned. // //////////////////////////////////////////////////////////////////////// public unsafe virtual bool IsPrefix(String source, String prefix, CompareOptions options) { if (source == null || prefix == null) { throw new ArgumentNullException((source == null ? "source" : "prefix"), SR.ArgumentNull_String); } Contract.EndContractBlock(); int prefixLen = prefix.Length; int sourceLength = source.Length; if (prefixLen == 0) { return (true); } if (sourceLength == 0) { return false; } if (options == CompareOptions.OrdinalIgnoreCase) { return source.StartsWith(prefix, StringComparison.OrdinalIgnoreCase); } if (options == CompareOptions.Ordinal) { return source.StartsWith(prefix, StringComparison.Ordinal); } if ((options & ValidIndexMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, "options"); } return StartsWith(source, prefix, options); } public virtual bool IsPrefix(String source, String prefix) { return (IsPrefix(source, prefix, 0)); } //////////////////////////////////////////////////////////////////////// // // IsSuffix // // Determines whether suffix is a suffix of string. If suffix equals // String.Empty, true is returned. // //////////////////////////////////////////////////////////////////////// public unsafe virtual bool IsSuffix(String source, String suffix, CompareOptions options) { if (source == null || suffix == null) { throw new ArgumentNullException((source == null ? "source" : "suffix"), SR.ArgumentNull_String); } Contract.EndContractBlock(); int suffixLen = suffix.Length; int sourceLength = source.Length; if (suffixLen == 0) { return (true); } if (sourceLength == 0) { return false; } if (options == CompareOptions.OrdinalIgnoreCase) { return source.EndsWith(suffix, StringComparison.OrdinalIgnoreCase); } if (options == CompareOptions.Ordinal) { return source.EndsWith(suffix, StringComparison.Ordinal); } if ((options & ValidIndexMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, "options"); } return EndsWith(source, suffix, options); } public virtual bool IsSuffix(String source, String suffix) { return (IsSuffix(source, suffix, 0)); } //////////////////////////////////////////////////////////////////////// // // IndexOf // // Returns the first index where value is found in string. The // search starts from startIndex and ends at endIndex. Returns -1 if // the specified value is not found. If value equals String.Empty, // startIndex is returned. Throws IndexOutOfRange if startIndex or // endIndex is less than zero or greater than the length of string. // Throws ArgumentException if value is null. // //////////////////////////////////////////////////////////////////////// public unsafe virtual int IndexOf(String source, char value) { if (source == null) throw new ArgumentNullException("source"); Contract.EndContractBlock(); return IndexOf(source, value, 0, source.Length, CompareOptions.None); } public unsafe virtual int IndexOf(String source, String value) { if (source == null) throw new ArgumentNullException("source"); Contract.EndContractBlock(); return IndexOf(source, value, 0, source.Length, CompareOptions.None); } public unsafe virtual int IndexOf(String source, char value, CompareOptions options) { if (source == null) throw new ArgumentNullException("source"); Contract.EndContractBlock(); return IndexOf(source, value, 0, source.Length, options); } public unsafe virtual int IndexOf(String source, String value, CompareOptions options) { if (source == null) throw new ArgumentNullException("source"); Contract.EndContractBlock(); return IndexOf(source, value, 0, source.Length, options); } public unsafe virtual int IndexOf(String source, char value, int startIndex, CompareOptions options) { if (source == null) throw new ArgumentNullException("source"); Contract.EndContractBlock(); return IndexOf(source, value, startIndex, source.Length - startIndex, options); } public unsafe virtual int IndexOf(String source, String value, int startIndex, CompareOptions options) { if (source == null) throw new ArgumentNullException("source"); Contract.EndContractBlock(); return IndexOf(source, value, startIndex, source.Length - startIndex, options); } public unsafe virtual int IndexOf(String source, char value, int startIndex, int count) { return IndexOf(source, value, startIndex, count, CompareOptions.None); } public unsafe virtual int IndexOf(String source, String value, int startIndex, int count) { return IndexOf(source, value, startIndex, count, CompareOptions.None); } public unsafe virtual int IndexOf(String source, char value, int startIndex, int count, CompareOptions options) { // Validate inputs if (source == null) throw new ArgumentNullException("source"); if (startIndex < 0 || startIndex > source.Length) throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); if (count < 0 || startIndex > source.Length - count) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); Contract.EndContractBlock(); if (options == CompareOptions.OrdinalIgnoreCase) { return source.IndexOf(value.ToString(), startIndex, count, StringComparison.OrdinalIgnoreCase); } // Validate CompareOptions // Ordinal can't be selected with other flags if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal)) throw new ArgumentException(SR.Argument_InvalidFlag, "options"); return IndexOfCore(source, new string(value, 1), startIndex, count, options); } public unsafe virtual int IndexOf(String source, String value, int startIndex, int count, CompareOptions options) { // Validate inputs if (source == null) throw new ArgumentNullException("source"); if (value == null) throw new ArgumentNullException("value"); if (startIndex > source.Length) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } Contract.EndContractBlock(); // In Everett we used to return -1 for empty string even if startIndex is negative number so we keeping same behavior here. // We return 0 if both source and value are empty strings for Everett compatibility too. if (source.Length == 0) { if (value.Length == 0) { return 0; } return -1; } if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (count < 0 || startIndex > source.Length - count) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); if (options == CompareOptions.OrdinalIgnoreCase) { return IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true); } // Validate CompareOptions // Ordinal can't be selected with other flags if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal)) throw new ArgumentException(SR.Argument_InvalidFlag, "options"); return IndexOfCore(source, value, startIndex, count, options); } //////////////////////////////////////////////////////////////////////// // // LastIndexOf // // Returns the last index where value is found in string. The // search starts from startIndex and ends at endIndex. Returns -1 if // the specified value is not found. If value equals String.Empty, // endIndex is returned. Throws IndexOutOfRange if startIndex or // endIndex is less than zero or greater than the length of string. // Throws ArgumentException if value is null. // //////////////////////////////////////////////////////////////////////// public unsafe virtual int LastIndexOf(String source, char value) { if (source == null) throw new ArgumentNullException("source"); Contract.EndContractBlock(); // Can't start at negative index, so make sure we check for the length == 0 case. return LastIndexOf(source, value, source.Length - 1, source.Length, CompareOptions.None); } public virtual int LastIndexOf(String source, String value) { if (source == null) throw new ArgumentNullException("source"); Contract.EndContractBlock(); // Can't start at negative index, so make sure we check for the length == 0 case. return LastIndexOf(source, value, source.Length - 1, source.Length, CompareOptions.None); } public virtual int LastIndexOf(String source, char value, CompareOptions options) { if (source == null) throw new ArgumentNullException("source"); Contract.EndContractBlock(); // Can't start at negative index, so make sure we check for the length == 0 case. return LastIndexOf(source, value, source.Length - 1, source.Length, options); } public unsafe virtual int LastIndexOf(String source, String value, CompareOptions options) { if (source == null) throw new ArgumentNullException("source"); Contract.EndContractBlock(); // Can't start at negative index, so make sure we check for the length == 0 case. return LastIndexOf(source, value, source.Length - 1, source.Length, options); } public unsafe virtual int LastIndexOf(String source, char value, int startIndex, CompareOptions options) { return LastIndexOf(source, value, startIndex, startIndex + 1, options); } public unsafe virtual int LastIndexOf(String source, String value, int startIndex, CompareOptions options) { return LastIndexOf(source, value, startIndex, startIndex + 1, options); } public unsafe virtual int LastIndexOf(String source, char value, int startIndex, int count) { return LastIndexOf(source, value, startIndex, count, CompareOptions.None); } public unsafe virtual int LastIndexOf(String source, String value, int startIndex, int count) { return LastIndexOf(source, value, startIndex, count, CompareOptions.None); } public unsafe virtual int LastIndexOf(String source, char value, int startIndex, int count, CompareOptions options) { // Verify Arguments if (source == null) throw new ArgumentNullException("source"); Contract.EndContractBlock(); // Validate CompareOptions // Ordinal can't be selected with other flags if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal) && (options != CompareOptions.OrdinalIgnoreCase)) throw new ArgumentException(SR.Argument_InvalidFlag, "options"); // Special case for 0 length input strings if (source.Length == 0 && (startIndex == -1 || startIndex == 0)) return -1; // Make sure we're not out of range if (startIndex < 0 || startIndex > source.Length) throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); // Make sure that we allow startIndex == source.Length if (startIndex == source.Length) { startIndex--; if (count > 0) count--; } // 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if (count < 0 || startIndex - count + 1 < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); if (options == CompareOptions.OrdinalIgnoreCase) { return source.LastIndexOf(value.ToString(), startIndex, count, StringComparison.OrdinalIgnoreCase); } return LastIndexOfCore(source, new string(value, 1), startIndex, count, options); } public unsafe virtual int LastIndexOf(String source, String value, int startIndex, int count, CompareOptions options) { // Verify Arguments if (source == null) throw new ArgumentNullException("source"); if (value == null) throw new ArgumentNullException("value"); Contract.EndContractBlock(); // Validate CompareOptions // Ordinal can't be selected with other flags if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal) && (options != CompareOptions.OrdinalIgnoreCase)) throw new ArgumentException(SR.Argument_InvalidFlag, "options"); // Special case for 0 length input strings if (source.Length == 0 && (startIndex == -1 || startIndex == 0)) return (value.Length == 0) ? 0 : -1; // Make sure we're not out of range if (startIndex < 0 || startIndex > source.Length) throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); // Make sure that we allow startIndex == source.Length if (startIndex == source.Length) { startIndex--; if (count > 0) count--; // If we are looking for nothing, just return 0 if (value.Length == 0 && count >= 0 && startIndex - count + 1 >= 0) return startIndex; } // 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if (count < 0 || startIndex - count + 1 < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); if (options == CompareOptions.OrdinalIgnoreCase) { return LastIndexOfOrdinal(source, value, startIndex, count, ignoreCase: true); } return LastIndexOfCore(source, value, startIndex, count, options); } //////////////////////////////////////////////////////////////////////// // // Equals // // Implements Object.Equals(). Returns a boolean indicating whether // or not object refers to the same CompareInfo as the current // instance. // //////////////////////////////////////////////////////////////////////// public override bool Equals(Object value) { CompareInfo that = value as CompareInfo; if (that != null) { return this.Name == that.Name; } return (false); } //////////////////////////////////////////////////////////////////////// // // GetHashCode // // Implements Object.GetHashCode(). Returns the hash code for the // CompareInfo. The hash code is guaranteed to be the same for // CompareInfo A and B where A.Equals(B) is true. // //////////////////////////////////////////////////////////////////////// public override int GetHashCode() { return (this.Name.GetHashCode()); } //////////////////////////////////////////////////////////////////////// // // GetHashCodeOfString // // This internal method allows a method that allows the equivalent of creating a Sortkey for a // string from CompareInfo, and generate a hashcode value from it. It is not very convenient // to use this method as is and it creates an unnecessary Sortkey object that will be GC'ed. // // The hash code is guaranteed to be the same for string A and B where A.Equals(B) is true and both // the CompareInfo and the CompareOptions are the same. If two different CompareInfo objects // treat the string the same way, this implementation will treat them differently (the same way that // Sortkey does at the moment). // // This method will never be made public itself, but public consumers of it could be created, e.g.: // // string.GetHashCode(CultureInfo) // string.GetHashCode(CompareInfo) // string.GetHashCode(CultureInfo, CompareOptions) // string.GetHashCode(CompareInfo, CompareOptions) // etc. // // (the methods above that take a CultureInfo would use CultureInfo.CompareInfo) // //////////////////////////////////////////////////////////////////////// internal int GetHashCodeOfString(string source, CompareOptions options) { // // Parameter validation // if (null == source) { throw new ArgumentNullException("source"); } if ((options & ValidHashCodeOfStringMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, "options"); } Contract.EndContractBlock(); return GetHashCodeOfStringCore(source, options); } public virtual int GetHashCode(string source, CompareOptions options) { if (source == null) { throw new ArgumentNullException("source"); } if (options == CompareOptions.Ordinal) { return source.GetHashCode(); } if (options == CompareOptions.OrdinalIgnoreCase) { return TextInfo.GetHashCodeOrdinalIgnoreCase(source); } // // GetHashCodeOfString does more parameters validation. basically will throw when // having Ordinal, OrdinalIgnoreCase and StringSort // return GetHashCodeOfString(source, options); } //////////////////////////////////////////////////////////////////////// // // ToString // // Implements Object.ToString(). Returns a string describing the // CompareInfo. // //////////////////////////////////////////////////////////////////////// public override String ToString() { return ("CompareInfo - " + this.Name); } } }
// 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. // Match is the result class for a regex search. // It returns the location, length, and substring for // the entire match as well as every captured group. // Match is also used during the search to keep track of each capture for each group. This is // done using the "_matches" array. _matches[x] represents an array of the captures for group x. // This array consists of start and length pairs, and may have empty entries at the end. _matchcount[x] // stores how many captures a group has. Note that _matchcount[x]*2 is the length of all the valid // values in _matches. _matchcount[x]*2-2 is the Start of the last capture, and _matchcount[x]*2-1 is the // Length of the last capture // // For example, if group 2 has one capture starting at position 4 with length 6, // _matchcount[2] == 1 // _matches[2][0] == 4 // _matches[2][1] == 6 // // Values in the _matches array can also be negative. This happens when using the balanced match // construct, "(?<start-end>...)". When the "end" group matches, a capture is added for both the "start" // and "end" groups. The capture added for "start" receives the negative values, and these values point to // the next capture to be balanced. They do NOT point to the capture that "end" just balanced out. The negative // values are indices into the _matches array transformed by the formula -3-x. This formula also untransforms. // using System.Collections; using System.Globalization; namespace System.Text.RegularExpressions { /// <summary> /// Represents the results from a single regular expression match. /// </summary> public class Match : Group { private const int ReplaceBufferSize = 256; internal GroupCollection _groupcoll; // input to the match internal Regex _regex; internal int _textbeg; internal int _textpos; internal int _textend; internal int _textstart; // output from the match internal int[][] _matches; internal int[] _matchcount; internal bool _balancing; // whether we've done any balancing with this match. If we // have done balancing, we'll need to do extra work in Tidy(). internal Match(Regex regex, int capcount, string text, int begpos, int len, int startpos) : base(text, new int[2], 0, "0") { _regex = regex; _matchcount = new int[capcount]; _matches = new int[capcount][]; _matches[0] = _caps; _textbeg = begpos; _textend = begpos + len; _textstart = startpos; _balancing = false; // No need for an exception here. This is only called internally, so we'll use an Assert instead System.Diagnostics.Debug.Assert(!(_textbeg < 0 || _textstart < _textbeg || _textend < _textstart || Text.Length < _textend), "The parameters are out of range."); } /// <summary> /// Returns an empty Match object. /// </summary> public static Match Empty { get; } = new Match(null, 1, string.Empty, 0, 0, 0); internal virtual void Reset(Regex regex, string text, int textbeg, int textend, int textstart) { _regex = regex; Text = text; _textbeg = textbeg; _textend = textend; _textstart = textstart; for (int i = 0; i < _matchcount.Length; i++) { _matchcount[i] = 0; } _balancing = false; } public virtual GroupCollection Groups { get { if (_groupcoll == null) _groupcoll = new GroupCollection(this, null); return _groupcoll; } } /// <summary> /// Returns a new Match with the results for the next match, starting /// at the position at which the last match ended (at the character beyond the last /// matched character). /// </summary> public Match NextMatch() { if (_regex == null) return this; return _regex.Run(false, Length, Text, _textbeg, _textend - _textbeg, _textpos); } /// <summary> /// Returns the expansion of the passed replacement pattern. For /// example, if the replacement pattern is ?$1$2?, Result returns the concatenation /// of Group(1).ToString() and Group(2).ToString(). /// </summary> public virtual string Result(string replacement) { if (replacement == null) throw new ArgumentNullException(nameof(replacement)); if (_regex == null) throw new NotSupportedException(SR.NoResultOnFailed); // Gets the weakly cached replacement helper or creates one if there isn't one already. RegexReplacement repl = RegexReplacement.GetOrCreate(_regex._replref, replacement, _regex.caps, _regex.capsize, _regex.capnames, _regex.roptions); Span<char> charInitSpan = stackalloc char[ReplaceBufferSize]; var vsb = new ValueStringBuilder(charInitSpan); repl.ReplacementImpl(ref vsb, this); return vsb.ToString(); } internal virtual ReadOnlySpan<char> GroupToStringImpl(int groupnum) { int c = _matchcount[groupnum]; if (c == 0) return string.Empty; int[] matches = _matches[groupnum]; return Text.AsSpan(matches[(c - 1) * 2], matches[(c * 2) - 1]); } internal ReadOnlySpan<char> LastGroupToStringImpl() { return GroupToStringImpl(_matchcount.Length - 1); } /// <summary> /// Returns a Match instance equivalent to the one supplied that is safe to share /// between multiple threads. /// </summary> public static Match Synchronized(Match inner) { if (inner == null) throw new ArgumentNullException(nameof(inner)); int numgroups = inner._matchcount.Length; // Populate all groups by looking at each one for (int i = 0; i < numgroups; i++) { Group group = inner.Groups[i]; // Depends on the fact that Group.Synchronized just // operates on and returns the same instance Group.Synchronized(group); } return inner; } /// <summary> /// Adds a capture to the group specified by "cap" /// </summary> internal virtual void AddMatch(int cap, int start, int len) { int capcount; if (_matches[cap] == null) _matches[cap] = new int[2]; capcount = _matchcount[cap]; if (capcount * 2 + 2 > _matches[cap].Length) { int[] oldmatches = _matches[cap]; int[] newmatches = new int[capcount * 8]; for (int j = 0; j < capcount * 2; j++) newmatches[j] = oldmatches[j]; _matches[cap] = newmatches; } _matches[cap][capcount * 2] = start; _matches[cap][capcount * 2 + 1] = len; _matchcount[cap] = capcount + 1; } /* * Nonpublic builder: Add a capture to balance the specified group. This is used by the balanced match construct. (?<foo-foo2>...) If there were no such thing as backtracking, this would be as simple as calling RemoveMatch(cap). However, since we have backtracking, we need to keep track of everything. */ internal virtual void BalanceMatch(int cap) { _balancing = true; // we'll look at the last capture first int capcount = _matchcount[cap]; int target = capcount * 2 - 2; // first see if it is negative, and therefore is a reference to the next available // capture group for balancing. If it is, we'll reset target to point to that capture. if (_matches[cap][target] < 0) target = -3 - _matches[cap][target]; // move back to the previous capture target -= 2; // if the previous capture is a reference, just copy that reference to the end. Otherwise, point to it. if (target >= 0 && _matches[cap][target] < 0) AddMatch(cap, _matches[cap][target], _matches[cap][target + 1]); else AddMatch(cap, -3 - target, -4 - target /* == -3 - (target + 1) */ ); } /// <summary> /// Removes a group match by capnum /// </summary> internal virtual void RemoveMatch(int cap) { _matchcount[cap]--; } /// <summary> /// Tells if a group was matched by capnum /// </summary> internal virtual bool IsMatched(int cap) { return cap < _matchcount.Length && _matchcount[cap] > 0 && _matches[cap][_matchcount[cap] * 2 - 1] != (-3 + 1); } /// <summary> /// Returns the index of the last specified matched group by capnum /// </summary> internal virtual int MatchIndex(int cap) { int i = _matches[cap][_matchcount[cap] * 2 - 2]; if (i >= 0) return i; return _matches[cap][-3 - i]; } /// <summary> /// Returns the length of the last specified matched group by capnum /// </summary> internal virtual int MatchLength(int cap) { int i = _matches[cap][_matchcount[cap] * 2 - 1]; if (i >= 0) return i; return _matches[cap][-3 - i]; } /// <summary> /// Tidy the match so that it can be used as an immutable result /// </summary> internal virtual void Tidy(int textpos) { int[] interval = _matches[0]; Index = interval[0]; Length = interval[1]; _textpos = textpos; _capcount = _matchcount[0]; if (_balancing) { // The idea here is that we want to compact all of our unbalanced captures. To do that we // use j basically as a count of how many unbalanced captures we have at any given time // (really j is an index, but j/2 is the count). First we skip past all of the real captures // until we find a balance captures. Then we check each subsequent entry. If it's a balance // capture (it's negative), we decrement j. If it's a real capture, we increment j and copy // it down to the last free position. for (int cap = 0; cap < _matchcount.Length; cap++) { int limit; int[] matcharray; limit = _matchcount[cap] * 2; matcharray = _matches[cap]; int i = 0; int j; for (i = 0; i < limit; i++) { if (matcharray[i] < 0) break; } for (j = i; i < limit; i++) { if (matcharray[i] < 0) { // skip negative values j--; } else { // but if we find something positive (an actual capture), copy it back to the last // unbalanced position. if (i != j) matcharray[j] = matcharray[i]; j++; } } _matchcount[cap] = j / 2; } _balancing = false; } } #if DEBUG internal bool Debug { get { if (_regex == null) return false; return _regex.Debug; } } internal virtual void Dump() { int i, j; for (i = 0; i < _matchcount.Length; i++) { System.Diagnostics.Debug.WriteLine("Capnum " + i.ToString(CultureInfo.InvariantCulture) + ":"); for (j = 0; j < _matchcount[i]; j++) { string text = ""; if (_matches[i][j * 2] >= 0) text = Text.Substring(_matches[i][j * 2], _matches[i][j * 2 + 1]); System.Diagnostics.Debug.WriteLine(" (" + _matches[i][j * 2].ToString(CultureInfo.InvariantCulture) + "," + _matches[i][j * 2 + 1].ToString(CultureInfo.InvariantCulture) + ") " + text); } } } #endif } /// <summary> /// MatchSparse is for handling the case where slots are sparsely arranged (e.g., if somebody says use slot 100000) /// </summary> internal class MatchSparse : Match { // the lookup hashtable internal new readonly Hashtable _caps; internal MatchSparse(Regex regex, Hashtable caps, int capcount, string text, int begpos, int len, int startpos) : base(regex, capcount, text, begpos, len, startpos) { _caps = caps; } public override GroupCollection Groups { get { if (_groupcoll == null) _groupcoll = new GroupCollection(this, _caps); return _groupcoll; } } #if DEBUG internal override void Dump() { if (_caps != null) { foreach (DictionaryEntry kvp in _caps) { System.Diagnostics.Debug.WriteLine("Slot " + kvp.Key.ToString() + " -> " + kvp.Value.ToString()); } } base.Dump(); } #endif } }
using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using NServiceKit.Common.Reflection; using NServiceKit.DesignPatterns.Model; using NServiceKit.Text; namespace NServiceKit.Common.Utils { /// <summary>An identifier utilities.</summary> /// <typeparam name="T">Generic type parameter.</typeparam> public static class IdUtils<T> { internal static Func<T, object> CanGetId; static IdUtils() { #if !SILVERLIGHT && !MONOTOUCH && !XBOX var hasIdInterfaces = typeof(T).FindInterfaces( (t, critera) => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IHasId<>), null); if (hasIdInterfaces.Length > 0) { CanGetId = HasId<T>.GetId; return; } #endif if (typeof(T).IsClass()) { if (typeof(T).GetPropertyInfo(IdUtils.IdField) != null && typeof(T).GetPropertyInfo(IdUtils.IdField).GetMethodInfo() != null) { CanGetId = HasPropertyId<T>.GetId; return; } foreach (var pi in typeof(T).GetPublicProperties() .Where(pi => pi.CustomAttributes() .Cast<Attribute>() .Any(attr => attr.GetType().Name == "PrimaryKeyAttribute"))) { CanGetId = StaticAccessors<T>.ValueUnTypedGetPropertyTypeFn(pi); return; } } CanGetId = x => x.GetHashCode(); } /// <summary>Gets an identifier.</summary> /// /// <param name="entity">The entity.</param> /// /// <returns>The identifier.</returns> public static object GetId(T entity) { return CanGetId(entity); } } internal static class HasPropertyId<TEntity> { private static readonly Func<TEntity, object> GetIdFn; static HasPropertyId() { var pi = typeof(TEntity).GetPropertyInfo(IdUtils.IdField); GetIdFn = StaticAccessors<TEntity>.ValueUnTypedGetPropertyTypeFn(pi); } /// <summary>Gets an identifier.</summary> /// /// <param name="entity">The entity.</param> /// /// <returns>The identifier.</returns> public static object GetId(TEntity entity) { return GetIdFn(entity); } } internal static class HasId<TEntity> { private static readonly Func<TEntity, object> GetIdFn; static HasId() { #if MONOTOUCH || SILVERLIGHT GetIdFn = HasPropertyId<TEntity>.GetId; #else var hasIdInterfaces = typeof(TEntity).FindInterfaces( (t, critera) => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IHasId<>), null); var genericArg = hasIdInterfaces[0].GetGenericArguments()[0]; var genericType = typeof(HasIdGetter<,>).MakeGenericType(typeof(TEntity), genericArg); var oInstanceParam = System.Linq.Expressions.Expression.Parameter(typeof(TEntity), "oInstanceParam"); var exprCallStaticMethod = System.Linq.Expressions.Expression.Call ( genericType, "GetId", new Type[0], oInstanceParam ); GetIdFn = System.Linq.Expressions.Expression.Lambda<Func<TEntity, object>> ( exprCallStaticMethod, oInstanceParam ).Compile(); #endif } /// <summary>Gets an identifier.</summary> /// /// <param name="entity">The entity.</param> /// /// <returns>The identifier.</returns> public static object GetId(TEntity entity) { return GetIdFn(entity); } } internal class HasIdGetter<TEntity, TId> where TEntity : IHasId<TId> { /// <summary>Gets an identifier.</summary> /// /// <param name="entity">The entity.</param> /// /// <returns>The identifier.</returns> public static object GetId(TEntity entity) { return entity.Id; } } /// <summary>An identifier utilities.</summary> public static class IdUtils { /// <summary>The identifier field.</summary> public const string IdField = "Id"; /// <summary>An object extension method that gets object identifier.</summary> /// /// <param name="entity">The entity to act on.</param> /// /// <returns>The object identifier.</returns> public static object GetObjectId(this object entity) { return entity.GetType().GetPropertyInfo(IdField).GetMethodInfo().Invoke(entity, new object[0]); } /// <summary>A T extension method that gets an identifier.</summary> /// /// <typeparam name="T">Generic type parameter.</typeparam> /// <param name="entity">The entity to act on.</param> /// /// <returns>The identifier.</returns> public static object GetId<T>(this T entity) { return IdUtils<T>.GetId(entity); } /// <summary>A T extension method that creates an URN.</summary> /// /// <typeparam name="T">Generic type parameter.</typeparam> /// <param name="id">The identifier.</param> /// /// <returns>The new URN.</returns> public static string CreateUrn<T>(object id) { return string.Format("urn:{0}:{1}", typeof(T).Name.ToLowerInvariant(), id); } /// <summary>Creates an URN.</summary> /// /// <param name="type">The type.</param> /// <param name="id"> The identifier.</param> /// /// <returns>The new URN.</returns> public static string CreateUrn(Type type, object id) { return string.Format("urn:{0}:{1}", type.Name.ToLowerInvariant(), id); } /// <summary>A T extension method that creates an URN.</summary> /// /// <typeparam name="T">Generic type parameter.</typeparam> /// <param name="entity">The entity to act on.</param> /// /// <returns>The new URN.</returns> public static string CreateUrn<T>(this T entity) { var id = GetId(entity); return string.Format("urn:{0}:{1}", typeof(T).Name.ToLowerInvariant(), id); } /// <summary>Creates cache key path.</summary> /// /// <typeparam name="T">Generic type parameter.</typeparam> /// <param name="idValue">The identifier value.</param> /// /// <returns>The new cache key path.</returns> public static string CreateCacheKeyPath<T>(string idValue) { if (idValue.Length < 4) { idValue = idValue.PadLeft(4, '0'); } idValue = idValue.Replace(" ", "-"); var rootDir = typeof(T).Name; var dir1 = idValue.Substring(0, 2); var dir2 = idValue.Substring(2, 2); var path = string.Format("{1}{0}{2}{0}{3}{0}{4}", Text.StringExtensions.DirSeparatorChar, rootDir, dir1, dir2, idValue); return path; } } }
#region Copyright notice and license // Copyright 2015-2016 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using CommandLine; using CommandLine.Text; using Google.Apis.Auth.OAuth2; using Google.Protobuf; using Grpc.Auth; using Grpc.Core; using Grpc.Core.Logging; using Grpc.Core.Utils; using Grpc.Testing; using Newtonsoft.Json.Linq; using NUnit.Framework; namespace Grpc.IntegrationTesting { public class InteropClient { private class ClientOptions { [Option("server_host", Default = "localhost")] public string ServerHost { get; set; } [Option("server_host_override")] public string ServerHostOverride { get; set; } [Option("server_port", Required = true)] public int ServerPort { get; set; } [Option("test_case", Default = "large_unary")] public string TestCase { get; set; } // Deliberately using nullable bool type to allow --use_tls=true syntax (as opposed to --use_tls) [Option("use_tls", Default = false)] public bool? UseTls { get; set; } // Deliberately using nullable bool type to allow --use_test_ca=true syntax (as opposed to --use_test_ca) [Option("use_test_ca", Default = false)] public bool? UseTestCa { get; set; } [Option("default_service_account", Required = false)] public string DefaultServiceAccount { get; set; } [Option("oauth_scope", Required = false)] public string OAuthScope { get; set; } [Option("service_account_key_file", Required = false)] public string ServiceAccountKeyFile { get; set; } } ClientOptions options; private InteropClient(ClientOptions options) { this.options = options; } public static void Run(string[] args) { GrpcEnvironment.SetLogger(new ConsoleLogger()); var parserResult = Parser.Default.ParseArguments<ClientOptions>(args) .WithNotParsed(errors => Environment.Exit(1)) .WithParsed(options => { var interopClient = new InteropClient(options); interopClient.Run().Wait(); }); } private async Task Run() { var credentials = await CreateCredentialsAsync(); List<ChannelOption> channelOptions = null; if (!string.IsNullOrEmpty(options.ServerHostOverride)) { channelOptions = new List<ChannelOption> { new ChannelOption(ChannelOptions.SslTargetNameOverride, options.ServerHostOverride) }; } var channel = new Channel(options.ServerHost, options.ServerPort, credentials, channelOptions); await RunTestCaseAsync(channel, options); await channel.ShutdownAsync(); } private async Task<ChannelCredentials> CreateCredentialsAsync() { var credentials = ChannelCredentials.Insecure; if (options.UseTls.Value) { credentials = options.UseTestCa.Value ? TestCredentials.CreateSslCredentials() : new SslCredentials(); } if (options.TestCase == "jwt_token_creds") { var googleCredential = await GoogleCredential.GetApplicationDefaultAsync(); Assert.IsTrue(googleCredential.IsCreateScopedRequired); credentials = ChannelCredentials.Create(credentials, googleCredential.ToCallCredentials()); } if (options.TestCase == "compute_engine_creds") { var googleCredential = await GoogleCredential.GetApplicationDefaultAsync(); Assert.IsFalse(googleCredential.IsCreateScopedRequired); credentials = ChannelCredentials.Create(credentials, googleCredential.ToCallCredentials()); } return credentials; } private async Task RunTestCaseAsync(Channel channel, ClientOptions options) { var client = new TestService.TestServiceClient(channel); switch (options.TestCase) { case "empty_unary": RunEmptyUnary(client); break; case "large_unary": RunLargeUnary(client); break; case "client_streaming": await RunClientStreamingAsync(client); break; case "server_streaming": await RunServerStreamingAsync(client); break; case "ping_pong": await RunPingPongAsync(client); break; case "empty_stream": await RunEmptyStreamAsync(client); break; case "compute_engine_creds": RunComputeEngineCreds(client, options.DefaultServiceAccount, options.OAuthScope); break; case "jwt_token_creds": RunJwtTokenCreds(client); break; case "oauth2_auth_token": await RunOAuth2AuthTokenAsync(client, options.OAuthScope); break; case "per_rpc_creds": await RunPerRpcCredsAsync(client, options.OAuthScope); break; case "cancel_after_begin": await RunCancelAfterBeginAsync(client); break; case "cancel_after_first_response": await RunCancelAfterFirstResponseAsync(client); break; case "timeout_on_sleeping_server": await RunTimeoutOnSleepingServerAsync(client); break; case "custom_metadata": await RunCustomMetadataAsync(client); break; case "status_code_and_message": await RunStatusCodeAndMessageAsync(client); break; case "unimplemented_service": RunUnimplementedService(new UnimplementedService.UnimplementedServiceClient(channel)); break; case "unimplemented_method": RunUnimplementedMethod(client); break; case "client_compressed_unary": RunClientCompressedUnary(client); break; case "client_compressed_streaming": await RunClientCompressedStreamingAsync(client); break; default: throw new ArgumentException("Unknown test case " + options.TestCase); } } public static void RunEmptyUnary(TestService.TestServiceClient client) { Console.WriteLine("running empty_unary"); var response = client.EmptyCall(new Empty()); Assert.IsNotNull(response); Console.WriteLine("Passed!"); } public static void RunLargeUnary(TestService.TestServiceClient client) { Console.WriteLine("running large_unary"); var request = new SimpleRequest { ResponseSize = 314159, Payload = CreateZerosPayload(271828) }; var response = client.UnaryCall(request); Assert.AreEqual(314159, response.Payload.Body.Length); Console.WriteLine("Passed!"); } public static async Task RunClientStreamingAsync(TestService.TestServiceClient client) { Console.WriteLine("running client_streaming"); var bodySizes = new List<int> { 27182, 8, 1828, 45904 }.Select((size) => new StreamingInputCallRequest { Payload = CreateZerosPayload(size) }); using (var call = client.StreamingInputCall()) { await call.RequestStream.WriteAllAsync(bodySizes); var response = await call.ResponseAsync; Assert.AreEqual(74922, response.AggregatedPayloadSize); } Console.WriteLine("Passed!"); } public static async Task RunServerStreamingAsync(TestService.TestServiceClient client) { Console.WriteLine("running server_streaming"); var bodySizes = new List<int> { 31415, 9, 2653, 58979 }; var request = new StreamingOutputCallRequest { ResponseParameters = { bodySizes.Select((size) => new ResponseParameters { Size = size }) } }; using (var call = client.StreamingOutputCall(request)) { var responseList = await call.ResponseStream.ToListAsync(); CollectionAssert.AreEqual(bodySizes, responseList.Select((item) => item.Payload.Body.Length)); } Console.WriteLine("Passed!"); } public static async Task RunPingPongAsync(TestService.TestServiceClient client) { Console.WriteLine("running ping_pong"); using (var call = client.FullDuplexCall()) { await call.RequestStream.WriteAsync(new StreamingOutputCallRequest { ResponseParameters = { new ResponseParameters { Size = 31415 } }, Payload = CreateZerosPayload(27182) }); Assert.IsTrue(await call.ResponseStream.MoveNext()); Assert.AreEqual(31415, call.ResponseStream.Current.Payload.Body.Length); await call.RequestStream.WriteAsync(new StreamingOutputCallRequest { ResponseParameters = { new ResponseParameters { Size = 9 } }, Payload = CreateZerosPayload(8) }); Assert.IsTrue(await call.ResponseStream.MoveNext()); Assert.AreEqual(9, call.ResponseStream.Current.Payload.Body.Length); await call.RequestStream.WriteAsync(new StreamingOutputCallRequest { ResponseParameters = { new ResponseParameters { Size = 2653 } }, Payload = CreateZerosPayload(1828) }); Assert.IsTrue(await call.ResponseStream.MoveNext()); Assert.AreEqual(2653, call.ResponseStream.Current.Payload.Body.Length); await call.RequestStream.WriteAsync(new StreamingOutputCallRequest { ResponseParameters = { new ResponseParameters { Size = 58979 } }, Payload = CreateZerosPayload(45904) }); Assert.IsTrue(await call.ResponseStream.MoveNext()); Assert.AreEqual(58979, call.ResponseStream.Current.Payload.Body.Length); await call.RequestStream.CompleteAsync(); Assert.IsFalse(await call.ResponseStream.MoveNext()); } Console.WriteLine("Passed!"); } public static async Task RunEmptyStreamAsync(TestService.TestServiceClient client) { Console.WriteLine("running empty_stream"); using (var call = client.FullDuplexCall()) { await call.RequestStream.CompleteAsync(); var responseList = await call.ResponseStream.ToListAsync(); Assert.AreEqual(0, responseList.Count); } Console.WriteLine("Passed!"); } public static void RunComputeEngineCreds(TestService.TestServiceClient client, string defaultServiceAccount, string oauthScope) { Console.WriteLine("running compute_engine_creds"); var request = new SimpleRequest { ResponseSize = 314159, Payload = CreateZerosPayload(271828), FillUsername = true, FillOauthScope = true }; // not setting credentials here because they were set on channel already var response = client.UnaryCall(request); Assert.AreEqual(314159, response.Payload.Body.Length); Assert.False(string.IsNullOrEmpty(response.OauthScope)); Assert.True(oauthScope.Contains(response.OauthScope)); Assert.AreEqual(defaultServiceAccount, response.Username); Console.WriteLine("Passed!"); } public static void RunJwtTokenCreds(TestService.TestServiceClient client) { Console.WriteLine("running jwt_token_creds"); var request = new SimpleRequest { ResponseSize = 314159, Payload = CreateZerosPayload(271828), FillUsername = true, }; // not setting credentials here because they were set on channel already var response = client.UnaryCall(request); Assert.AreEqual(314159, response.Payload.Body.Length); Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username); Console.WriteLine("Passed!"); } public static async Task RunOAuth2AuthTokenAsync(TestService.TestServiceClient client, string oauthScope) { Console.WriteLine("running oauth2_auth_token"); ITokenAccess credential = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { oauthScope }); string oauth2Token = await credential.GetAccessTokenForRequestAsync(); var credentials = GoogleGrpcCredentials.FromAccessToken(oauth2Token); var request = new SimpleRequest { FillUsername = true, FillOauthScope = true }; var response = client.UnaryCall(request, new CallOptions(credentials: credentials)); Assert.False(string.IsNullOrEmpty(response.OauthScope)); Assert.True(oauthScope.Contains(response.OauthScope)); Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username); Console.WriteLine("Passed!"); } public static async Task RunPerRpcCredsAsync(TestService.TestServiceClient client, string oauthScope) { Console.WriteLine("running per_rpc_creds"); ITokenAccess googleCredential = await GoogleCredential.GetApplicationDefaultAsync(); var credentials = googleCredential.ToCallCredentials(); var request = new SimpleRequest { FillUsername = true, }; var response = client.UnaryCall(request, new CallOptions(credentials: credentials)); Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username); Console.WriteLine("Passed!"); } public static async Task RunCancelAfterBeginAsync(TestService.TestServiceClient client) { Console.WriteLine("running cancel_after_begin"); var cts = new CancellationTokenSource(); using (var call = client.StreamingInputCall(cancellationToken: cts.Token)) { // TODO(jtattermusch): we need this to ensure call has been initiated once we cancel it. await Task.Delay(1000); cts.Cancel(); var ex = Assert.ThrowsAsync<RpcException>(async () => await call.ResponseAsync); Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode); } Console.WriteLine("Passed!"); } public static async Task RunCancelAfterFirstResponseAsync(TestService.TestServiceClient client) { Console.WriteLine("running cancel_after_first_response"); var cts = new CancellationTokenSource(); using (var call = client.FullDuplexCall(cancellationToken: cts.Token)) { await call.RequestStream.WriteAsync(new StreamingOutputCallRequest { ResponseParameters = { new ResponseParameters { Size = 31415 } }, Payload = CreateZerosPayload(27182) }); Assert.IsTrue(await call.ResponseStream.MoveNext()); Assert.AreEqual(31415, call.ResponseStream.Current.Payload.Body.Length); cts.Cancel(); try { // cannot use Assert.ThrowsAsync because it uses Task.Wait and would deadlock. await call.ResponseStream.MoveNext(); Assert.Fail(); } catch (RpcException ex) { Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode); } } Console.WriteLine("Passed!"); } public static async Task RunTimeoutOnSleepingServerAsync(TestService.TestServiceClient client) { Console.WriteLine("running timeout_on_sleeping_server"); var deadline = DateTime.UtcNow.AddMilliseconds(1); using (var call = client.FullDuplexCall(deadline: deadline)) { try { await call.RequestStream.WriteAsync(new StreamingOutputCallRequest { Payload = CreateZerosPayload(27182) }); } catch (InvalidOperationException) { // Deadline was reached before write has started. Eat the exception and continue. } catch (RpcException) { // Deadline was reached before write has started. Eat the exception and continue. } try { await call.ResponseStream.MoveNext(); Assert.Fail(); } catch (RpcException ex) { // We can't guarantee the status code always DeadlineExceeded. See issue #2685. Assert.Contains(ex.Status.StatusCode, new[] { StatusCode.DeadlineExceeded, StatusCode.Internal }); } } Console.WriteLine("Passed!"); } public static async Task RunCustomMetadataAsync(TestService.TestServiceClient client) { Console.WriteLine("running custom_metadata"); { // step 1: test unary call var request = new SimpleRequest { ResponseSize = 314159, Payload = CreateZerosPayload(271828) }; var call = client.UnaryCallAsync(request, headers: CreateTestMetadata()); await call.ResponseAsync; var responseHeaders = await call.ResponseHeadersAsync; var responseTrailers = call.GetTrailers(); Assert.AreEqual("test_initial_metadata_value", responseHeaders.First((entry) => entry.Key == "x-grpc-test-echo-initial").Value); CollectionAssert.AreEqual(new byte[] { 0xab, 0xab, 0xab }, responseTrailers.First((entry) => entry.Key == "x-grpc-test-echo-trailing-bin").ValueBytes); } { // step 2: test full duplex call var request = new StreamingOutputCallRequest { ResponseParameters = { new ResponseParameters { Size = 31415 } }, Payload = CreateZerosPayload(27182) }; var call = client.FullDuplexCall(headers: CreateTestMetadata()); await call.RequestStream.WriteAsync(request); await call.RequestStream.CompleteAsync(); await call.ResponseStream.ToListAsync(); var responseHeaders = await call.ResponseHeadersAsync; var responseTrailers = call.GetTrailers(); Assert.AreEqual("test_initial_metadata_value", responseHeaders.First((entry) => entry.Key == "x-grpc-test-echo-initial").Value); CollectionAssert.AreEqual(new byte[] { 0xab, 0xab, 0xab }, responseTrailers.First((entry) => entry.Key == "x-grpc-test-echo-trailing-bin").ValueBytes); } Console.WriteLine("Passed!"); } public static async Task RunStatusCodeAndMessageAsync(TestService.TestServiceClient client) { Console.WriteLine("running status_code_and_message"); var echoStatus = new EchoStatus { Code = 2, Message = "test status message" }; { // step 1: test unary call var request = new SimpleRequest { ResponseStatus = echoStatus }; var e = Assert.Throws<RpcException>(() => client.UnaryCall(request)); Assert.AreEqual(StatusCode.Unknown, e.Status.StatusCode); Assert.AreEqual(echoStatus.Message, e.Status.Detail); } { // step 2: test full duplex call var request = new StreamingOutputCallRequest { ResponseStatus = echoStatus }; var call = client.FullDuplexCall(); await call.RequestStream.WriteAsync(request); await call.RequestStream.CompleteAsync(); try { // cannot use Assert.ThrowsAsync because it uses Task.Wait and would deadlock. await call.ResponseStream.ToListAsync(); Assert.Fail(); } catch (RpcException e) { Assert.AreEqual(StatusCode.Unknown, e.Status.StatusCode); Assert.AreEqual(echoStatus.Message, e.Status.Detail); } } Console.WriteLine("Passed!"); } public static void RunUnimplementedService(UnimplementedService.UnimplementedServiceClient client) { Console.WriteLine("running unimplemented_service"); var e = Assert.Throws<RpcException>(() => client.UnimplementedCall(new Empty())); Assert.AreEqual(StatusCode.Unimplemented, e.Status.StatusCode); Console.WriteLine("Passed!"); } public static void RunUnimplementedMethod(TestService.TestServiceClient client) { Console.WriteLine("running unimplemented_method"); var e = Assert.Throws<RpcException>(() => client.UnimplementedCall(new Empty())); Assert.AreEqual(StatusCode.Unimplemented, e.Status.StatusCode); Console.WriteLine("Passed!"); } public static void RunClientCompressedUnary(TestService.TestServiceClient client) { Console.WriteLine("running client_compressed_unary"); var probeRequest = new SimpleRequest { ExpectCompressed = new BoolValue { Value = true // lie about compression }, ResponseSize = 314159, Payload = CreateZerosPayload(271828) }; var e = Assert.Throws<RpcException>(() => client.UnaryCall(probeRequest, CreateClientCompressionMetadata(false))); Assert.AreEqual(StatusCode.InvalidArgument, e.Status.StatusCode); var compressedRequest = new SimpleRequest { ExpectCompressed = new BoolValue { Value = true }, ResponseSize = 314159, Payload = CreateZerosPayload(271828) }; var response1 = client.UnaryCall(compressedRequest, CreateClientCompressionMetadata(true)); Assert.AreEqual(314159, response1.Payload.Body.Length); var uncompressedRequest = new SimpleRequest { ExpectCompressed = new BoolValue { Value = false }, ResponseSize = 314159, Payload = CreateZerosPayload(271828) }; var response2 = client.UnaryCall(uncompressedRequest, CreateClientCompressionMetadata(false)); Assert.AreEqual(314159, response2.Payload.Body.Length); Console.WriteLine("Passed!"); } public static async Task RunClientCompressedStreamingAsync(TestService.TestServiceClient client) { Console.WriteLine("running client_compressed_streaming"); try { var probeCall = client.StreamingInputCall(CreateClientCompressionMetadata(false)); await probeCall.RequestStream.WriteAsync(new StreamingInputCallRequest { ExpectCompressed = new BoolValue { Value = true }, Payload = CreateZerosPayload(27182) }); // cannot use Assert.ThrowsAsync because it uses Task.Wait and would deadlock. await probeCall; Assert.Fail(); } catch (RpcException e) { Assert.AreEqual(StatusCode.InvalidArgument, e.Status.StatusCode); } var call = client.StreamingInputCall(CreateClientCompressionMetadata(true)); await call.RequestStream.WriteAsync(new StreamingInputCallRequest { ExpectCompressed = new BoolValue { Value = true }, Payload = CreateZerosPayload(27182) }); call.RequestStream.WriteOptions = new WriteOptions(WriteFlags.NoCompress); await call.RequestStream.WriteAsync(new StreamingInputCallRequest { ExpectCompressed = new BoolValue { Value = false }, Payload = CreateZerosPayload(45904) }); await call.RequestStream.CompleteAsync(); var response = await call.ResponseAsync; Assert.AreEqual(73086, response.AggregatedPayloadSize); Console.WriteLine("Passed!"); } private static Payload CreateZerosPayload(int size) { return new Payload { Body = ByteString.CopyFrom(new byte[size]) }; } private static Metadata CreateClientCompressionMetadata(bool compressed) { var algorithmName = compressed ? "gzip" : "identity"; return new Metadata { { new Metadata.Entry(Metadata.CompressionRequestAlgorithmMetadataKey, algorithmName) } }; } // extracts the client_email field from service account file used for auth test cases private static string GetEmailFromServiceAccountFile() { string keyFile = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS"); Assert.IsNotNull(keyFile); var jobject = JObject.Parse(File.ReadAllText(keyFile)); string email = jobject.GetValue("client_email").Value<string>(); Assert.IsTrue(email.Length > 0); // spec requires nonempty client email. return email; } private static Metadata CreateTestMetadata() { return new Metadata { {"x-grpc-test-echo-initial", "test_initial_metadata_value"}, {"x-grpc-test-echo-trailing-bin", new byte[] {0xab, 0xab, 0xab}} }; } } }
// Copyright (c) 2010-2014 SharpDX - 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.Diagnostics; using System.Reflection; using System.Text; using SharpDX.Collections; namespace SharpDX.Diagnostics { /// <summary> /// Event args for <see cref="ComObject"/> used by <see cref="ObjectTracker"/>. /// </summary> public class ComObjectEventArgs : EventArgs { /// <summary> /// The object being tracked/untracked. /// </summary> public ComObject Object; /// <summary> /// Initializes a new instance of the <see cref="ComObjectEventArgs"/> class. /// </summary> /// <param name="o">The o.</param> public ComObjectEventArgs(ComObject o) { Object = o; } } /// <summary> /// Track all allocated objects. /// </summary> public static class ObjectTracker { private static Dictionary<IntPtr, List<ObjectReference>> processGlobalObjectReferences; [ThreadStatic] private static Dictionary<IntPtr, List<ObjectReference>> threadStaticObjectReferences; /// <summary> /// Occurs when a ComObject is tracked. /// </summary> public static event EventHandler<ComObjectEventArgs> Tracked; /// <summary> /// Occurs when a ComObject is untracked. /// </summary> public static event EventHandler<ComObjectEventArgs> UnTracked; private static Dictionary<IntPtr, List<ObjectReference>> ObjectReferences { get { Dictionary<IntPtr, List<ObjectReference>> objectReferences; if (Configuration.UseThreadStaticObjectTracking) { if (threadStaticObjectReferences == null) threadStaticObjectReferences = new Dictionary<IntPtr, List<ObjectReference>>(EqualityComparer.DefaultIntPtr); objectReferences = threadStaticObjectReferences; } else { if (processGlobalObjectReferences == null) processGlobalObjectReferences = new Dictionary<IntPtr, List<ObjectReference>>(EqualityComparer.DefaultIntPtr); objectReferences = processGlobalObjectReferences; } return objectReferences; } } /// <summary> /// Tracks the specified COM object. /// </summary> /// <param name="comObject">The COM object.</param> public static void Track(ComObject comObject) { if (comObject == null || comObject.NativePointer == IntPtr.Zero) return; lock (ObjectReferences) { List<ObjectReference> referenceList; // Object is already tracked if (!ObjectReferences.TryGetValue(comObject.NativePointer, out referenceList)) { referenceList = new List<ObjectReference>(); ObjectReferences.Add(comObject.NativePointer, referenceList); } #if STORE_APP var stacktrace = "Stacktrace is not available on this platform"; // This code is a workaround to be able to get a full stacktrace on Windows Store App. // This is an unsafe code, that should not run on production. Only at dev time! // Make sure we are on a 32bit process if(IntPtr.Size == 4) { // Get an access to a restricted method try { var stackTraceGetMethod = typeof(Environment).GetRuntimeProperty("StackTrace").GetMethod; try { // First try to get the stacktrace stacktrace = (string)stackTraceGetMethod.Invoke(null, null); } catch(Exception ex) { // If we have an exception, it means that the access to the method is not possible // so we are going to patch the field RuntimeMethodInfo.m_invocationFlags that should contain // 0x41 (initialized + security), and replace it by 0x1 (initialized) // and then callback again the method unsafe { // unsafe code, the RuntimeMethodInfo could be relocated (is it a real managed GC object?), // but we don't have much choice var addr = *(int**)Interop.Fixed(ref stackTraceGetMethod); // offset to RuntimeMethodInfo.m_invocationFlags addr += 13; // Check if we have the expecting value if(*addr == 0x41) { // if yes, change it to 0x1 *addr = 0x1; try { // And try to callit again a second time // if it succeeds, first Invoke() should run on next call stacktrace = (string)stackTraceGetMethod.Invoke(null, null); } catch(Exception ex2) { // if it is still failing, we can't do anything } } } } } catch(Exception ex) { // can't do anything } } referenceList.Add(new ObjectReference(DateTime.Now, comObject, stacktrace)); #else try { throw new Exception(); } catch(Exception ex) { referenceList.Add(new ObjectReference(DateTime.Now, comObject, ex.StackTrace)); } #endif // Fire Tracked event. OnTracked(comObject); } } /// <summary> /// Finds a list of object reference from a specified COM object pointer. /// </summary> /// <param name="comObjectPtr">The COM object pointer.</param> /// <returns>A list of object reference</returns> public static List<ObjectReference> Find(IntPtr comObjectPtr) { lock (ObjectReferences) { List<ObjectReference> referenceList; // Object is already tracked if (ObjectReferences.TryGetValue(comObjectPtr, out referenceList)) return new List<ObjectReference>(referenceList); } return new List<ObjectReference>(); } /// <summary> /// Finds the object reference for a specific COM object. /// </summary> /// <param name="comObject">The COM object.</param> /// <returns>An object reference</returns> public static ObjectReference Find(ComObject comObject) { lock (ObjectReferences) { List<ObjectReference> referenceList; // Object is already tracked if (ObjectReferences.TryGetValue(comObject.NativePointer, out referenceList)) { foreach (var objectReference in referenceList) { if (ReferenceEquals(objectReference.Object.Target, comObject)) return objectReference; } } } return null; } /// <summary> /// Untracks the specified COM object. /// </summary> /// <param name="comObject">The COM object.</param> public static void UnTrack(ComObject comObject) { if (comObject == null || comObject.NativePointer == IntPtr.Zero) return; lock (ObjectReferences) { List<ObjectReference> referenceList; // Object is already tracked if (ObjectReferences.TryGetValue(comObject.NativePointer, out referenceList)) { for (int i = referenceList.Count-1; i >=0; i--) { var objectReference = referenceList[i]; if (ReferenceEquals(objectReference.Object.Target, comObject)) referenceList.RemoveAt(i); else if (!objectReference.IsAlive) referenceList.RemoveAt(i); } // Remove empty list if (referenceList.Count == 0) ObjectReferences.Remove(comObject.NativePointer); // Fire UnTracked event OnUnTracked(comObject); } } } /// <summary> /// Reports all COM object that are active and not yet disposed. /// </summary> public static List<ObjectReference> FindActiveObjects() { var activeObjects = new List<ObjectReference>(); lock (ObjectReferences) { foreach (var referenceList in ObjectReferences.Values) { foreach (var objectReference in referenceList) { if (objectReference.IsAlive) activeObjects.Add(objectReference); } } } return activeObjects; } /// <summary> /// Reports all COM object that are active and not yet disposed. /// </summary> public static string ReportActiveObjects() { var text = new StringBuilder(); int count = 0; var countPerType = new Dictionary<string, int>(); foreach (var findActiveObject in FindActiveObjects()) { var findActiveObjectStr = findActiveObject.ToString(); if (!string.IsNullOrEmpty(findActiveObjectStr)) { text.AppendFormat("[{0}]: {1}", count, findActiveObjectStr); var target = findActiveObject.Object.Target; if (target != null) { int typeCount; var targetType = target.GetType().Name; if (!countPerType.TryGetValue(targetType, out typeCount)) { countPerType[targetType] = 0; } countPerType[targetType] = typeCount + 1; } } count++; } var keys = new List<string>(countPerType.Keys); keys.Sort(); text.AppendLine(); text.AppendLine("Count per Type:"); foreach (var key in keys) { text.AppendFormat("{0} : {1}", key, countPerType[key]); text.AppendLine(); } return text.ToString(); } private static void OnTracked(ComObject obj) { var handler = Tracked; if (handler != null) { handler(null, new ComObjectEventArgs(obj)); } } private static void OnUnTracked(ComObject obj) { var handler = UnTracked; if (handler != null) { handler(null, new ComObjectEventArgs(obj)); } } } }
// 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.IO; using Xunit; namespace System.IO.Tests { public class FileStream_Seek : FileSystemTest { [Fact] public void InvalidSeekOriginThrows() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { AssertExtensions.Throws<ArgumentException>("origin", null, () => fs.Seek(0, ~SeekOrigin.Begin)); } } [Fact] public void InvalidOffsetThrows() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { // Ensure our test is set up correctly Assert.Equal(0, fs.Length); Assert.Equal(0, fs.Position); Assert.Throws<IOException>(() => fs.Seek(-1, SeekOrigin.Begin)); Assert.Throws<IOException>(() => fs.Seek(-1, SeekOrigin.Current)); Assert.Throws<IOException>(() => fs.Seek(-1, SeekOrigin.End)); Assert.Throws<IOException>(() => fs.Seek(int.MinValue, SeekOrigin.Begin)); Assert.Throws<IOException>(() => fs.Seek(int.MinValue, SeekOrigin.Current)); Assert.Throws<IOException>(() => fs.Seek(int.MinValue, SeekOrigin.End)); } } [Fact] public void SeekDisposedThrows() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { fs.Dispose(); Assert.Throws<ObjectDisposedException>(() => fs.Seek(1, SeekOrigin.Begin)); // no fast path Assert.Throws<ObjectDisposedException>(() => fs.Seek(fs.Position, SeekOrigin.Begin)); // parameter checking happens first AssertExtensions.Throws<ArgumentException>("origin", null, () => fs.Seek(0, ~SeekOrigin.Begin)); } } [Fact] public void SeekUnseekableThrows() { using (FileStream fs = new UnseekableFileStream(GetTestFilePath(), FileMode.Create)) { Assert.Throws<NotSupportedException>(() => fs.Seek(1, SeekOrigin.Begin)); // no fast path Assert.Throws<NotSupportedException>(() => fs.Seek(fs.Position, SeekOrigin.Begin)); // parameter checking happens first AssertExtensions.Throws<ArgumentException>("origin", null, () => fs.Seek(0, ~SeekOrigin.Begin)); // dispose checking happens first fs.Dispose(); Assert.Throws<ObjectDisposedException>(() => fs.Seek(fs.Position, SeekOrigin.Begin)); } } [Fact] public void SeekAppendModifyThrows() { string fileName = GetTestFilePath(); using (FileStream fs = new FileStream(fileName, FileMode.Create)) { fs.Write(TestBuffer, 0, TestBuffer.Length); } using (FileStream fs = new FileStream(fileName, FileMode.Append)) { long length = fs.Length; Assert.Throws<IOException>(() => fs.Seek(length - 1, SeekOrigin.Begin)); Assert.Equal(length, fs.Position); Assert.Throws<IOException>(() => fs.Seek(-1, SeekOrigin.Current)); Assert.Equal(length, fs.Position); Assert.Throws<IOException>(() => fs.Seek(-1, SeekOrigin.End)); Assert.Equal(length, fs.Position); Assert.Throws<IOException>(() => fs.Seek(0, SeekOrigin.Begin)); Assert.Equal(length, fs.Position); Assert.Throws<IOException>(() => fs.Seek(-length, SeekOrigin.Current)); Assert.Equal(length, fs.Position); Assert.Throws<IOException>(() => fs.Seek(-length, SeekOrigin.End)); Assert.Equal(length, fs.Position); } } [Fact] public void SeekOriginBegin() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { fs.Write(TestBuffer, 0, TestBuffer.Length); // Ensure our test is set up correctly Assert.Equal(TestBuffer.Length, fs.Length); Assert.Equal(TestBuffer.Length, fs.Position); // Beginning Assert.Equal(0, fs.Seek(0, SeekOrigin.Begin)); Assert.Equal(0, fs.Position); // End Assert.Equal(fs.Length, fs.Seek(fs.Length, SeekOrigin.Begin)); Assert.Equal(fs.Length, fs.Position); // Middle Assert.Equal(fs.Length / 2, fs.Seek(fs.Length / 2, SeekOrigin.Begin)); Assert.Equal(fs.Length / 2, fs.Position); } } [Fact] public void SeekOriginCurrent() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { fs.Write(TestBuffer, 0, TestBuffer.Length); // Ensure our test is set up correctly Assert.Equal(TestBuffer.Length, fs.Length); Assert.Equal(TestBuffer.Length, fs.Position); // Beginning Assert.Equal(0, fs.Seek(-fs.Length, SeekOrigin.Current)); Assert.Equal(0, fs.Position); // End Assert.Equal(fs.Length, fs.Seek(fs.Length, SeekOrigin.Current)); Assert.Equal(fs.Length, fs.Position); // Middle Assert.Equal(fs.Length / 2, fs.Seek(fs.Length / 2 - fs.Length, SeekOrigin.Current)); Assert.Equal(fs.Length / 2, fs.Position); } } [Fact] public void SeekOriginEnd() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { fs.Write(TestBuffer, 0, TestBuffer.Length); // Ensure our test is set up correctly Assert.Equal(TestBuffer.Length, fs.Length); Assert.Equal(TestBuffer.Length, fs.Position); // Beginning Assert.Equal(0, fs.Seek(-fs.Length, SeekOrigin.End)); Assert.Equal(0, fs.Position); // End Assert.Equal(fs.Length, fs.Seek(0, SeekOrigin.End)); Assert.Equal(fs.Length, fs.Position); // Middle Assert.Equal(fs.Length / 2, fs.Seek(fs.Length / 2 - fs.Length, SeekOrigin.End)); Assert.Equal(fs.Length / 2, fs.Position); } } [Fact] public void NoopSeeksDoNotChangePosition() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { fs.Write(TestBuffer, 0, TestBuffer.Length); // Ensure our test is set up correctly Assert.Equal(TestBuffer.Length, fs.Length); Assert.Equal(TestBuffer.Length, fs.Position); // end ValidateNoopSeeks(fs); fs.Seek(0, SeekOrigin.Begin); // beginning ValidateNoopSeeks(fs); fs.Seek(fs.Length / 2, SeekOrigin.Begin); // middle ValidateNoopSeeks(fs); } } private void ValidateNoopSeeks(Stream stream) { // validate seeks that don't change position long position = stream.Position; Assert.Equal(position, stream.Seek(position, SeekOrigin.Begin)); Assert.Equal(position, stream.Position); Assert.Equal(position, stream.Seek(0, SeekOrigin.Current)); Assert.Equal(position, stream.Position); Assert.Equal(position, stream.Seek(position - stream.Length, SeekOrigin.End)); Assert.Equal(position, stream.Position); } [Fact] public void SeekPastEnd() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { fs.Write(TestBuffer, 0, TestBuffer.Length); // Ensure our test is set up correctly Assert.Equal(TestBuffer.Length, fs.Length); Assert.Equal(TestBuffer.Length, fs.Position); long originalLength = TestBuffer.Length; // Move past end Assert.Equal(originalLength + 1, fs.Seek(fs.Length + 1, SeekOrigin.Begin)); Assert.Equal(originalLength + 1, fs.Position); // Length is not updated until a write Assert.Equal(originalLength, fs.Length); // At end of stream Assert.Equal(-1, fs.ReadByte()); // Read should not update position or length Assert.Equal(originalLength + 1, fs.Position); Assert.Equal(originalLength, fs.Length); // Move back one, still at end of stream since length hasn't changed Assert.Equal(originalLength, fs.Seek(-1, SeekOrigin.Current)); Assert.Equal(-1, fs.ReadByte()); // Read should not update position or length Assert.Equal(originalLength, fs.Position); Assert.Equal(originalLength, fs.Length); // Move past end Assert.Equal(originalLength + 1, fs.Seek(fs.Length + 1, SeekOrigin.Begin)); fs.WriteByte(0x2A); // Writing a single byte should update length by 2 (filling gap with zero). Assert.Equal(originalLength + 2, fs.Position); Assert.Equal(originalLength + 2, fs.Length); // Validate zero fill Assert.Equal(originalLength, fs.Seek(-2, SeekOrigin.Current)); Assert.Equal(0, fs.ReadByte()); // Validate written value Assert.Equal(0x2A, fs.ReadByte()); } } [Fact] public void RandomSeekReadConsistency() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { var rand = new Random(1); // fixed seed to enable repeatable runs const int Trials = 1000; const int FileLength = 0x4000; const int MaxBytesToRead = 21; // Write data to the file var buffer = new byte[FileLength]; for (int i = 0; i < buffer.Length; i++) buffer[i] = unchecked((byte)i); fs.Write(buffer, 0, buffer.Length); fs.Position = 0; // Repeatedly jump around, reading, and making sure we get the right data back for (int trial = 0; trial < Trials; trial++) { // Pick some number of bytes to read int bytesToRead = rand.Next(1, MaxBytesToRead); // Jump to a random position, seeking either from one of the possible origins SeekOrigin origin = (SeekOrigin)rand.Next(3); int offset = 0; switch (origin) { case SeekOrigin.Begin: offset = rand.Next(0, (int)fs.Length - bytesToRead); break; case SeekOrigin.Current: offset = rand.Next(-(int)fs.Position + bytesToRead, (int)fs.Length - (int)fs.Position - bytesToRead); break; case SeekOrigin.End: offset = -rand.Next(bytesToRead, (int)fs.Length); break; } long pos = fs.Seek(offset, origin); Assert.InRange(pos, 0, fs.Length - bytesToRead - 1); // Read the requested number of bytes, and verify each is correct for (int i = 0; i < bytesToRead; i++) { int byteRead = fs.ReadByte(); Assert.Equal(buffer[pos + i], byteRead); } } } } } }
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Moq.Language; using Moq.Language.Flow; using Moq.Properties; namespace Moq.Protected { internal sealed class ProtectedAsMock<T, TAnalog> : IProtectedAsMock<T, TAnalog> where T : class where TAnalog : class { private Mock<T> mock; private static DuckReplacer DuckReplacerInstance = new DuckReplacer(typeof(TAnalog), typeof(T)); public ProtectedAsMock(Mock<T> mock) { Debug.Assert(mock != null); this.mock = mock; } public ISetup<T> Setup(Expression<Action<TAnalog>> expression) { Guard.NotNull(expression, nameof(expression)); Expression<Action<T>> rewrittenExpression; try { rewrittenExpression = (Expression<Action<T>>)ReplaceDuck(expression); } catch (ArgumentException ex) { throw new ArgumentException(ex.Message, nameof(expression)); } var setup = Mock.Setup(this.mock, rewrittenExpression, null); return new VoidSetupPhrase<T>(setup); } public ISetup<T, TResult> Setup<TResult>(Expression<Func<TAnalog, TResult>> expression) { Guard.NotNull(expression, nameof(expression)); Expression<Func<T, TResult>> rewrittenExpression; try { rewrittenExpression = (Expression<Func<T, TResult>>)ReplaceDuck(expression); } catch (ArgumentException ex) { throw new ArgumentException(ex.Message, nameof(expression)); } var setup = Mock.Setup(this.mock, rewrittenExpression, null); return new NonVoidSetupPhrase<T, TResult>(setup); } public ISetupGetter<T, TProperty> SetupGet<TProperty>(Expression<Func<TAnalog, TProperty>> expression) { Guard.NotNull(expression, nameof(expression)); Expression<Func<T, TProperty>> rewrittenExpression; try { rewrittenExpression = (Expression<Func<T, TProperty>>)ReplaceDuck(expression); } catch (ArgumentException ex) { throw new ArgumentException(ex.Message, nameof(expression)); } var setup = Mock.SetupGet(this.mock, rewrittenExpression, null); return new NonVoidSetupPhrase<T, TProperty>(setup); } public Mock<T> SetupProperty<TProperty>(Expression<Func<TAnalog, TProperty>> expression, TProperty initialValue = default(TProperty)) { Guard.NotNull(expression, nameof(expression)); Expression<Func<T, TProperty>> rewrittenExpression; try { rewrittenExpression = (Expression<Func<T, TProperty>>)ReplaceDuck(expression); } catch (ArgumentException ex) { throw new ArgumentException(ex.Message, nameof(expression)); } return this.mock.SetupProperty<TProperty>(rewrittenExpression, initialValue); } public ISetupSequentialResult<TResult> SetupSequence<TResult>(Expression<Func<TAnalog, TResult>> expression) { Guard.NotNull(expression, nameof(expression)); Expression<Func<T, TResult>> rewrittenExpression; try { rewrittenExpression = (Expression<Func<T, TResult>>)ReplaceDuck(expression); } catch (ArgumentException ex) { throw new ArgumentException(ex.Message, nameof(expression)); } var setup = Mock.SetupSequence(this.mock, rewrittenExpression); return new SetupSequencePhrase<TResult>(setup); } public ISetupSequentialAction SetupSequence(Expression<Action<TAnalog>> expression) { Guard.NotNull(expression, nameof(expression)); Expression<Action<T>> rewrittenExpression; try { rewrittenExpression = (Expression<Action<T>>)ReplaceDuck(expression); } catch (ArgumentException ex) { throw new ArgumentException(ex.Message, nameof(expression)); } var setup = Mock.SetupSequence(this.mock, rewrittenExpression); return new SetupSequencePhrase(setup); } public void Verify(Expression<Action<TAnalog>> expression, Times? times = null, string failMessage = null) { Guard.NotNull(expression, nameof(expression)); Expression<Action<T>> rewrittenExpression; try { rewrittenExpression = (Expression<Action<T>>)ReplaceDuck(expression); } catch (ArgumentException ex) { throw new ArgumentException(ex.Message, nameof(expression)); } Mock.Verify(this.mock, rewrittenExpression, times ?? Times.AtLeastOnce(), failMessage); } public void Verify<TResult>(Expression<Func<TAnalog, TResult>> expression, Times? times = null, string failMessage = null) { Guard.NotNull(expression, nameof(expression)); Expression<Func<T, TResult>> rewrittenExpression; try { rewrittenExpression = (Expression<Func<T, TResult>>)ReplaceDuck(expression); } catch (ArgumentException ex) { throw new ArgumentException(ex.Message, nameof(expression)); } Mock.Verify(this.mock, rewrittenExpression, times ?? Times.AtLeastOnce(), failMessage); } public void VerifyGet<TProperty>(Expression<Func<TAnalog, TProperty>> expression, Times? times = null, string failMessage = null) { Guard.NotNull(expression, nameof(expression)); Expression<Func<T, TProperty>> rewrittenExpression; try { rewrittenExpression = (Expression<Func<T, TProperty>>)ReplaceDuck(expression); } catch (ArgumentException ex) { throw new ArgumentException(ex.Message, nameof(expression)); } Mock.VerifyGet(this.mock, rewrittenExpression, times ?? Times.AtLeastOnce(), failMessage); } private static LambdaExpression ReplaceDuck(LambdaExpression expression) { Debug.Assert(expression.Parameters.Count == 1); var targetParameter = Expression.Parameter(typeof(T), expression.Parameters[0].Name); return Expression.Lambda(DuckReplacerInstance.Visit(expression.Body), targetParameter); } /// <summary> /// <see cref="ExpressionVisitor"/> used to replace occurrences of `TAnalog.Member` sub-expressions with `T.Member`. /// </summary> private sealed class DuckReplacer : ExpressionVisitor { private Type duckType; private Type targetType; public DuckReplacer(Type duckType, Type targetType) { this.duckType = duckType; this.targetType = targetType; } protected override Expression VisitMethodCall(MethodCallExpression node) { if (node.Object is ParameterExpression left && left.Type == this.duckType) { var targetParameter = Expression.Parameter(this.targetType, left.Name); return Expression.Call(targetParameter, FindCorrespondingMethod(node.Method), node.Arguments); } else { return node; } } protected override Expression VisitMember(MemberExpression node) { if (node.Expression is ParameterExpression left && left.Type == this.duckType) { var targetParameter = Expression.Parameter(this.targetType, left.Name); return Expression.MakeMemberAccess(targetParameter, FindCorrespondingMember(node.Member)); } else { return node; } } private MemberInfo FindCorrespondingMember(MemberInfo duckMember) { if (duckMember is MethodInfo duckMethod) { return FindCorrespondingMethod(duckMethod); } else if (duckMember is PropertyInfo duckProperty) { return FindCorrespondingProperty(duckProperty); } else { throw new NotSupportedException(); } } private MethodInfo FindCorrespondingMethod(MethodInfo duckMethod) { var candidateTargetMethods = this.targetType .GetMethods(BindingFlags.NonPublic | BindingFlags.Instance) .Where(ctm => IsCorrespondingMethod(duckMethod, ctm)) .ToArray(); if (candidateTargetMethods.Length == 0) { throw new ArgumentException(string.Format(Resources.ProtectedMemberNotFound, this.targetType, duckMethod)); } Debug.Assert(candidateTargetMethods.Length == 1); var targetMethod = candidateTargetMethods[0]; if (targetMethod.IsGenericMethodDefinition) { var duckGenericArgs = duckMethod.GetGenericArguments(); targetMethod = targetMethod.MakeGenericMethod(duckGenericArgs); } return targetMethod; } private PropertyInfo FindCorrespondingProperty(PropertyInfo duckProperty) { var candidateTargetProperties = this.targetType .GetProperties(BindingFlags.NonPublic | BindingFlags.Instance) .Where(ctp => IsCorrespondingProperty(duckProperty, ctp)) .ToArray(); if (candidateTargetProperties.Length == 0) { throw new ArgumentException(string.Format(Resources.ProtectedMemberNotFound, this.targetType, duckProperty)); } Debug.Assert(candidateTargetProperties.Length == 1); return candidateTargetProperties[0]; } private static bool IsCorrespondingMethod(MethodInfo duckMethod, MethodInfo candidateTargetMethod) { if (candidateTargetMethod.Name != duckMethod.Name) { return false; } if (candidateTargetMethod.IsGenericMethod != duckMethod.IsGenericMethod) { return false; } if (candidateTargetMethod.IsGenericMethodDefinition) { // when both methods are generic, then the candidate method should be an open generic method // while the duck-type method should be a closed one. in this case, we close the former // over the same generic type arguments that the latter uses. Debug.Assert(!duckMethod.IsGenericMethodDefinition); var candidateGenericArgs = candidateTargetMethod.GetGenericArguments(); var duckGenericArgs = duckMethod.GetGenericArguments(); if (candidateGenericArgs.Length != duckGenericArgs.Length) { return false; } // this could perhaps go wrong due to generic type parameter constraints; if it does // go wrong, then obviously the duck-type method doesn't correspond to the candidate. try { candidateTargetMethod = candidateTargetMethod.MakeGenericMethod(duckGenericArgs); } catch { return false; } } var duckParameters = duckMethod.GetParameters(); var candidateParameters = candidateTargetMethod.GetParameters(); if (candidateParameters.Length != duckParameters.Length) { return false; } for (int i = 0, n = candidateParameters.Length; i < n; ++i) { if (candidateParameters[i].ParameterType != duckParameters[i].ParameterType) { return false; } } return true; } private static bool IsCorrespondingProperty(PropertyInfo duckProperty, PropertyInfo candidateTargetProperty) { return candidateTargetProperty.Name == duckProperty.Name && candidateTargetProperty.PropertyType == duckProperty.PropertyType && candidateTargetProperty.CanRead(out _) == duckProperty.CanRead(out _) && candidateTargetProperty.CanWrite(out _) == duckProperty.CanWrite(out _); // TODO: parameter lists should be compared, too, to properly support indexers. } } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using SDKTemplate.Helpers; using SDKTemplate.Logging; using System; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Foundation.Collections; using Windows.Media.Core; using Windows.Media.Playback; using Windows.Media.Streaming.Adaptive; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using Windows.Web.Http; namespace SDKTemplate { /// See the README.md for discussion of this scenario. public sealed partial class Scenario6_AdInsertion : Page { public Scenario6_AdInsertion() { this.InitializeComponent(); } protected override void OnNavigatedFrom(NavigationEventArgs e) { // Release handles on various media objects to ensure a quick clean-up ContentSelectorControl.MediaPlaybackItem = null; var mediaPlayer = mediaPlayerElement.MediaPlayer; if (mediaPlayer != null) { mediaPlayerLogger?.Dispose(); mediaPlayerLogger = null; UnregisterHandlers(mediaPlayer); mediaPlayer.DisposeSource(); mediaPlayerElement.SetMediaPlayer(null); mediaPlayer.Dispose(); } } private void UnregisterHandlers(MediaPlayer mediaPlayer) { AdaptiveMediaSource adaptiveMediaSource = null; MediaPlaybackItem mpItem = mediaPlayer.Source as MediaPlaybackItem; if (mpItem != null) { adaptiveMediaSource = mpItem.Source.AdaptiveMediaSource; UnregisterForMediaSourceEvents(mpItem.Source); UnregisterForMediaPlaybackItemEvents(mpItem); } MediaSource source = mediaPlayer.Source as MediaSource; if (source != null) { adaptiveMediaSource = source.AdaptiveMediaSource; UnregisterForMediaSourceEvents(source); } mediaPlaybackItemLogger?.Dispose(); mediaPlaybackItemLogger = null; mediaSourceLogger?.Dispose(); mediaSourceLogger = null; adaptiveMediaSourceLogger?.Dispose(); adaptiveMediaSourceLogger = null; } private void Page_OnLoaded(object sender, RoutedEventArgs e) { var mediaPlayer = new MediaPlayer(); // We use a helper class that logs all the events for the MediaPlayer: mediaPlayerLogger = new MediaPlayerLogger(LoggerControl, mediaPlayer); // Ensure we have PlayReady support, in case the user enters a DASH/PR Uri in the text box. var prHelper = new PlayReadyHelper(LoggerControl); prHelper.SetUpProtectionManager(mediaPlayer); mediaPlayerElement.SetMediaPlayer(mediaPlayer); ContentSelectorControl.Initialize( mediaPlayer, MainPage.ContentManagementSystemStub.Where(m => !m.Aes), null, LoggerControl, LoadSourceFromUriAsync); } #region Content Loading private async Task<MediaPlaybackItem> LoadSourceFromUriAsync(Uri uri, HttpClient httpClient = null) { UnregisterHandlers(mediaPlayerElement.MediaPlayer); mediaPlayerElement.MediaPlayer?.DisposeSource(); AdaptiveMediaSourceCreationResult result = null; if (httpClient != null) { result = await AdaptiveMediaSource.CreateFromUriAsync(uri, httpClient); } else { result = await AdaptiveMediaSource.CreateFromUriAsync(uri); } MediaSource source; if (result.Status == AdaptiveMediaSourceCreationStatus.Success) { var adaptiveMediaSource = result.MediaSource; // We use a helper class that logs all the events for the AdaptiveMediaSource: adaptiveMediaSourceLogger = new AdaptiveMediaSourceLogger(LoggerControl, adaptiveMediaSource); source = MediaSource.CreateFromAdaptiveMediaSource(adaptiveMediaSource); } else { Log($"Error creating the AdaptiveMediaSource. Status: {result.Status}, ExtendedError.Message: {result.ExtendedError.Message}, ExtendedError.HResult: {result.ExtendedError.HResult.ToString("X8")}"); return null; } // We use a helper class that logs all the events for the MediaSource: mediaSourceLogger = new MediaSourceLogger(LoggerControl, source); // Save the original Uri. source.CustomProperties["uri"] = uri.ToString(); // You're likely to put a content tracking id into the CustomProperties. source.CustomProperties["contentId"] = "MainContent_ID"; // In addition to logging, this scenario uses MediaSource events: RegisterForMediaSourceEvents(source); var mpItem = new MediaPlaybackItem(source); // We use a helper class that logs all the events for the MediaPlaybackItem: mediaPlaybackItemLogger = new MediaPlaybackItemLogger(LoggerControl, mpItem); // In addition to logging, this scenario uses MediaPlaybackItem events: RegisterForMediaPlaybackItemEvents(mpItem); // Now that we should have a MediaPlaybackItem, we will insert pre- mid- and post-roll ads // with the MediaBreak API. CreateMediaBreaksForItem(mpItem); HideDescriptionOnSmallScreen(); return mpItem; } private async void HideDescriptionOnSmallScreen() { // On small screens, hide the description text to make room for the video. await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { DescriptionText.Visibility = (ActualHeight < 500) ? Visibility.Collapsed : Visibility.Visible; }); } private void CreateMediaBreaksForItem(MediaPlaybackItem item) { if (item != null) { // We have two ads that will be repeated. var redSkyUri = new Uri("http://az29176.vo.msecnd.net/videocontent/RedSky_FoxRiverWisc_GettyImagesRF-499617760_1080_HD_EN-US.mp4"); var flowersUri = new Uri("http://az29176.vo.msecnd.net/videocontent/CrocusTL_FramePoolRM_688-580-676_1080_HD_EN-US.mp4"); // One option is to create a separate MediaPlaybackItem for each of your ads. // You might choose to do this if each ad needs different reporting information. // Another option is to re-use MediaPlaybackItems in different MediaBreaks. // This scenario demonstrates both patterns. var ad1 = new MediaPlaybackItem(MediaSource.CreateFromUri(redSkyUri)); ad1.Source.CustomProperties["contentId"] = "Ad1_ID"; ad1.Source.CustomProperties["description"] = "Red Sky"; ad1.Source.CustomProperties["uri"] = redSkyUri.ToString(); RegisterForMediaSourceEvents(ad1.Source); RegisterForMediaPlaybackItemEvents(ad1); var ad2 = new MediaPlaybackItem(MediaSource.CreateFromUri(flowersUri)); ad2.Source.CustomProperties["contentId"] = "Ad2_ID"; ad2.Source.CustomProperties["description"] = "Flowers"; ad2.Source.CustomProperties["uri"] = flowersUri.ToString(); RegisterForMediaSourceEvents(ad2.Source); RegisterForMediaPlaybackItemEvents(ad2); var ad3 = new MediaPlaybackItem(MediaSource.CreateFromUri(redSkyUri)); ad3.Source.CustomProperties["contentId"] = "Ad3_ID"; ad3.Source.CustomProperties["description"] = "Red Sky 2"; ad3.Source.CustomProperties["uri"] = redSkyUri.ToString(); RegisterForMediaSourceEvents(ad3.Source); RegisterForMediaPlaybackItemEvents(ad3); // Create a PrerollBreak on your main content. if (item.BreakSchedule.PrerollBreak == null) { item.BreakSchedule.PrerollBreak = new MediaBreak(MediaBreakInsertionMethod.Interrupt); } // Add the ads to the PrerollBreak in the order you want them played item.BreakSchedule.PrerollBreak.PlaybackList.Items.Add(ad1); item.BreakSchedule.PrerollBreak.PlaybackList.Items.Add(ad2); // Add the ads to the MidRoll break at 10% into the main content. // To do this, we need to wait until the main MediaPlaybackItem is fully loaded by the player // so that we know its Duration. This will happen on MediaSource.OpenOperationCompleted. item.Source.OpenOperationCompleted += (sender, args) => { var attachedItem = MediaPlaybackItem.FindFromMediaSource(sender); if (sender.Duration.HasValue) { // For live streaming, the duration will be TimeSpan.MaxValue, which won't work for this scenario, // so we'll assume the total duration is 2 minutes for the purpose of ad insertion. bool isLiveMediaSource = item.Source.AdaptiveMediaSource != null ? item.Source.AdaptiveMediaSource.IsLive : false; long sourceDurationTicks = isLiveMediaSource ? TimeSpan.FromMinutes(2).Ticks : sender.Duration.Value.Ticks; var positionAt10PercentOfMainContent = TimeSpan.FromTicks(sourceDurationTicks / 10); // If the content is live, then the ad break replaces the streaming content. // If the content is not live, then the content pauses for the ad, and then resumes // after the ad is complete. MediaBreakInsertionMethod insertionMethod = isLiveMediaSource ? MediaBreakInsertionMethod.Replace : MediaBreakInsertionMethod.Interrupt; var midRollBreak = new MediaBreak(insertionMethod, positionAt10PercentOfMainContent); midRollBreak.PlaybackList.Items.Add(ad2); midRollBreak.PlaybackList.Items.Add(ad1); attachedItem.BreakSchedule.InsertMidrollBreak(midRollBreak); Log($"Added MidRoll at {positionAt10PercentOfMainContent}"); } }; // Create a PostrollBreak: // Note: for Live content, it will only play once the presentation transitions to VOD. if (item.BreakSchedule.PostrollBreak == null) { item.BreakSchedule.PostrollBreak = new MediaBreak(MediaBreakInsertionMethod.Interrupt); } // Add the ads to the PostrollBreak in the order you want them played item.BreakSchedule.PostrollBreak.PlaybackList.Items.Add(ad3); } } #endregion #region MediaSource Event Handlers private void RegisterForMediaSourceEvents(MediaSource source) { source.OpenOperationCompleted += Source_OpenOperationCompleted; } private void UnregisterForMediaSourceEvents(MediaSource source) { source.OpenOperationCompleted -= Source_OpenOperationCompleted; } private void Source_OpenOperationCompleted(MediaSource source, MediaSourceOpenOperationCompletedEventArgs args) { // Here we create our own metadata track. // Our goal is to track progress through the asset and report it back to a server. object customValue = null; source.CustomProperties.TryGetValue("contentId", out customValue); string contentId = (string)customValue; var reportingUriFormat = "http://myserver/reporting/{0}?id={1}"; // From \Shared\TrackingEventCue.cs: TrackingEventCue.CreateTrackingEventsTrack(source, contentId, reportingUriFormat); } #endregion #region MediaPlaybackItem Event Handlers private void RegisterForMediaPlaybackItemEvents(MediaPlaybackItem item) { // If we encountered some unknown tags in an m3u8 manifest, // we might already have metadata tracks in the source, // which is used as the constructor for the MediaPlaybackItem. // Therefore, the MediaPlaybackItem may already have metadata tracks. // Since TracksChanged will not be raised for these it is best to check // if we have tracks, and set up the handlers: if (item.TimedMetadataTracks.Count > 0) { Log($"Registering existing TimedMetadataTracks, Count: {item.TimedMetadataTracks.Count}"); for (int index = 0; index < item.TimedMetadataTracks.Count; index++) { RegisterMetadataHandlers(item, index); } } // For any tracks found as the content is parsed, we register for the event handler: item.TimedMetadataTracksChanged += Item_TimedMetadataTracksChanged; } private void UnregisterForMediaPlaybackItemEvents(MediaPlaybackItem item) { item.TimedMetadataTracksChanged -= Item_TimedMetadataTracksChanged; foreach (var track in item.TimedMetadataTracks) { UnregisterMetadataHandlers(track); } } private void Item_TimedMetadataTracksChanged(MediaPlaybackItem item, IVectorChangedEventArgs args) { Log($"item.TimedMetadataTracksChanged: CollectionChange:{args.CollectionChange} Index:{args.Index} Total:{item.TimedMetadataTracks.Count}"); if (args.CollectionChange == CollectionChange.ItemInserted) { RegisterMetadataHandlers(item, (int)args.Index); } if (args.CollectionChange == CollectionChange.Reset) { for (int index = 0; index < item.TimedMetadataTracks.Count; index++) { RegisterMetadataHandlers(item, index); } } } private void RegisterMetadataHandlers(MediaPlaybackItem mediaPlaybackItem, int index) { var timedTrack = mediaPlaybackItem.TimedMetadataTracks[index]; object customValue = null; mediaPlaybackItem.Source.CustomProperties.TryGetValue("contentId", out customValue); string contentId = (string)customValue; StringBuilder logMsg = new StringBuilder($"{contentId} "); if (timedTrack.TrackKind == MediaTrackKind.TimedMetadata && timedTrack.TimedMetadataKind == TimedMetadataKind.Custom) { // Check for our Custom TimedMetadataTrack if (mediaPlaybackItem.TimedMetadataTracks[index].Id == "TrackingEvents") { timedTrack.CueEntered += metadata_TrackingEvents_CueEntered; timedTrack.Label = "Tracking Events"; mediaPlaybackItem.TimedMetadataTracks.SetPresentationMode((uint)index, TimedMetadataTrackPresentationMode.ApplicationPresented); } logMsg.AppendLine($"Registered CueEntered for {timedTrack.Label}."); } else { logMsg.AppendLine("Did not register CueEntered for TimedMetadataTrack."); } logMsg.AppendLine($"TimedMetadataKind: {timedTrack.TimedMetadataKind}, Id: {timedTrack.Id}, Label: {timedTrack.Label}, DispatchType: {timedTrack.DispatchType}, Language: {timedTrack.Language}"); Log(logMsg.ToString()); } private void UnregisterMetadataHandlers(TimedMetadataTrack timedTrack) { if (timedTrack.Label == "Tracking Events") { timedTrack.CueEntered -= metadata_TrackingEvents_CueEntered; } } private void metadata_TrackingEvents_CueEntered(TimedMetadataTrack timedMetadataTrack, MediaCueEventArgs args) { StringBuilder logMsg = new StringBuilder(); object customValue = null; timedMetadataTrack.PlaybackItem.Source.CustomProperties.TryGetValue("contentId", out customValue); string contentId = (string)customValue; logMsg.AppendLine($"{contentId} TrackingEventCue CueEntered raised."); var trackingEventCue = args.Cue as TrackingEventCue; if (trackingEventCue != null) { logMsg.AppendLine($"Label: {timedMetadataTrack.Label}, Id: {trackingEventCue.Id}, StartTime: {trackingEventCue.StartTime}, Duration: {trackingEventCue.Duration}"); logMsg.Append($"{trackingEventCue.TrackingEventUri}"); // TODO: Use the reporing Uri. } Log(logMsg.ToString()); } #endregion #region Utilities private void Log(string message) { LoggerControl.Log(message); } MediaPlayerLogger mediaPlayerLogger; MediaSourceLogger mediaSourceLogger; MediaPlaybackItemLogger mediaPlaybackItemLogger; AdaptiveMediaSourceLogger adaptiveMediaSourceLogger; #endregion } }
using System; using System.Collections.Generic; using Newtonsoft.Json.Linq; using Wizcorp.MageSDK.MageClient; namespace Wizcorp.MageSDK.Tomes { public class TomeArray : JArray { // public Tome.OnChanged OnChanged; public Tome.OnDestroy OnDestroy; public Tome.OnAdd OnAdd; public Tome.OnDel OnDel; // private JToken root; // public TomeArray(JArray data, JToken root) { // this.root = root; if (this.root == null) { this.root = this; } // for (var i = 0; i < data.Count; i += 1) { Add(Tome.Conjure(data[i], this.root)); } // OnChanged += EmitToParents; OnAdd += EmitChanged; OnDel += EmitChanged; } // private void EmitToParents(JToken oldValue) { if (!ReferenceEquals(this, root)) { Tome.EmitParentChange(Parent); } } // private void EmitChanged(JToken key) { if (OnChanged != null) { OnChanged.Invoke(null); } } // public void Assign(JToken newValue) { lock ((object)this) { switch (newValue.Type) { case JTokenType.Array: var newTomeArray = new TomeArray((JArray)newValue, root); Replace(newTomeArray); if (Parent == null) { // If replace was successfuly move over event handlers and call new OnChanged handler // The instance in which replace would not be successful, is when the old and new values are the same OnChanged -= EmitToParents; OnChanged += newTomeArray.OnChanged; newTomeArray.OnChanged = OnChanged; newTomeArray.OnDestroy = OnDestroy; OnAdd -= EmitChanged; OnAdd += newTomeArray.OnAdd; newTomeArray.OnAdd = OnAdd; OnDel -= EmitChanged; OnDel += newTomeArray.OnDel; newTomeArray.OnDel = OnDel; if (newTomeArray.OnChanged != null) { newTomeArray.OnChanged.Invoke(null); } } else { // Otherwise call original OnChanged handler if (OnChanged != null) { OnChanged.Invoke(null); } } break; case JTokenType.Object: var newTomeObject = new TomeObject((JObject)newValue, root); Replace(newTomeObject); if (Parent == null) { // If replace was successfuly move over event handlers and call new OnChanged handler // The instance in which replace would not be successful, is when the old and new values are the same OnChanged -= EmitToParents; OnChanged += newTomeObject.OnChanged; newTomeObject.OnChanged = OnChanged; newTomeObject.OnDestroy = OnDestroy; OnAdd -= EmitChanged; OnAdd += newTomeObject.OnAdd; newTomeObject.OnAdd = OnAdd; OnDel -= EmitChanged; OnDel += newTomeObject.OnDel; newTomeObject.OnDel = OnDel; if (newTomeObject.OnChanged != null) { newTomeObject.OnChanged.Invoke(null); } } else { // Otherwise call original OnChanged handler if (OnChanged != null) { OnChanged.Invoke(null); } } break; default: var newTomeValue = new TomeValue((JValue)newValue, root); Replace(newTomeValue); if (Parent == null) { // If replace was successfuly move over event handlers and call new OnChanged handler // The instance in which replace would not be successful, is when the old and new values are the same OnChanged -= EmitToParents; OnChanged += newTomeValue.OnChanged; newTomeValue.OnChanged = OnChanged; newTomeValue.OnDestroy = OnDestroy; if (newTomeValue.OnChanged != null) { newTomeValue.OnChanged.Invoke(null); } } else { // Otherwise call original OnChanged handler if (OnChanged != null) { OnChanged.Invoke(null); } } break; } } } // public void Destroy() { lock ((object)this) { foreach (JToken value in this) { Tome.Destroy(value); } if (OnDestroy != null) { OnDestroy.Invoke(); } OnChanged = null; OnDestroy = null; OnAdd = null; OnDel = null; } } // public void Set(int index, JToken value) { lock ((object)this) { // Make sure the property exists, filling in missing indexes if (Count <= index) { while (Count < index) { Add(Tome.Conjure(JValue.CreateNull(), root)); } Add(Tome.Conjure(value, root)); if (OnAdd != null) { OnAdd.Invoke(index); } return; } // Assign the property JToken property = this[index]; switch (property.Type) { case JTokenType.Array: ((TomeArray)property).Assign(value); break; case JTokenType.Object: ((TomeObject)property).Assign(value); break; default: var tomeValue = property as TomeValue; if (tomeValue == null) { Mage.Instance.Logger("Tomes").Data(property).Error("property is not a tome value: " + index.ToString()); UnityEngine.Debug.Log(this); } else { tomeValue.Assign(value); } break; } } } // public void Del(int index) { lock ((object)this) { JToken property = this[index]; switch (property.Type) { case JTokenType.Array: ((TomeArray)property).Destroy(); break; case JTokenType.Object: ((TomeObject)property).Destroy(); break; default: var tomeValue = property as TomeValue; if (tomeValue == null) { Mage.Instance.Logger("Tomes").Data(property).Error("property is not a tome value:" + index.ToString()); UnityEngine.Debug.Log(this); } else { tomeValue.Destroy(); } break; } this[index].Replace(JValue.CreateNull()); if (OnDel != null) { OnDel.Invoke(index); } } } // public void Move(int fromKey, JToken newParent, JToken newKey) { lock ((object)this) { if (newParent.Type == JTokenType.Array) { ((TomeArray)newParent).Set((int)newKey, this[fromKey]); } else { ((TomeObject)newParent).Set((string)newKey, this[fromKey]); } Del(fromKey); } } // public void Rename(int wasKey, int isKey) { lock ((object)this) { JToken wasValue = this[wasKey]; Del(wasKey); Set(isKey, wasValue); } } // public void Swap(int firstKey, JToken secondParent, JToken secondKey) { lock ((object)this) { JToken secondValue; if (secondParent.Type == JTokenType.Array) { secondValue = secondParent[(int)secondKey]; secondParent[(int)secondKey].Replace(this[firstKey]); } else { secondValue = secondParent[(string)secondKey]; secondParent[(string)secondKey].Replace(this[firstKey]); } this[firstKey].Replace(secondValue); if (OnChanged != null) { OnChanged.Invoke(null); } } } // public void Push(JToken item) { lock ((object)this) { Set(Count, item); } } // NOTE: Tome behavior for a del operation is to replace values with null. // However a pop operation does in fact remove the item as well as // firing the del event. Thus we do both below. public JToken Pop() { lock ((object)this) { JToken last = this[Count - 1]; Del(Count - 1); Last.Remove(); return last; } } // NOTE: Tome behavior for a del operation is to replace values with null. // However a shift operation does in fact remove the item as well as // firing the del event. Thus we do both below. public JToken Shift() { lock ((object)this) { JToken first = this[0]; Del(0); First.Remove(); return first; } } // public void UnShift(JToken item) { lock ((object)this) { AddFirst(Tome.Conjure(item, root)); if (OnAdd != null) { OnAdd.Invoke(0); } } } // public void Reverse() { lock ((object)this) { var oldOrder = new JArray(this); for (int i = oldOrder.Count; i > 0; i -= 1) { this[oldOrder.Count - i].Replace(oldOrder[i - 1]); } if (OnChanged != null) { OnChanged.Invoke(null); } } } // public void Splice(int index, int deleteCount, JArray insertItems) { lock ((object)this) { // Delete given item count starting at given index for (int delI = index + deleteCount - 1; delI >= index; delI -= 1) { if (delI > Count - 1) { continue; } Del(delI); this[delI].Remove(); } // Insert given items starting at given index for (var addI = 0; addI < insertItems.Count; addI += 1) { int insertI = index + addI; Insert(insertI, Tome.Conjure(insertItems[addI])); if (OnAdd != null) { OnAdd.Invoke(insertI); } } } } // We implement this as when using JArray.IndexOf(JToken) it compares the reference but not the value. public int IndexOf(string lookFor) { lock ((object)this) { for (var i = 0; i < Count; i += 1) { JToken value = this[i]; if (value.Type == JTokenType.String && (string)value == lookFor) { return i; } } return -1; } } // public void ApplyOperation(string op, JToken val, JToken root) { lock ((object)this) { switch (op) { case "assign": Assign(val); break; case "set": Set((int)val["key"], val["val"]); break; case "del": Del((int)val); break; case "move": var fromKey = (int)val["key"]; JToken newParent = Tome.PathValue(root, val["newParent"] as JArray); JToken toKey = (val["newKey"] != null) ? val["newKey"] : new JValue(fromKey); Move(fromKey, newParent, toKey); break; case "rename": foreach (KeyValuePair<string, JToken> property in (JObject)val) { int wasKey = int.Parse(property.Key); var isKey = (int)property.Value; Rename(wasKey, isKey); } break; case "swap": var firstKey = (int)val["key"]; JToken secondParent = Tome.PathValue(root, val["newParent"] as JArray); JToken secondKey = (val["newKey"] != null) ? val["newKey"] : new JValue(firstKey); Swap(firstKey, secondParent, secondKey); break; case "push": foreach (JToken item in (JArray)val) { Push(item); } break; case "pop": Pop(); break; case "shift": Shift(); break; case "unshift": var unshiftItems = val as JArray; for (int i = unshiftItems.Count; i > 0; i -= 1) { UnShift(unshiftItems[i - 1]); } break; case "reverse": Reverse(); break; case "splice": var index = (int)val[0]; var deleteCount = (int)val[1]; var items = new JArray(val as JArray); items.First.Remove(); items.First.Remove(); Splice(index, deleteCount, items); break; default: throw new Exception("TomeArray - Unsupported operation: " + op); } } } } }
using Lucene.Net.Support; namespace Lucene.Net.Util // from org.apache.solr.util rev 555343 { /* * 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. */ /// <summary> /// A variety of high efficiency bit twiddling routines. /// <para/> /// @lucene.internal /// </summary> public sealed class BitUtil { private static readonly sbyte[] BYTE_COUNTS = new sbyte[] { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 }; // table of bits/byte // The General Idea: instead of having an array per byte that has // the offsets of the next set bit, that array could be // packed inside a 32 bit integer (8 4 bit numbers). That // should be faster than accessing an array for each index, and // the total array size is kept smaller (256*sizeof(int))=1K /// <summary> /// the python code that generated bitlist /// <code> /// def bits2int(val): /// arr=0 /// for shift in range(8,0,-1): /// if val &amp; 0x80: /// arr = (arr &lt;&lt; 4) | shift /// val = val &lt;&lt; 1 /// return arr /// /// def int_table(): /// tbl = [ hex(bits2int(val)).strip('L') for val in range(256) ] /// return ','.join(tbl) /// </code> /// </summary> private static readonly int[] BIT_LISTS = new int[] { 0x0, 0x1, 0x2, 0x21, 0x3, 0x31, 0x32, 0x321, 0x4, 0x41, 0x42, 0x421, 0x43, 0x431, 0x432, 0x4321, 0x5, 0x51, 0x52, 0x521, 0x53, 0x531, 0x532, 0x5321, 0x54, 0x541, 0x542, 0x5421, 0x543, 0x5431, 0x5432, 0x54321, 0x6, 0x61, 0x62, 0x621, 0x63, 0x631, 0x632, 0x6321, 0x64, 0x641, 0x642, 0x6421, 0x643, 0x6431, 0x6432, 0x64321, 0x65, 0x651, 0x652, 0x6521, 0x653, 0x6531, 0x6532, 0x65321, 0x654, 0x6541, 0x6542, 0x65421, 0x6543, 0x65431, 0x65432, 0x654321, 0x7, 0x71, 0x72, 0x721, 0x73, 0x731, 0x732, 0x7321, 0x74, 0x741, 0x742, 0x7421, 0x743, 0x7431, 0x7432, 0x74321, 0x75, 0x751, 0x752, 0x7521, 0x753, 0x7531, 0x7532, 0x75321, 0x754, 0x7541, 0x7542, 0x75421, 0x7543, 0x75431, 0x75432, 0x754321, 0x76, 0x761, 0x762, 0x7621, 0x763, 0x7631, 0x7632, 0x76321, 0x764, 0x7641, 0x7642, 0x76421, 0x7643, 0x76431, 0x76432, 0x764321, 0x765, 0x7651, 0x7652, 0x76521, 0x7653, 0x76531, 0x76532, 0x765321, 0x7654, 0x76541, 0x76542, 0x765421, 0x76543, 0x765431, 0x765432, 0x7654321, 0x8, 0x81, 0x82, 0x821, 0x83, 0x831, 0x832, 0x8321, 0x84, 0x841, 0x842, 0x8421, 0x843, 0x8431, 0x8432, 0x84321, 0x85, 0x851, 0x852, 0x8521, 0x853, 0x8531, 0x8532, 0x85321, 0x854, 0x8541, 0x8542, 0x85421, 0x8543, 0x85431, 0x85432, 0x854321, 0x86, 0x861, 0x862, 0x8621, 0x863, 0x8631, 0x8632, 0x86321, 0x864, 0x8641, 0x8642, 0x86421, 0x8643, 0x86431, 0x86432, 0x864321, 0x865, 0x8651, 0x8652, 0x86521, 0x8653, 0x86531, 0x86532, 0x865321, 0x8654, 0x86541, 0x86542, 0x865421, 0x86543, 0x865431, 0x865432, 0x8654321, 0x87, 0x871, 0x872, 0x8721, 0x873, 0x8731, 0x8732, 0x87321, 0x874, 0x8741, 0x8742, 0x87421, 0x8743, 0x87431, 0x87432, 0x874321, 0x875, 0x8751, 0x8752, 0x87521, 0x8753, 0x87531, 0x87532, 0x875321, 0x8754, 0x87541, 0x87542, 0x875421, 0x87543, 0x875431, 0x875432, 0x8754321, 0x876, 0x8761, 0x8762, 0x87621, 0x8763, 0x87631, 0x87632, 0x876321, 0x8764, 0x87641, 0x87642, 0x876421, 0x87643, 0x876431, 0x876432, 0x8764321, 0x8765, 0x87651, 0x87652, 0x876521, 0x87653, 0x876531, 0x876532, 0x8765321, 0x87654, 0x876541, 0x876542, 0x8765421, 0x876543, 0x8765431, 0x8765432, unchecked((int)0x87654321) }; private BitUtil() // no instance { } /// <summary> /// Return the number of bits sets in <paramref name="b"/>. </summary> public static int BitCount(byte b) { return BYTE_COUNTS[b & 0xFF]; } /// <summary> /// Return the list of bits which are set in <paramref name="b"/> encoded as followed: /// <code>(i >>> (4 * n)) &amp; 0x0F</code> is the offset of the n-th set bit of /// the given byte plus one, or 0 if there are n or less bits set in the given /// byte. For example <code>bitList(12)</code> returns 0x43: /// <list type="bullet"> /// <item><description><code>0x43 &amp; 0x0F</code> is 3, meaning the the first bit set is at offset 3-1 = 2,</description></item> /// <item><description><code>(0x43 >>> 4) &amp; 0x0F</code> is 4, meaning there is a second bit set at offset 4-1=3,</description></item> /// <item><description><code>(0x43 >>> 8) &amp; 0x0F</code> is 0, meaning there is no more bit set in this byte.</description></item> /// </list> /// </summary> public static int BitList(byte b) { return BIT_LISTS[b & 0xFF]; } // The pop methods used to rely on bit-manipulation tricks for speed but it // turns out that it is faster to use the Long.bitCount method (which is an // intrinsic since Java 6u18) in a naive loop, see LUCENE-2221 /// <summary> /// Returns the number of set bits in an array of <see cref="long"/>s. </summary> public static long Pop_Array(long[] arr, int wordOffset, int numWords) { long popCount = 0; for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) { popCount += Number.BitCount(arr[i]); } return popCount; } /// <summary> /// Returns the popcount or cardinality of the two sets after an intersection. /// Neither array is modified. /// </summary> public static long Pop_Intersect(long[] arr1, long[] arr2, int wordOffset, int numWords) { long popCount = 0; for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) { popCount += Number.BitCount(arr1[i] & arr2[i]); } return popCount; } /// <summary> /// Returns the popcount or cardinality of the union of two sets. /// Neither array is modified. /// </summary> public static long Pop_Union(long[] arr1, long[] arr2, int wordOffset, int numWords) { long popCount = 0; for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) { popCount += Number.BitCount(arr1[i] | arr2[i]); } return popCount; } /// <summary> /// Returns the popcount or cardinality of A &amp; ~B. /// Neither array is modified. /// </summary> public static long Pop_AndNot(long[] arr1, long[] arr2, int wordOffset, int numWords) { long popCount = 0; for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) { popCount += Number.BitCount(arr1[i] & ~arr2[i]); } return popCount; } /// <summary> /// Returns the popcount or cardinality of A ^ B /// Neither array is modified. /// </summary> public static long Pop_Xor(long[] arr1, long[] arr2, int wordOffset, int numWords) { long popCount = 0; for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) { popCount += Number.BitCount(arr1[i] ^ arr2[i]); } return popCount; } /// <summary> /// Returns the next highest power of two, or the current value if it's already a power of two or zero </summary> public static int NextHighestPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } /// <summary> /// Returns the next highest power of two, or the current value if it's already a power of two or zero </summary> public static long NextHighestPowerOfTwo(long v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v |= v >> 32; v++; return v; } } }
// Generated by UblXml2CSharp using System.Xml; using UblLarsen.Ubl2; using UblLarsen.Ubl2.Cac; using UblLarsen.Ubl2.Ext; using UblLarsen.Ubl2.Udt; namespace UblLarsen.Test.UblClass { internal class UBLOrder20Example { public static OrderType Create() { var doc = new OrderType { UBLVersionID = "2.0", CustomizationID = "urn:oasis:names:specification:ubl:xpath:Order-2.0:sbs-1.0-draft", ProfileID = "bpid:urn:oasis:names:draft:bpss:ubl-2-sbs-order-with-simple-response-draft", ID = "AEG012345", SalesOrderID = "CON0095678", CopyIndicator = false, UUID = "6E09886B-DC6E-439F-82D1-7CCAC7F4E3B1", IssueDate = "2005-06-20", Note = new TextType[] { new TextType { Value = "sample" } }, BuyerCustomerParty = new CustomerPartyType { CustomerAssignedAccountID = "XFB01", SupplierAssignedAccountID = "GT00978567", Party = new PartyType { PartyName = new PartyNameType[] { new PartyNameType { Name = "IYT Corporation" } }, PostalAddress = new AddressType { StreetName = "Avon Way", BuildingName = "Thereabouts", BuildingNumber = "56A", CityName = "Bridgtow", PostalZone = "ZZ99 1ZZ", CountrySubentity = "Avon", AddressLine = new AddressLineType[] { new AddressLineType { Line = "3rd Floor, Room 5" } }, Country = new CountryType { IdentificationCode = "GB" } }, PartyTaxScheme = new PartyTaxSchemeType[] { new PartyTaxSchemeType { RegistrationName = "Bridgtow District Council", CompanyID = "12356478", ExemptionReason = new TextType[] { new TextType { Value = "Local Authority" } }, TaxScheme = new TaxSchemeType { ID = "UK VAT", TaxTypeCode = "VAT" } } }, Contact = new ContactType { Name = "Mr Fred Churchill", Telephone = "0127 2653214", Telefax = "0127 2653215", ElectronicMail = "[email protected]" } } }, SellerSupplierParty = new SupplierPartyType { CustomerAssignedAccountID = "CO001", Party = new PartyType { PartyName = new PartyNameType[] { new PartyNameType { Name = "Consortial" } }, PostalAddress = new AddressType { StreetName = "Busy Street", BuildingName = "Thereabouts", BuildingNumber = "56A", CityName = "Farthing", PostalZone = "AA99 1BB", CountrySubentity = "Heremouthshire", AddressLine = new AddressLineType[] { new AddressLineType { Line = "The Roundabout" } }, Country = new CountryType { IdentificationCode = "GB" } }, PartyTaxScheme = new PartyTaxSchemeType[] { new PartyTaxSchemeType { RegistrationName = "Farthing Purchasing Consortium", CompanyID = "175 269 2355", ExemptionReason = new TextType[] { new TextType { Value = "N/A" } }, TaxScheme = new TaxSchemeType { ID = "VAT", TaxTypeCode = "VAT" } } }, Contact = new ContactType { Name = "Mrs Bouquet", Telephone = "0158 1233714", Telefax = "0158 1233856", ElectronicMail = "[email protected]" } } }, OriginatorCustomerParty = new CustomerPartyType { Party = new PartyType { PartyName = new PartyNameType[] { new PartyNameType { Name = "The Terminus" } }, PostalAddress = new AddressType { StreetName = "Avon Way", BuildingName = "Thereabouts", BuildingNumber = "56A", CityName = "Bridgtow", PostalZone = "ZZ99 1ZZ", CountrySubentity = "Avon", AddressLine = new AddressLineType[] { new AddressLineType { Line = "3rd Floor, Room 5" } }, Country = new CountryType { IdentificationCode = "GB" } }, PartyTaxScheme = new PartyTaxSchemeType[] { new PartyTaxSchemeType { RegistrationName = "Bridgtow District Council", CompanyID = "12356478", ExemptionReason = new TextType[] { new TextType { Value = "Local Authority" } }, TaxScheme = new TaxSchemeType { ID = "UK VAT", TaxTypeCode = "VAT" } } }, Contact = new ContactType { Name = "S Massiah", Telephone = "0127 98876545", Telefax = "0127 98876546", ElectronicMail = "[email protected]" } } }, Delivery = new DeliveryType[] { new DeliveryType { DeliveryAddress = new AddressType { StreetName = "Avon Way", BuildingName = "Thereabouts", BuildingNumber = "56A", CityName = "Bridgtow", PostalZone = "ZZ99 1ZZ", CountrySubentity = "Avon", AddressLine = new AddressLineType[] { new AddressLineType { Line = "3rd Floor, Room 5" } }, Country = new CountryType { IdentificationCode = "GB" } }, RequestedDeliveryPeriod = new PeriodType { StartDate = "2005-06-29", StartTime = "09:30:47.0Z", EndDate = "2005-06-29", EndTime = "09:30:47.0Z" } } }, DeliveryTerms = new DeliveryTermsType[] { new DeliveryTermsType { SpecialTerms = new TextType[] { new TextType { Value = "1% deduction for late delivery as per contract" } } } }, TransactionConditions = new TransactionConditionsType { Description = new TextType[] { new TextType { Value = "order response required; payment is by BACS or by cheque" } } }, AnticipatedMonetaryTotal = new MonetaryTotalType { LineExtensionAmount = new AmountType { currencyID = "GBP", Value = 100.00M }, PayableAmount = new AmountType { currencyID = "GBP", Value = 100.00M } }, OrderLine = new OrderLineType[] { new OrderLineType { Note = new TextType[] { new TextType { Value = "this is an illustrative order line" } }, LineItem = new LineItemType { ID = "1", SalesOrderID = "A", LineStatusCode = "NoStatus", Quantity = new QuantityType { unitCode = "KGM", Value = 100M }, LineExtensionAmount = new AmountType { currencyID = "GBP", Value = 100.00M }, TotalTaxAmount = new AmountType { currencyID = "GBP", Value = 17.50M }, Price = new PriceType { PriceAmount = new AmountType { currencyID = "GBP", Value = 100.00M }, BaseQuantity = new QuantityType { unitCode = "KGM", Value = 1M } }, Item = new ItemType { Description = new TextType[] { new TextType { Value = "Acme beeswax" } }, Name = "beeswax", BuyersItemIdentification = new ItemIdentificationType { ID = "6578489" }, SellersItemIdentification = new ItemIdentificationType { ID = "17589683" } } } } } }; doc.Xmlns = new System.Xml.Serialization.XmlSerializerNamespaces(new[] { new XmlQualifiedName("cbc","urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"), new XmlQualifiedName("cac","urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"), }); return doc; } } }
using System.Collections.Generic; using Eto.Drawing; using System; using System.Linq; namespace Eto.Forms { /// <summary> /// Represents a display on the system. /// </summary> [Handler(typeof(Screen.IHandler))] public class Screen : Widget { new IHandler Handler { get { return (IHandler)base.Handler; } } /// <summary> /// Initializes a new instance of the <see cref="Eto.Forms.Screen"/> class. /// </summary> public Screen() { } /// <summary> /// Initializes a new instance of the <see cref="Eto.Forms.Screen"/> class with the specified <paramref name="handler"/>. /// </summary> /// <remarks> /// Used by platform implementations to create instances of a screen with a particular handler. /// </remarks> /// <param name="handler">Handler for the screen.</param> public Screen(IHandler handler) : base(handler) { } /// <summary> /// Gets an enumerable of display screens available on the current system. /// </summary> /// <value>The screens of the current system.</value> public static IEnumerable<Screen> Screens { get { var handler = Platform.Instance.CreateShared<IScreensHandler>(); return handler.Screens; } } /// <summary> /// Gets the display bounds of all screens on the current system. /// </summary> /// <value>The display bounds of all screens.</value> public static RectangleF DisplayBounds { get { var handler = Platform.Instance.CreateShared<IScreensHandler>(); var bounds = RectangleF.Empty; foreach (var screen in handler.Screens) { bounds.Union(screen.Bounds); } return bounds; } } /// <summary> /// Gets the primary screen of the current system. /// </summary> /// <remarks> /// This is typically the user's main screen. /// </remarks> /// <value>The primary screen.</value> public static Screen PrimaryScreen { get { var handler = Platform.Instance.CreateShared<IScreensHandler>(); return handler.PrimaryScreen; } } /// <summary> /// Gets the logical Dots/Pixels Per Inch of the screen. /// </summary> /// <value>The Dots Per Inch</value> public float DPI { get { return Handler.Scale * 72f; } } /// <summary> /// Gets the logical scale of the pixels of the screen vs. points. /// </summary> /// <remarks> /// The scale can be used to translate points to pixels. E.g. /// <code> /// var pixels = points * screen.Scale; /// </code> /// This is useful when creating fonts that need to be a certain pixel size. /// /// Since this is a logical scale, this will give you the 'recommended' pixel size that will appear to be the same /// physical size, even on retina displays. /// </remarks> /// <value>The logical scale of pixels per point.</value> public float Scale { get { return Handler.Scale; } } /// <summary> /// Gets the real Dots/Pixels Per Inch of the screen, accounting for retina displays. /// </summary> /// <remarks> /// This is similar to <see cref="DPI"/>, however will give you the 'real' DPI of the screen. /// For example, a Retina display on OS X will have the RealDPI twice the DPI reported. /// </remarks> /// <value>The real DP.</value> public float RealDPI { get { return Handler.RealScale * 72f; } } /// <summary> /// Gets the real scale of the pixels of the screen vs. points. /// </summary> /// <remarks> /// The scale can be used to translate points to 'real' pixels. E.g. /// <code> /// var pixels = points * screen.Scale; /// </code> /// This is useful when creating fonts that need to be a certain pixel size. /// /// Since this is a real scale, this will give you the actual pixel size. /// This means on retina displays on OS X will appear to be half the physical size as regular displays. /// </remarks> /// <value>The real scale of pixels per point.</value> public float RealScale { get { return Handler.RealScale; } } /// <summary> /// Gets the bounds of the display in the <see cref="DisplayBounds"/> area. /// </summary> /// <remarks> /// The primary screen's upper left corner is always located at 0,0. /// A negative X/Y indicates that the screen location is to the left or top of the primary screen. /// A positive X/Y indicates that the screen location is to the right or bottom of the primary screen. /// </remarks> /// <value>The display's bounds.</value> public RectangleF Bounds { get { return Handler.Bounds; } } /// <summary> /// Gets the working area of the display, excluding any menu/task bars, docks, etc. /// </summary> /// <remarks> /// This is useful to position your window in the usable area of the screen. /// </remarks> /// <value>The working area of the screen.</value> public RectangleF WorkingArea { get { return Handler.WorkingArea; } } /// <summary> /// Gets the number of bits each pixel uses to represent its color value. /// </summary> /// <value>The screen's bits per pixel.</value> public int BitsPerPixel { get { return Handler.BitsPerPixel; } } /// <summary> /// Gets a value indicating whether this screen is the primary/main screen. /// </summary> /// <value><c>true</c> if this is the primary screen; otherwise, <c>false</c>.</value> public bool IsPrimary { get { return Handler.IsPrimary; } } /// <summary> /// Handler interface for the <see cref="Screen"/>. /// </summary> public new interface IHandler : Widget.IHandler { /// <summary> /// Gets the logical scale of the pixels of the screen vs. points. /// </summary> /// <remarks> /// This scale should be based on a standard 72dpi screen. /// </remarks> /// <value>The logical scale of pixels per point.</value> float Scale { get; } /// <summary> /// Gets the real scale of the pixels of the screen vs. points. /// </summary> /// <remarks> /// This should be based on a standard 72dpi screen, and is useful for retina displays when the real DPI /// is double the logical DPI. E.g. 1440x900 logical screen size is actually 2880x1800 pixels. /// </remarks> /// <value>The real scale of pixels per point.</value> float RealScale { get; } /// <summary> /// Gets the number of bits each pixel uses to represent its color value. /// </summary> /// <value>The screen's bits per pixel.</value> int BitsPerPixel { get; } /// <summary> /// Gets the bounds of the display. /// </summary> /// <remarks> /// The primary screen's upper left corner is always located at 0,0. /// A negative X/Y indicates that the screen location is to the left or top of the primary screen. /// A positive X/Y indicates that the screen location is to the right or bottom of the primary screen. /// </remarks> /// <value>The display's bounds.</value> RectangleF Bounds { get; } /// <summary> /// Gets the working area of the display, excluding any menu/task bars, docks, etc. /// </summary> /// <remarks> /// This is useful to position your window in the usable area of the screen. /// </remarks> /// <value>The working area of the screen.</value> RectangleF WorkingArea { get; } /// <summary> /// Gets a value indicating whether this screen is the primary/main screen. /// </summary> /// <value><c>true</c> if this is the primary screen; otherwise, <c>false</c>.</value> bool IsPrimary { get; } } /// <summary> /// Handler interface for static methods of the <see cref="Screen"/>. /// </summary> public interface IScreensHandler { /// <summary> /// Gets an enumerable of display screens available on the current system. /// </summary> /// <value>The screens of the current system.</value> IEnumerable<Screen> Screens { get; } /// <summary> /// Gets the primary screen of the current system. /// </summary> /// <remarks> /// This is typically the user's main screen. /// </remarks> /// <value>The primary screen.</value> Screen PrimaryScreen { get; } } /// <summary> /// Gets the screen that contains the specified <paramref name="point"/>, /// or the closest screen to the point if it is outside the bounds of all screens. /// </summary> /// <returns>The screen encompassing or closest the specified point.</returns> /// <param name="point">Point to find the screen.</param> public static Screen FromPoint(PointF point) { var screens = Screens.ToArray(); foreach (var screen in screens) { if (screen.Bounds.Contains(point)) return screen; } Screen foundScreen = null; float foundDistance = float.MaxValue; foreach (var screen in screens) { var diff = RectangleF.Distance(screen.Bounds, point); var distance = (float)Math.Sqrt(diff.Width * diff.Width + diff.Height * diff.Height); if (distance < foundDistance) { foundScreen = screen; foundDistance = distance; } } return foundScreen ?? PrimaryScreen; } /// <summary> /// Gets the screen that encompases the biggest part of the specified <paramref name="rectangle"/>, /// or the closest screen to the rectangle if it is outside the bounds of all screens.. /// </summary> /// <returns>The screen encompassing or closest to the specified rectangle.</returns> /// <param name="rectangle">Rectangle to find the screen.</param> public static Screen FromRectangle(RectangleF rectangle) { Screen foundScreen = null; float foundArea = 0; var screens = Screens.ToArray(); foreach (var screen in screens) { var rect = rectangle; rect.Intersect(screen.Bounds); var area = rect.Size.Width * rect.Size.Height; if (area > foundArea) { foundScreen = screen; foundArea = area; } } if (foundScreen != null) return foundScreen; // find by distance float foundDistance = float.MaxValue; foreach (var screen in screens) { var diff = RectangleF.Distance(rectangle, screen.Bounds); var distance = (float)Math.Sqrt(diff.Width * diff.Width + diff.Height * diff.Height); if (distance < foundDistance) { foundScreen = screen; foundDistance = distance; } } return foundScreen ?? PrimaryScreen; } } }
// /* // SharpNative - C# to D Transpiler // (C) 2014 Irio Systems // */ #region Imports using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using CSharpExtensions = Microsoft.CodeAnalysis.CSharpExtensions; #endregion namespace SharpNative.Compiler { internal static class WriteVariableDeclaration { public static void Go(OutputWriter writer, VariableDeclarationSyntax declaration) { foreach (var variable in declaration.Variables) { ISymbol symbol = TypeProcessor.GetDeclaredSymbol(variable); var isRef = false; //UsedAsRef(variable, symbol); writer.WriteIndent(); // writer.Write("var "); // if (isRef) //Not needed c++ can passby ref // { // // var typeStr = TypeProcessor.ConvertType(declaration.Declaration.Type); // // var localSymbol = symbol as ILocalSymbol; // var ptr = localSymbol != null && !localSymbol.Type.IsValueType?"*" : ""; // writer.Write("gc::gc_ptr < " + typeStr+ ptr + " >"); // writer.Write("" + typeStr + ptr + ""); // // writer.Write(" "); // writer.Write(WriteIdentifierName.TransformIdentifier(variable.Identifier.Text)); // // Program.RefOutSymbols.TryAdd(symbol, null); // // writer.Write(" = std::make_shared < "); // writer.Write(typeStr + ptr); // writer.Write(" >("); // // WriteInitializer(writer, declaration, variable); // // writer.Write(")"); // } // else { var lsymbol = symbol as ILocalSymbol; if (lsymbol != null && lsymbol.Type.IsValueType == false) { writer.Write(" "); // Ideally Escape analysis should take care of this, but for now all value types are on heap and ref types on stack } writer.Write(TypeProcessor.ConvertType(declaration.Type)); if (lsymbol != null && lsymbol.Type.IsValueType == false) writer.Write(" "); writer.Write(" "); writer.Write(WriteIdentifierName.TransformIdentifier(variable.Identifier.Text)); writer.Write(" = "); WriteInitializer(writer, declaration, variable); } writer.Write(";\r\n"); } } private static void ProcessInitializer(OutputWriter writer, VariableDeclarationSyntax declaration, VariableDeclaratorSyntax variable) { var initializer = variable.Initializer; if (initializer != null) { if (CSharpExtensions.CSharpKind(initializer.Value) == SyntaxKind.CollectionInitializerExpression) return; var value = initializer.Value; var initializerType = TypeProcessor.GetTypeInfo(value); var memberaccessexpression = value as MemberAccessExpressionSyntax; var nameexpression = value as NameSyntax; var nullAssignment = value.ToFullString().Trim() == "null"; var shouldBox = initializerType.Type != null && (initializerType.Type.IsValueType) && !initializerType.ConvertedType.IsValueType; var shouldUnBox = initializerType.Type != null && !initializerType.Type.IsValueType && initializerType.ConvertedType.IsValueType; var isname = value is NameSyntax; var ismemberexpression = value is MemberAccessExpressionSyntax || (isname && TypeProcessor.GetSymbolInfo(value as NameSyntax).Symbol.Kind == SymbolKind.Method); var isdelegateassignment = ismemberexpression && initializerType.ConvertedType.TypeKind == TypeKind.Delegate; var isstaticdelegate = isdelegateassignment && ((memberaccessexpression != null && TypeProcessor.GetSymbolInfo(memberaccessexpression).Symbol.IsStatic) || (isname && TypeProcessor.GetSymbolInfo(nameexpression).Symbol.IsStatic)); var shouldCast = initializerType.Type != initializerType.ConvertedType && initializerType.ConvertedType != null; if (nullAssignment) { if (initializerType.Type != null) //Nullable Support { if (initializerType.Type.Name == "Nullable") { var atype = TypeProcessor.ConvertType(initializerType.Type); writer.Write(atype + "()"); } } else writer.Write("null"); return; } if (shouldBox) { //Box writer.Write("BOX!(" + TypeProcessor.ConvertType(initializerType.Type) + ")("); //When passing an argument by ref or out, leave off the .Value suffix Core.Write(writer, value); writer.Write(")"); return; } if (shouldUnBox) { writer.Write("cast(" + TypeProcessor.ConvertType(initializerType.Type) + ")("); Core.Write(writer, value); writer.Write(")"); return; } if (initializer.Parent.Parent.Parent is FixedStatementSyntax) // Fixed is a bit special { //TODO write a better fix var type = TypeProcessor.GetTypeInfo(declaration.Type); writer.Write("cast(" + TypeProcessor.ConvertType(type.Type) + ")("); Core.Write(writer, value); writer.Write(")"); return; } if (isdelegateassignment) { var typeString = TypeProcessor.ConvertType(initializerType.ConvertedType); var createNew = !(value is ObjectCreationExpressionSyntax); if (createNew) { if (initializerType.ConvertedType.TypeKind == TypeKind.TypeParameter) writer.Write(" __TypeNew!(" + typeString + ")("); else writer.Write("new " + typeString + "("); } var isStatic = isstaticdelegate; // if (isStatic) // writer.Write("__ToDelegate("); MemberUtilities.WriteMethodPointer(writer, value); // if (isStatic) // writer.Write(")"); if (createNew) writer.Write(")"); return; } if (initializerType.Type == null && initializerType.ConvertedType == null) { writer.Write("null"); return; } Core.Write(writer, value); } else writer.Write(TypeProcessor.DefaultValue(declaration.Type)); } private static void WriteInitializer(OutputWriter writer, VariableDeclarationSyntax declaration, VariableDeclaratorSyntax variable) { ProcessInitializer(writer, declaration, variable); } /// <summary> /// Determines if the passed symbol is used in any ref or out clauses /// </summary> private static bool UsedAsRef(VariableDeclaratorSyntax variable, ISymbol symbol) { SyntaxNode node = variable; BlockSyntax scope; do scope = (node = node.Parent) as BlockSyntax; while (scope == null); return scope.DescendantNodes().OfType<InvocationExpressionSyntax>() .SelectMany(o => o.ArgumentList.Arguments) .Where(o => o.RefOrOutKeyword.RawKind != (decimal)SyntaxKind.None) .Any(o => TypeProcessor.GetSymbolInfo(o.Expression).Symbol == symbol); } } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// Defines an account billing plan response object. /// </summary> [DataContract] public partial class AccountBillingPlanResponse : IEquatable<AccountBillingPlanResponse>, IValidatableObject { public AccountBillingPlanResponse() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="AccountBillingPlanResponse" /> class. /// </summary> /// <param name="BillingAddress">BillingAddress.</param> /// <param name="BillingAddressIsCreditCardAddress">When set to **true**, the credit card address information is the same as that returned as the billing address. If false, then the billing address is considered a billing contact address, and the credit card address can be different..</param> /// <param name="BillingPlan">BillingPlan.</param> /// <param name="CreditCardInformation">CreditCardInformation.</param> /// <param name="DirectDebitProcessorInformation">DirectDebitProcessorInformation.</param> /// <param name="DowngradePlanInformation">DowngradePlanInformation.</param> /// <param name="DowngradeRequestInformation">DowngradeRequestInformation.</param> /// <param name="EntityInformation">EntityInformation.</param> /// <param name="PaymentMethod">PaymentMethod.</param> /// <param name="PaymentProcessorInformation">PaymentProcessorInformation.</param> /// <param name="ReferralInformation">ReferralInformation.</param> /// <param name="SuccessorPlans">SuccessorPlans.</param> /// <param name="TaxExemptId">TaxExemptId.</param> public AccountBillingPlanResponse(AccountAddress BillingAddress = default(AccountAddress), string BillingAddressIsCreditCardAddress = default(string), AccountBillingPlan BillingPlan = default(AccountBillingPlan), CreditCardInformation CreditCardInformation = default(CreditCardInformation), DirectDebitProcessorInformation DirectDebitProcessorInformation = default(DirectDebitProcessorInformation), DowngradePlanUpdateResponse DowngradePlanInformation = default(DowngradePlanUpdateResponse), DowngradeRequestInformation DowngradeRequestInformation = default(DowngradeRequestInformation), BillingEntityInformationResponse EntityInformation = default(BillingEntityInformationResponse), string PaymentMethod = default(string), PaymentProcessorInformation PaymentProcessorInformation = default(PaymentProcessorInformation), ReferralInformation ReferralInformation = default(ReferralInformation), List<BillingPlan> SuccessorPlans = default(List<BillingPlan>), string TaxExemptId = default(string)) { this.BillingAddress = BillingAddress; this.BillingAddressIsCreditCardAddress = BillingAddressIsCreditCardAddress; this.BillingPlan = BillingPlan; this.CreditCardInformation = CreditCardInformation; this.DirectDebitProcessorInformation = DirectDebitProcessorInformation; this.DowngradePlanInformation = DowngradePlanInformation; this.DowngradeRequestInformation = DowngradeRequestInformation; this.EntityInformation = EntityInformation; this.PaymentMethod = PaymentMethod; this.PaymentProcessorInformation = PaymentProcessorInformation; this.ReferralInformation = ReferralInformation; this.SuccessorPlans = SuccessorPlans; this.TaxExemptId = TaxExemptId; } /// <summary> /// Gets or Sets BillingAddress /// </summary> [DataMember(Name="billingAddress", EmitDefaultValue=false)] public AccountAddress BillingAddress { get; set; } /// <summary> /// When set to **true**, the credit card address information is the same as that returned as the billing address. If false, then the billing address is considered a billing contact address, and the credit card address can be different. /// </summary> /// <value>When set to **true**, the credit card address information is the same as that returned as the billing address. If false, then the billing address is considered a billing contact address, and the credit card address can be different.</value> [DataMember(Name="billingAddressIsCreditCardAddress", EmitDefaultValue=false)] public string BillingAddressIsCreditCardAddress { get; set; } /// <summary> /// Gets or Sets BillingPlan /// </summary> [DataMember(Name="billingPlan", EmitDefaultValue=false)] public AccountBillingPlan BillingPlan { get; set; } /// <summary> /// Gets or Sets CreditCardInformation /// </summary> [DataMember(Name="creditCardInformation", EmitDefaultValue=false)] public CreditCardInformation CreditCardInformation { get; set; } /// <summary> /// Gets or Sets DirectDebitProcessorInformation /// </summary> [DataMember(Name="directDebitProcessorInformation", EmitDefaultValue=false)] public DirectDebitProcessorInformation DirectDebitProcessorInformation { get; set; } /// <summary> /// Gets or Sets DowngradePlanInformation /// </summary> [DataMember(Name="downgradePlanInformation", EmitDefaultValue=false)] public DowngradePlanUpdateResponse DowngradePlanInformation { get; set; } /// <summary> /// Gets or Sets DowngradeRequestInformation /// </summary> [DataMember(Name="downgradeRequestInformation", EmitDefaultValue=false)] public DowngradeRequestInformation DowngradeRequestInformation { get; set; } /// <summary> /// Gets or Sets EntityInformation /// </summary> [DataMember(Name="entityInformation", EmitDefaultValue=false)] public BillingEntityInformationResponse EntityInformation { get; set; } /// <summary> /// Gets or Sets PaymentMethod /// </summary> [DataMember(Name="paymentMethod", EmitDefaultValue=false)] public string PaymentMethod { get; set; } /// <summary> /// Gets or Sets PaymentProcessorInformation /// </summary> [DataMember(Name="paymentProcessorInformation", EmitDefaultValue=false)] public PaymentProcessorInformation PaymentProcessorInformation { get; set; } /// <summary> /// Gets or Sets ReferralInformation /// </summary> [DataMember(Name="referralInformation", EmitDefaultValue=false)] public ReferralInformation ReferralInformation { get; set; } /// <summary> /// Gets or Sets SuccessorPlans /// </summary> [DataMember(Name="successorPlans", EmitDefaultValue=false)] public List<BillingPlan> SuccessorPlans { get; set; } /// <summary> /// Gets or Sets TaxExemptId /// </summary> [DataMember(Name="taxExemptId", EmitDefaultValue=false)] public string TaxExemptId { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class AccountBillingPlanResponse {\n"); sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); sb.Append(" BillingAddressIsCreditCardAddress: ").Append(BillingAddressIsCreditCardAddress).Append("\n"); sb.Append(" BillingPlan: ").Append(BillingPlan).Append("\n"); sb.Append(" CreditCardInformation: ").Append(CreditCardInformation).Append("\n"); sb.Append(" DirectDebitProcessorInformation: ").Append(DirectDebitProcessorInformation).Append("\n"); sb.Append(" DowngradePlanInformation: ").Append(DowngradePlanInformation).Append("\n"); sb.Append(" DowngradeRequestInformation: ").Append(DowngradeRequestInformation).Append("\n"); sb.Append(" EntityInformation: ").Append(EntityInformation).Append("\n"); sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); sb.Append(" PaymentProcessorInformation: ").Append(PaymentProcessorInformation).Append("\n"); sb.Append(" ReferralInformation: ").Append(ReferralInformation).Append("\n"); sb.Append(" SuccessorPlans: ").Append(SuccessorPlans).Append("\n"); sb.Append(" TaxExemptId: ").Append(TaxExemptId).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as AccountBillingPlanResponse); } /// <summary> /// Returns true if AccountBillingPlanResponse instances are equal /// </summary> /// <param name="other">Instance of AccountBillingPlanResponse to be compared</param> /// <returns>Boolean</returns> public bool Equals(AccountBillingPlanResponse other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.BillingAddress == other.BillingAddress || this.BillingAddress != null && this.BillingAddress.Equals(other.BillingAddress) ) && ( this.BillingAddressIsCreditCardAddress == other.BillingAddressIsCreditCardAddress || this.BillingAddressIsCreditCardAddress != null && this.BillingAddressIsCreditCardAddress.Equals(other.BillingAddressIsCreditCardAddress) ) && ( this.BillingPlan == other.BillingPlan || this.BillingPlan != null && this.BillingPlan.Equals(other.BillingPlan) ) && ( this.CreditCardInformation == other.CreditCardInformation || this.CreditCardInformation != null && this.CreditCardInformation.Equals(other.CreditCardInformation) ) && ( this.DirectDebitProcessorInformation == other.DirectDebitProcessorInformation || this.DirectDebitProcessorInformation != null && this.DirectDebitProcessorInformation.Equals(other.DirectDebitProcessorInformation) ) && ( this.DowngradePlanInformation == other.DowngradePlanInformation || this.DowngradePlanInformation != null && this.DowngradePlanInformation.Equals(other.DowngradePlanInformation) ) && ( this.DowngradeRequestInformation == other.DowngradeRequestInformation || this.DowngradeRequestInformation != null && this.DowngradeRequestInformation.Equals(other.DowngradeRequestInformation) ) && ( this.EntityInformation == other.EntityInformation || this.EntityInformation != null && this.EntityInformation.Equals(other.EntityInformation) ) && ( this.PaymentMethod == other.PaymentMethod || this.PaymentMethod != null && this.PaymentMethod.Equals(other.PaymentMethod) ) && ( this.PaymentProcessorInformation == other.PaymentProcessorInformation || this.PaymentProcessorInformation != null && this.PaymentProcessorInformation.Equals(other.PaymentProcessorInformation) ) && ( this.ReferralInformation == other.ReferralInformation || this.ReferralInformation != null && this.ReferralInformation.Equals(other.ReferralInformation) ) && ( this.SuccessorPlans == other.SuccessorPlans || this.SuccessorPlans != null && this.SuccessorPlans.SequenceEqual(other.SuccessorPlans) ) && ( this.TaxExemptId == other.TaxExemptId || this.TaxExemptId != null && this.TaxExemptId.Equals(other.TaxExemptId) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.BillingAddress != null) hash = hash * 59 + this.BillingAddress.GetHashCode(); if (this.BillingAddressIsCreditCardAddress != null) hash = hash * 59 + this.BillingAddressIsCreditCardAddress.GetHashCode(); if (this.BillingPlan != null) hash = hash * 59 + this.BillingPlan.GetHashCode(); if (this.CreditCardInformation != null) hash = hash * 59 + this.CreditCardInformation.GetHashCode(); if (this.DirectDebitProcessorInformation != null) hash = hash * 59 + this.DirectDebitProcessorInformation.GetHashCode(); if (this.DowngradePlanInformation != null) hash = hash * 59 + this.DowngradePlanInformation.GetHashCode(); if (this.DowngradeRequestInformation != null) hash = hash * 59 + this.DowngradeRequestInformation.GetHashCode(); if (this.EntityInformation != null) hash = hash * 59 + this.EntityInformation.GetHashCode(); if (this.PaymentMethod != null) hash = hash * 59 + this.PaymentMethod.GetHashCode(); if (this.PaymentProcessorInformation != null) hash = hash * 59 + this.PaymentProcessorInformation.GetHashCode(); if (this.ReferralInformation != null) hash = hash * 59 + this.ReferralInformation.GetHashCode(); if (this.SuccessorPlans != null) hash = hash * 59 + this.SuccessorPlans.GetHashCode(); if (this.TaxExemptId != null) hash = hash * 59 + this.TaxExemptId.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Collections.Generic; using NUnit.Framework.Internal; using NUnit.TestUtilities.Collections; using NUnit.TestUtilities.Comparers; namespace NUnit.Framework.Constraints { public class CollectionEquivalentConstraintTests { [Test] public void EqualCollectionsAreEquivalent() { ICollection set1 = new SimpleObjectCollection("x", "y", "z"); ICollection set2 = new SimpleObjectCollection("x", "y", "z"); Assert.That(new CollectionEquivalentConstraint(set1).ApplyTo(set2).IsSuccess); } [Test] public void WorksWithCollectionsOfArrays() { byte[] array1 = new byte[] { 0x20, 0x44, 0x56, 0x76, 0x1e, 0xff }; byte[] array2 = new byte[] { 0x42, 0x52, 0x72, 0xef }; byte[] array3 = new byte[] { 0x20, 0x44, 0x56, 0x76, 0x1e, 0xff }; byte[] array4 = new byte[] { 0x42, 0x52, 0x72, 0xef }; ICollection set1 = new SimpleObjectCollection(array1, array2); ICollection set2 = new SimpleObjectCollection(array3, array4); Constraint constraint = new CollectionEquivalentConstraint(set1); Assert.That(constraint.ApplyTo(set2).IsSuccess); set2 = new SimpleObjectCollection(array4, array3); Assert.That(constraint.ApplyTo(set2).IsSuccess); } [Test] public void EquivalentIgnoresOrder() { ICollection set1 = new SimpleObjectCollection("x", "y", "z"); ICollection set2 = new SimpleObjectCollection("z", "y", "x"); Assert.That(new CollectionEquivalentConstraint(set1).ApplyTo(set2).IsSuccess); } [Test] public void EquivalentFailsWithDuplicateElementInActual() { ICollection set1 = new SimpleObjectCollection("x", "y", "z"); ICollection set2 = new SimpleObjectCollection("x", "y", "x"); Assert.False(new CollectionEquivalentConstraint(set1).ApplyTo(set2).IsSuccess); } [Test] public void EquivalentFailsWithDuplicateElementInExpected() { ICollection set1 = new SimpleObjectCollection("x", "y", "x"); ICollection set2 = new SimpleObjectCollection("x", "y", "z"); Assert.False(new CollectionEquivalentConstraint(set1).ApplyTo(set2).IsSuccess); } [Test] public void EquivalentFailsWithExtraItemsInActual() { ICollection set1 = new SimpleObjectCollection("x", "y"); ICollection set2 = new SimpleObjectCollection("x", "x", "y"); Assert.False(new CollectionEquivalentConstraint(set1).ApplyTo(set2).IsSuccess); } [Test] public void EquivalentHandlesNull() { ICollection set1 = new SimpleObjectCollection(null, "x", null, "z"); ICollection set2 = new SimpleObjectCollection("z", null, "x", null); Assert.That(new CollectionEquivalentConstraint(set1).ApplyTo(set2).IsSuccess); } [Test] public void EquivalentHonorsIgnoreCase() { ICollection set1 = new SimpleObjectCollection("x", "y", "z"); ICollection set2 = new SimpleObjectCollection("z", "Y", "X"); Assert.That(new CollectionEquivalentConstraint(set1).IgnoreCase.ApplyTo(set2).IsSuccess); } [Test] [TestCaseSource(typeof(IgnoreCaseDataProvider), "TestCases")] public void HonorsIgnoreCase( IEnumerable expected, IEnumerable actual ) { var constraint = new CollectionEquivalentConstraint( expected ).IgnoreCase; var constraintResult = constraint.ApplyTo( actual ); if ( !constraintResult.IsSuccess ) { MessageWriter writer = new TextMessageWriter(); constraintResult.WriteMessageTo( writer ); Assert.Fail( writer.ToString() ); } } public class IgnoreCaseDataProvider { public static IEnumerable TestCases { get { yield return new TestCaseData(new SimpleObjectCollection("x", "y", "z"), new SimpleObjectCollection("z", "Y", "X")); yield return new TestCaseData(new[] {'A', 'B', 'C'}, new object[] {'a', 'c', 'b'}); yield return new TestCaseData(new[] {"a", "b", "c"}, new object[] {"A", "C", "B"}); yield return new TestCaseData(new Dictionary<int, string> {{2, "b"}, {1, "a"}}, new Dictionary<int, string> {{1, "A"}, {2, "b"}}); yield return new TestCaseData(new Dictionary<int, char> {{1, 'A'}}, new Dictionary<int, char> {{1, 'a'}}); yield return new TestCaseData(new Dictionary<string, int> {{ "b", 2 }, { "a", 1 } }, new Dictionary<string, int> {{"A", 1}, {"b", 2}}); yield return new TestCaseData(new Dictionary<char, int> {{'A', 1 }}, new Dictionary<char, int> {{'a', 1}}); #if !NETCOREAPP1_1 yield return new TestCaseData(new Hashtable {{1, "a"}, {2, "b"}}, new Hashtable {{1, "A"},{2, "B"}}); yield return new TestCaseData(new Hashtable {{1, 'A'}, {2, 'B'}}, new Hashtable {{1, 'a'},{2, 'b'}}); yield return new TestCaseData(new Hashtable {{"b", 2}, {"a", 1}}, new Hashtable {{"A", 1}, {"b", 2}}); yield return new TestCaseData(new Hashtable {{'A', 1}}, new Hashtable {{'a', 1}}); #endif } } } [Test] public void EquivalentHonorsUsing() { ICollection set1 = new SimpleObjectCollection("x", "y", "z"); ICollection set2 = new SimpleObjectCollection("z", "Y", "X"); Assert.That(new CollectionEquivalentConstraint(set1) .Using<string>((x, y) => StringUtil.Compare(x, y, true)) .ApplyTo(set2).IsSuccess); } [Test] public void EquivalentHonorsUsingWhenCollectionsAreOfDifferentTypes() { ICollection strings = new SimpleObjectCollection("1", "2", "3"); ICollection ints = new SimpleObjectCollection(1, 2, 3); Assert.That(ints, Is.EquivalentTo(strings).Using<int, string>((i, s) => i.ToString() == s)); } #if !(NET20 || NET35) [Test] public static void UsesProvidedGenericEqualityComparison() { var comparer = new GenericEqualityComparison<int>(); Assert.That(new[] { 1 }, Is.EquivalentTo(new[] { 1 }).Using<int>(comparer.Delegate)); Assert.That(comparer.WasCalled, "Comparer was not called"); } [Test] public static void UsesBooleanReturningDelegateWithImplicitParameterTypes() { Assert.That(new[] { 1 }, Is.EquivalentTo(new[] { 1 }).Using<int>((x, y) => x.Equals(y))); } [Test] public void CheckCollectionEquivalentConstraintResultIsReturned() { IEnumerable<string> set1 = new List<string>() { "one" }; IEnumerable<string> set2 = new List<string>() { "two" }; Assert.IsInstanceOf(typeof(CollectionEquivalentConstraintResult), new CollectionEquivalentConstraint(set1).ApplyTo(set2)); } /// <summary> /// A singular point test to ensure that the <see cref="ConstraintResult"/> returned by /// <see cref="CollectionEquivalentConstraint"/> includes the feature of describing both /// extra and missing elements when the collections are not equivalent. /// </summary> /// <remarks> /// This is not intended to fully test the display of missing/extra elements, but to ensure /// that the functionality is actually there. /// </remarks> [Test] public void TestConstraintResultMessageDisplaysMissingAndExtraElements() { List<string> expectedCollection = new List<string>() { "one", "two" }; List<string> actualCollection = new List<string>() { "three", "one" }; ConstraintResult cr = new CollectionEquivalentConstraint(expectedCollection).ApplyTo(actualCollection); TextMessageWriter writer = new TextMessageWriter(); cr.WriteMessageTo(writer); string expectedMsg = " Expected: equivalent to < \"one\", \"two\" >" + Environment.NewLine + " But was: < \"three\", \"one\" >" + Environment.NewLine + " Missing (1): < \"two\" >" + Environment.NewLine + " Extra (1): < \"three\" >" + Environment.NewLine; Assert.AreEqual(expectedMsg, writer.ToString()); } [Test] public void WorksWithHashSets() { var hash1 = new HashSet<string>(new string[] { "presto", "abracadabra", "hocuspocus" }); var hash2 = new HashSet<string>(new string[] { "abracadabra", "presto", "hocuspocus" }); Assert.That(new CollectionEquivalentConstraint(hash1).ApplyTo(hash2).IsSuccess); } [Test] public void WorksWithHashSetAndArray() { var hash = new HashSet<string>(new string[] { "presto", "abracadabra", "hocuspocus" }); var array = new string[] { "abracadabra", "presto", "hocuspocus" }; var constraint = new CollectionEquivalentConstraint(hash); Assert.That(constraint.ApplyTo(array).IsSuccess); } [Test] public void WorksWithArrayAndHashSet() { var hash = new HashSet<string>(new string[] { "presto", "abracadabra", "hocuspocus" }); var array = new string[] { "abracadabra", "presto", "hocuspocus" }; var constraint = new CollectionEquivalentConstraint(array); Assert.That(constraint.ApplyTo(hash).IsSuccess); } [Test] public void FailureMessageWithHashSetAndArray() { var hash = new HashSet<string>(new string[] { "presto", "abracadabra", "hocuspocus" }); var array = new string[] { "abracadabra", "presto", "hocusfocus" }; var constraint = new CollectionEquivalentConstraint(hash); var constraintResult = constraint.ApplyTo(array); Assert.False(constraintResult.IsSuccess); TextMessageWriter writer = new TextMessageWriter(); constraintResult.WriteMessageTo(writer); var expectedMessage = " Expected: equivalent to < \"presto\", \"abracadabra\", \"hocuspocus\" >" + Environment.NewLine + " But was: < \"abracadabra\", \"presto\", \"hocusfocus\" >" + Environment.NewLine + " Missing (1): < \"hocuspocus\" >" + Environment.NewLine + " Extra (1): < \"hocusfocus\" >" + Environment.NewLine; Assert.That(writer.ToString(), Is.EqualTo(expectedMessage)); } #endif } }