context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.Utility; using Random = UnityEngine.Random; namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof (CharacterController))] [RequireComponent(typeof (AudioSource))] public class FirstPersonControllerMod : MonoBehaviour { public bool m_Block = false; [SerializeField] private bool m_IsWalking; [SerializeField] private float m_WalkSpeed; [SerializeField] private float m_RunSpeed; [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten; [SerializeField] private float m_JumpSpeed; [SerializeField] private float m_StickToGroundForce; [SerializeField] private float m_GravityMultiplier; [SerializeField] private MouseLook m_MouseLook; [SerializeField] private bool m_UseFovKick; [SerializeField] private FOVKick m_FovKick = new FOVKick(); [SerializeField] private bool m_UseHeadBob; [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob(); [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob(); [SerializeField] private float m_StepInterval; [SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from. [SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground. [SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground. private Camera m_Camera; private bool m_Jump; private float m_YRotation; private Vector2 m_Input; private Vector3 m_MoveDir = Vector3.zero; private CharacterController m_CharacterController; public CollisionFlags m_CollisionFlags; private bool m_PreviouslyGrounded; private Vector3 m_OriginalCameraPosition; private float m_StepCycle; private float m_NextStep; private bool m_Jumping; private AudioSource m_AudioSource; private Quaternion LookRotation; private Quaternion CharacterRotation; private Vector3 CameraPosition; // Use this for initialization private void Start() { m_CharacterController = GetComponent<CharacterController>(); m_Camera = Camera.main; m_OriginalCameraPosition = m_Camera.transform.localPosition; m_FovKick.Setup(m_Camera); m_HeadBob.Setup(m_Camera, m_StepInterval); m_StepCycle = 0f; m_NextStep = m_StepCycle/2f; m_Jumping = false; m_AudioSource = GetComponent<AudioSource>(); m_MouseLook.Init(transform , m_Camera.transform); CameraPosition = m_CharacterController.transform.localPosition; } // Update is called once per frame private void Update() { RotateView(); // the jump state needs to read here to make sure it is not missed if (!m_Jump) { m_Jump = CrossPlatformInputManager.GetButtonDown("Jump"); } if (!m_PreviouslyGrounded && m_CharacterController.isGrounded) { StartCoroutine(m_JumpBob.DoBobCycle()); PlayLandingSound(); m_MoveDir.y = 0f; m_Jumping = false; } if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded) { m_MoveDir.y = 0f; } m_PreviouslyGrounded = m_CharacterController.isGrounded; } private void PlayLandingSound() { m_AudioSource.clip = m_LandSound; m_AudioSource.Play(); m_NextStep = m_StepCycle + .5f; } private void FixedUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height/2f); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x*speed; m_MoveDir.z = desiredMove.z*speed; if (m_CharacterController.isGrounded) { if (m_Jump) { m_MoveDir.y = m_JumpSpeed; PlayJumpSound(); m_Jump = false; m_Jumping = true; } } else { m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime; } //dit is beweging, dus wat als ik dit niet wil doen? if (!m_Block) m_CollisionFlags = m_CharacterController.Move(m_MoveDir * Time.fixedDeltaTime); else CameraPosition += m_MoveDir * Time.fixedDeltaTime; ProgressStepCycle(speed); UpdateCameraPosition(speed); } private void PlayJumpSound() { m_AudioSource.clip = m_JumpSound; m_AudioSource.Play(); } private void ProgressStepCycle(float speed) { if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0)) { m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))* Time.fixedDeltaTime; } if (!(m_StepCycle > m_NextStep)) { return; } m_NextStep = m_StepCycle + m_StepInterval; PlayFootStepAudio(); } private void PlayFootStepAudio() { if (!m_CharacterController.isGrounded) { return; } // pick & play a random footstep sound from the array, // excluding sound at index 0 int n = Random.Range(1, m_FootstepSounds.Length); m_AudioSource.clip = m_FootstepSounds[n]; m_AudioSource.PlayOneShot(m_AudioSource.clip); // move picked sound to index 0 so it's not picked next time m_FootstepSounds[n] = m_FootstepSounds[0]; m_FootstepSounds[0] = m_AudioSource.clip; } public Vector3 GetCameraMoveDirection() { return CameraPosition; } public Quaternion GetCharacterRotation() { return CharacterRotation; } public Quaternion GetCameraRotation() { return LookRotation; } private void UpdateCameraPosition(float speed) { Vector3 newCameraPosition; if (!m_UseHeadBob) { return; } if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded) { m_Camera.transform.localPosition = m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude + (speed * (m_IsWalking ? 1f : m_RunstepLenghten))); newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset(); } else { newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset(); } m_Camera.transform.localPosition = newCameraPosition; } private void GetInput(out float speed) { // Read input float horizontal = CrossPlatformInputManager.GetAxis("Horizontal"); float vertical = CrossPlatformInputManager.GetAxis("Vertical"); bool waswalking = m_IsWalking; #if !MOBILE_INPUT // On standalone builds, walk/run speed is modified by a key press. // keep track of whether or not the character is walking or running m_IsWalking = !Input.GetKey(KeyCode.LeftShift); #endif // set the desired speed to be walking or running speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed; m_Input = new Vector2(horizontal, vertical); // normalize input if it exceeds 1 in combined length: if (m_Input.sqrMagnitude > 1) { m_Input.Normalize(); } // handle speed change to give an fov kick // only if the player is going to a run, is running and the fovkick is to be used if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0) { StopAllCoroutines(); StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown()); } } private void RotateView() { if (!m_Block) { m_MouseLook.LookRotation(transform, m_Camera.transform); LookRotation = m_Camera.transform.localRotation; CharacterRotation = transform.localRotation; } else { //dont set it but calc it Quaternion[] r = m_MouseLook.LookRotation(transform, m_Camera.transform, false); LookRotation = r[0]; CharacterRotation = r[1]; } } private void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; //dont move the rigidbody if the character is on top of it if (m_CollisionFlags == CollisionFlags.Below) { return; } if (body == null || body.isKinematic) { return; } body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse); } } }
#region WatiN Copyright (C) 2006-2007 Jeroen van Menen //Copyright 2006-2007 Jeroen van Menen // // 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 Copyright using System.Text.RegularExpressions; using mshtml; using System; using ItiN.Interfaces; namespace ItiN { /// <summary> /// Summary description for SubElements. /// </summary> public sealed class ElementsSupport { public const string FrameTagName = "FRAME"; public const string InputTagName = "INPUT"; public const string TableCellTagName = "TD"; /// <summary> /// Prevent creating an instance of this class (contains only static members) /// </summary> private ElementsSupport() { } public static Element Element(DomContainer ie, Attribute findBy, IElementCollection elements) { return new ElementsContainer(ie, new ElementFinder(null, findBy, elements)); } public static ElementCollection Elements(DomContainer ie, IElementCollection elements) { return new ElementCollection(ie, new ElementFinder(null, elements)); } public static Option Option(DomContainer ie, Attribute findBy, IElementCollection elements) { return new Option(ie, new ElementFinder(ItiN.Option.ElementTags, findBy, elements)); } public static OptionCollection Options(DomContainer ie, IElementCollection elements) { return new OptionCollection(ie, new ElementFinder(ItiN.Option.ElementTags, elements)); } public static SelectList SelectList(DomContainer ie, Attribute findBy, IElementCollection elements) { return new SelectList(ie, new ElementFinder(ItiN.SelectList.ElementTags, findBy, elements)); } public static SelectListCollection SelectLists(DomContainer ie, IElementCollection elements) { return new SelectListCollection(ie, new ElementFinder(ItiN.SelectList.ElementTags, elements)); } public static RadioButton RadioButton(DomContainer ie, Attribute findBy, IElementCollection elements) { return new RadioButton(ie, new ElementFinder(ItiN.RadioButton.ElementTags, findBy, elements)); } public static RadioButtonCollection RadioButtons(DomContainer ie, IElementCollection elements) { return new RadioButtonCollection(ie, new ElementFinder(ItiN.RadioButton.ElementTags, elements)); } public static CheckBox CheckBox(DomContainer ie, Attribute findBy, IElementCollection elements) { return new CheckBox(ie, new ElementFinder(ItiN.CheckBox.ElementTags, findBy, elements)); } public static CheckBoxCollection CheckBoxes(DomContainer ie, IElementCollection elements) { return new CheckBoxCollection(ie, new ElementFinder(ItiN.CheckBox.ElementTags, elements)); } public static TextField TextField(DomContainer ie, Attribute findBy, IElementCollection elements) { return new TextField(ie, new ElementFinder(ItiN.TextField.ElementTags, findBy, elements)); } public static TextFieldCollection TextFields(DomContainer ie, IElementCollection elements) { return new TextFieldCollection(ie, new ElementFinder(ItiN.TextField.ElementTags, elements)); } public static Span Span(DomContainer ie, Attribute findBy, IElementCollection elements) { return new Span(ie, new ElementFinder(ItiN.Span.ElementTags, findBy, elements)); } public static SpanCollection Spans(DomContainer ie, IElementCollection elements) { return new SpanCollection(ie, new ElementFinder(ItiN.Span.ElementTags, elements)); } public static Div Div(DomContainer ie, Attribute findBy, IElementCollection elements) { return new Div(ie, new ElementFinder(ItiN.Div.ElementTags, findBy, elements)); } public static DivCollection Divs(DomContainer ie, IElementCollection elements) { return new DivCollection(ie, new ElementFinder(ItiN.Div.ElementTags, elements)); } //public static FileUpload FileUpload(DomContainer ie, Attribute findBy, IElementCollection elements) //{ // return new FileUpload(ie, new ElementFinder(Core.FileUpload.ElementTags, findBy, elements)); //} //public static FileUploadCollection FileUploads(DomContainer ie, IElementCollection elements) //{ // return new FileUploadCollection(ie, new ElementFinder(Core.FileUpload.ElementTags, elements)); //} //public static Form Form(DomContainer ie, Attribute findBy, IElementCollection elements) //{ // return new Form(ie, new ElementFinder(Core.Form.ElementTags, findBy, elements)); //} //public static FormCollection Forms(DomContainer ie, IElementCollection elements) //{ // return new FormCollection(ie, new ElementFinder(Core.Form.ElementTags, elements)); //} //public static Label Label(DomContainer ie, Attribute findBy, IElementCollection elements) //{ // return new Label(ie, new ElementFinder(Core.Label.ElementTags, findBy, elements)); //} //public static LabelCollection Labels(DomContainer ie, IElementCollection elements) //{ // return new LabelCollection(ie, new ElementFinder(Core.Label.ElementTags, elements)); //} //public static Link Link(DomContainer ie, Attribute findBy, IElementCollection elements) //{ // return new Link(ie, new ElementFinder(Core.Link.ElementTags, findBy, elements)); //} //public static LinkCollection Links(DomContainer ie, IElementCollection elements) //{ // return new LinkCollection(ie, new ElementFinder(Core.Link.ElementTags, elements)); //} //public static Para Para(DomContainer ie, Attribute findBy, IElementCollection elements) //{ // return new Para(ie, new ElementFinder(Core.Para.ElementTags, findBy, elements)); //} //public static ParaCollection Paras(DomContainer ie, IElementCollection elements) //{ // return new ParaCollection(ie, new ElementFinder(Core.Para.ElementTags, elements)); //} //public static Table Table(DomContainer ie, Attribute findBy, IElementCollection elements) //{ // return new Table(ie, new ElementFinder(Core.Table.ElementTags, findBy, elements)); //} //public static TableCollection Tables(DomContainer ie, IElementCollection elements) //{ // return new TableCollection(ie, new ElementFinder(Core.Table.ElementTags, elements)); //} //// public static TableSectionCollection TableSections(IDomContainer ie, IElementCollection elements) //// { //// return new TableSectionCollection(ie, elements); //// } //public static TableCell TableCell(DomContainer ie, Attribute findBy, IElementCollection elements) //{ // return new TableCell(ie, new ElementFinder(Core.TableCell.ElementTags, findBy, elements)); //} //public static TableCell TableCell(DomContainer ie, string elementId, int index, IElementCollection elements) //{ // return new TableCell(ie, new ElementFinder(Core.TableCell.ElementTags, new Index(index).And(new Id(elementId)), elements)); //} //public static TableCell TableCell(DomContainer ie, Regex elementId, int index, IElementCollection elements) //{ // return new TableCell(ie, new ElementFinder(Core.TableCell.ElementTags, new Index(index).And(new Id(elementId)), elements)); //} //public static TableCellCollection TableCells(DomContainer ie, IElementCollection elements) //{ // return new TableCellCollection(ie, new ElementFinder(Core.TableCell.ElementTags, elements)); //} //public static TableRow TableRow(DomContainer ie, Attribute findBy, IElementCollection elements) //{ // return new TableRow(ie, new ElementFinder(Core.TableRow.ElementTags, findBy, elements)); //} //public static TableRowCollection TableRows(DomContainer ie, IElementCollection elements) //{ // return new TableRowCollection(ie, new ElementFinder(Core.TableRow.ElementTags, elements)); //} //public static TableBody TableBody(DomContainer ie, Attribute findBy, IElementCollection elements) //{ // return new TableBody(ie, new ElementFinder(Core.TableBody.ElementTags, findBy, elements)); //} //public static TableBodyCollection TableBodies(DomContainer ie, IElementCollection elements) //{ // return new TableBodyCollection(ie, new ElementFinder(Core.TableBody.ElementTags, elements)); //} //public static Image Image(DomContainer ie, Attribute findBy, IElementCollection elements) //{ // return new Image(ie, new ElementFinder(Core.Image.ElementTags, findBy, elements)); //} //public static ImageCollection Images(DomContainer ie, IElementCollection elements) //{ // return new ImageCollection(ie, new ElementFinder(Core.Image.ElementTags, elements)); //} } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using Internal.Cryptography; using Internal.NativeCrypto; using Microsoft.Win32.SafeHandles; using static Internal.NativeCrypto.CapiHelper; namespace System.Security.Cryptography { public sealed partial class RSACryptoServiceProvider : RSA, ICspAsymmetricAlgorithm { private int _keySize; private readonly CspParameters _parameters; private readonly bool _randomKeyContainer; private SafeKeyHandle _safeKeyHandle; private SafeProvHandle _safeProvHandle; private static volatile CspProviderFlags s_useMachineKeyStore = 0; private bool _disposed; public RSACryptoServiceProvider() : this(0, new CspParameters(CapiHelper.DefaultRsaProviderType, null, null, s_useMachineKeyStore), true) { } public RSACryptoServiceProvider(int dwKeySize) : this(dwKeySize, new CspParameters(CapiHelper.DefaultRsaProviderType, null, null, s_useMachineKeyStore), false) { } public RSACryptoServiceProvider(int dwKeySize, CspParameters parameters) : this(dwKeySize, parameters, false) { } public RSACryptoServiceProvider(CspParameters parameters) : this(0, parameters, true) { } private RSACryptoServiceProvider(int keySize, CspParameters parameters, bool useDefaultKeySize) { if (keySize < 0) { throw new ArgumentOutOfRangeException("dwKeySize", "ArgumentOutOfRange_NeedNonNegNum"); } _parameters = CapiHelper.SaveCspParameters( CapiHelper.CspAlgorithmType.Rsa, parameters, s_useMachineKeyStore, out _randomKeyContainer); _keySize = useDefaultKeySize ? 1024 : keySize; // If this is not a random container we generate, create it eagerly // in the constructor so we can report any errors now. if (!_randomKeyContainer) { // Force-read the SafeKeyHandle property, which will summon it into existence. SafeKeyHandle localHandle = SafeKeyHandle; Debug.Assert(localHandle != null); } } private SafeProvHandle SafeProvHandle { get { if (_safeProvHandle == null) { lock (_parameters) { if (_safeProvHandle == null) { SafeProvHandle hProv = CapiHelper.CreateProvHandle(_parameters, _randomKeyContainer); Debug.Assert(hProv != null); Debug.Assert(!hProv.IsInvalid); Debug.Assert(!hProv.IsClosed); _safeProvHandle = hProv; } } return _safeProvHandle; } return _safeProvHandle; } set { lock (_parameters) { SafeProvHandle current = _safeProvHandle; if (ReferenceEquals(value, current)) { return; } if (current != null) { SafeKeyHandle keyHandle = _safeKeyHandle; _safeKeyHandle = null; keyHandle?.Dispose(); current.Dispose(); } _safeProvHandle = value; } } } private SafeKeyHandle SafeKeyHandle { get { if (_safeKeyHandle == null) { lock (_parameters) { if (_safeKeyHandle == null) { SafeKeyHandle hKey = CapiHelper.GetKeyPairHelper( CapiHelper.CspAlgorithmType.Rsa, _parameters, _keySize, SafeProvHandle); Debug.Assert(hKey != null); Debug.Assert(!hKey.IsInvalid); Debug.Assert(!hKey.IsClosed); _safeKeyHandle = hKey; } } } return _safeKeyHandle; } set { lock (_parameters) { SafeKeyHandle current = _safeKeyHandle; if (ReferenceEquals(value, current)) { return; } _safeKeyHandle = value; current?.Dispose(); } } } /// <summary> /// CspKeyContainerInfo property /// </summary> public CspKeyContainerInfo CspKeyContainerInfo { get { // Desktop compat: Read the SafeKeyHandle property to force the key to load, // because it might throw here. SafeKeyHandle localHandle = SafeKeyHandle; Debug.Assert(localHandle != null); return new CspKeyContainerInfo(_parameters, _randomKeyContainer); } } /// <summary> /// _keySize property /// </summary> public override int KeySize { get { byte[] keySize = CapiHelper.GetKeyParameter(SafeKeyHandle, Constants.CLR_KEYLEN); _keySize = (keySize[0] | (keySize[1] << 8) | (keySize[2] << 16) | (keySize[3] << 24)); return _keySize; } } public override KeySizes[] LegalKeySizes { get { return new[] { new KeySizes(384, 16384, 8) }; } } /// <summary> /// get set Persisted key in CSP /// </summary> public bool PersistKeyInCsp { get { return CapiHelper.GetPersistKeyInCsp(SafeProvHandle); } set { bool oldPersistKeyInCsp = this.PersistKeyInCsp; if (value == oldPersistKeyInCsp) { return; // Do nothing } CapiHelper.SetPersistKeyInCsp(SafeProvHandle, value); } } /// <summary> /// Gets the information of key if it is a public key /// </summary> public bool PublicOnly { get { byte[] publicKey = CapiHelper.GetKeyParameter(SafeKeyHandle, Constants.CLR_PUBLICKEYONLY); return (publicKey[0] == 1); } } /// <summary> /// MachineKey store properties /// </summary> public static bool UseMachineKeyStore { get { return (s_useMachineKeyStore == CspProviderFlags.UseMachineKeyStore); } set { s_useMachineKeyStore = (value ? CspProviderFlags.UseMachineKeyStore : 0); } } /// <summary> /// Decrypt raw data, generally used for decrypting symmetric key material /// </summary> /// <param name="rgb">encrypted data</param> /// <param name="fOAEP">true to use OAEP padding (PKCS #1 v2), false to use PKCS #1 type 2 padding</param> /// <returns>decrypted data</returns> public byte[] Decrypt(byte[] rgb, bool fOAEP) { if (rgb == null) { throw new ArgumentNullException(nameof(rgb)); } // Save the KeySize value to a local because it has non-trivial cost. int keySize = KeySize; // size check -- must be exactly the modulus size if (rgb.Length != (keySize / 8)) { throw new CryptographicException(SR.Cryptography_RSA_DecryptWrongSize); } byte[] decryptedKey; CapiHelper.DecryptKey(SafeKeyHandle, rgb, rgb.Length, fOAEP, out decryptedKey); return decryptedKey; } /// <summary> /// This method is not supported. Use Decrypt(byte[], RSAEncryptionPadding) instead. /// </summary> public override byte[] DecryptValue(byte[] rgb) => base.DecryptValue(rgb); /// <summary> /// Dispose the key handles /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed) { _safeKeyHandle.Dispose(); } if (_safeProvHandle != null && !_safeProvHandle.IsClosed) { _safeProvHandle.Dispose(); } _disposed = true; } } /// <summary> /// Encrypt raw data, generally used for encrypting symmetric key material. /// </summary> /// <remarks> /// This method can only encrypt (keySize - 88 bits) of data, so should not be used for encrypting /// arbitrary byte arrays. Instead, encrypt a symmetric key with this method, and use the symmetric /// key to encrypt the sensitive data. /// </remarks> /// <param name="rgb">raw data to encrypt</param> /// <param name="fOAEP">true to use OAEP padding (PKCS #1 v2), false to use PKCS #1 type 2 padding</param> /// <returns>Encrypted key</returns> public byte[] Encrypt(byte[] rgb, bool fOAEP) { if (rgb == null) { throw new ArgumentNullException(nameof(rgb)); } if (fOAEP) { int rsaSize = (KeySize + 7) / 8; const int OaepSha1Overhead = 20 + 20 + 2; // Normalize the Windows 7 and Windows 8.1+ exception if (rsaSize - OaepSha1Overhead < rgb.Length) { const int NTE_BAD_LENGTH = unchecked((int)0x80090004); throw NTE_BAD_LENGTH.ToCryptographicException(); } } byte[] encryptedKey = null; CapiHelper.EncryptKey(SafeKeyHandle, rgb, rgb.Length, fOAEP, ref encryptedKey); return encryptedKey; } /// <summary> /// This method is not supported. Use Encrypt(byte[], RSAEncryptionPadding) instead. /// </summary> public override byte[] EncryptValue(byte[] rgb) => base.EncryptValue(rgb); /// <summary> ///Exports a blob containing the key information associated with an RSACryptoServiceProvider object. /// </summary> public byte[] ExportCspBlob(bool includePrivateParameters) { return CapiHelper.ExportKeyBlob(includePrivateParameters, SafeKeyHandle); } /// <summary> /// Exports the RSAParameters /// </summary> public override RSAParameters ExportParameters(bool includePrivateParameters) { byte[] cspBlob = ExportCspBlob(includePrivateParameters); return cspBlob.ToRSAParameters(includePrivateParameters); } /// <summary> /// This method helps Acquire the default CSP and avoids the need for static SafeProvHandle /// in CapiHelper class /// </summary> private SafeProvHandle AcquireSafeProviderHandle() { SafeProvHandle safeProvHandle; CapiHelper.AcquireCsp(new CspParameters(CapiHelper.DefaultRsaProviderType), out safeProvHandle); return safeProvHandle; } /// <summary> /// Imports a blob that represents RSA key information /// </summary> /// <param name="keyBlob"></param> public void ImportCspBlob(byte[] keyBlob) { ThrowIfDisposed(); SafeKeyHandle safeKeyHandle; if (IsPublic(keyBlob)) { SafeProvHandle safeProvHandleTemp = AcquireSafeProviderHandle(); CapiHelper.ImportKeyBlob(safeProvHandleTemp, (CspProviderFlags)0, false, keyBlob, out safeKeyHandle); // The property set will take care of releasing any already-existing resources. SafeProvHandle = safeProvHandleTemp; } else { CapiHelper.ImportKeyBlob(SafeProvHandle, _parameters.Flags, false, keyBlob, out safeKeyHandle); } // The property set will take care of releasing any already-existing resources. SafeKeyHandle = safeKeyHandle; } /// <summary> /// Imports the specified RSAParameters /// </summary> public override void ImportParameters(RSAParameters parameters) { byte[] keyBlob = parameters.ToKeyBlob(); ImportCspBlob(keyBlob); } public override void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, ReadOnlySpan<byte> source, out int bytesRead) { ThrowIfDisposed(); base.ImportEncryptedPkcs8PrivateKey(passwordBytes, source, out bytesRead); } public override void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, ReadOnlySpan<byte> source, out int bytesRead) { ThrowIfDisposed(); base.ImportEncryptedPkcs8PrivateKey(password, source, out bytesRead); } /// <summary> /// Computes the hash value of a subset of the specified byte array using the /// specified hash algorithm, and signs the resulting hash value. /// </summary> /// <param name="buffer">The input data for which to compute the hash</param> /// <param name="offset">The offset into the array from which to begin using data</param> /// <param name="count">The number of bytes in the array to use as data. </param> /// <param name="halg">The hash algorithm to use to create the hash value. </param> /// <returns>The RSA signature for the specified data.</returns> public byte[] SignData(byte[] buffer, int offset, int count, object halg) { int calgHash = CapiHelper.ObjToHashAlgId(halg); HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg); byte[] hashVal = hash.ComputeHash(buffer, offset, count); return SignHash(hashVal, calgHash); } /// <summary> /// Computes the hash value of a subset of the specified byte array using the /// specified hash algorithm, and signs the resulting hash value. /// </summary> /// <param name="buffer">The input data for which to compute the hash</param> /// <param name="halg">The hash algorithm to use to create the hash value. </param> /// <returns>The RSA signature for the specified data.</returns> public byte[] SignData(byte[] buffer, object halg) { int calgHash = CapiHelper.ObjToHashAlgId(halg); HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg); byte[] hashVal = hash.ComputeHash(buffer); return SignHash(hashVal, calgHash); } /// <summary> /// Computes the hash value of a subset of the specified byte array using the /// specified hash algorithm, and signs the resulting hash value. /// </summary> /// <param name="inputStream">The input data for which to compute the hash</param> /// <param name="halg">The hash algorithm to use to create the hash value. </param> /// <returns>The RSA signature for the specified data.</returns> public byte[] SignData(Stream inputStream, object halg) { int calgHash = CapiHelper.ObjToHashAlgId(halg); HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg); byte[] hashVal = hash.ComputeHash(inputStream); return SignHash(hashVal, calgHash); } /// <summary> /// Computes the hash value of a subset of the specified byte array using the /// specified hash algorithm, and signs the resulting hash value. /// </summary> /// <param name="rgbHash">The input data for which to compute the hash</param> /// <param name="str">The hash algorithm to use to create the hash value. </param> /// <returns>The RSA signature for the specified data.</returns> public byte[] SignHash(byte[] rgbHash, string str) { if (rgbHash == null) throw new ArgumentNullException(nameof(rgbHash)); if (PublicOnly) throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); int calgHash = CapiHelper.NameOrOidToHashAlgId(str, OidGroup.HashAlgorithm); return SignHash(rgbHash, calgHash); } /// <summary> /// Computes the hash value of a subset of the specified byte array using the /// specified hash algorithm, and signs the resulting hash value. /// </summary> /// <param name="rgbHash">The input data for which to compute the hash</param> /// <param name="calgHash">The hash algorithm to use to create the hash value. </param> /// <returns>The RSA signature for the specified data.</returns> private byte[] SignHash(byte[] rgbHash, int calgHash) { Debug.Assert(rgbHash != null); return CapiHelper.SignValue( SafeProvHandle, SafeKeyHandle, _parameters.KeyNumber, CapiHelper.CALG_RSA_SIGN, calgHash, rgbHash); } /// <summary> /// Verifies the signature of a hash value. /// </summary> public bool VerifyData(byte[] buffer, object halg, byte[] signature) { int calgHash = CapiHelper.ObjToHashAlgId(halg); HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg); byte[] hashVal = hash.ComputeHash(buffer); return VerifyHash(hashVal, calgHash, signature); } /// <summary> /// Verifies the signature of a hash value. /// </summary> public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature) { if (rgbHash == null) throw new ArgumentNullException(nameof(rgbHash)); if (rgbSignature == null) throw new ArgumentNullException(nameof(rgbSignature)); int calgHash = CapiHelper.NameOrOidToHashAlgId(str, OidGroup.HashAlgorithm); return VerifyHash(rgbHash, calgHash, rgbSignature); } /// <summary> /// Verifies the signature of a hash value. /// </summary> private bool VerifyHash(byte[] rgbHash, int calgHash, byte[] rgbSignature) { return CapiHelper.VerifySign( SafeProvHandle, SafeKeyHandle, CapiHelper.CALG_RSA_SIGN, calgHash, rgbHash, rgbSignature); } /// <summary> /// find whether an RSA key blob is public. /// </summary> private static bool IsPublic(byte[] keyBlob) { if (keyBlob == null) { throw new ArgumentNullException(nameof(keyBlob)); } // The CAPI RSA public key representation consists of the following sequence: // - BLOBHEADER // - RSAPUBKEY // The first should be PUBLICKEYBLOB and magic should be RSA_PUB_MAGIC "RSA1" if (keyBlob[0] != CapiHelper.PUBLICKEYBLOB) { return false; } if (keyBlob[11] != 0x31 || keyBlob[10] != 0x41 || keyBlob[9] != 0x53 || keyBlob[8] != 0x52) { return false; } return true; } protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { // we're sealed and the base should have checked this already Debug.Assert(data != null); Debug.Assert(count >= 0 && count <= data.Length); Debug.Assert(offset >= 0 && offset <= data.Length - count); Debug.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name)); using (HashAlgorithm hash = GetHashAlgorithm(hashAlgorithm)) { return hash.ComputeHash(data, offset, count); } } protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) { // we're sealed and the base should have checked this already Debug.Assert(data != null); Debug.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name)); using (HashAlgorithm hash = GetHashAlgorithm(hashAlgorithm)) { return hash.ComputeHash(data); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5351", Justification = "MD5 is used when the user asks for it.")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "SHA1 is used when the user asks for it.")] private static HashAlgorithm GetHashAlgorithm(HashAlgorithmName hashAlgorithm) { switch (hashAlgorithm.Name) { case "MD5": return MD5.Create(); case "SHA1": return SHA1.Create(); case "SHA256": return SHA256.Create(); case "SHA384": return SHA384.Create(); case "SHA512": return SHA512.Create(); default: throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name); } } private static int GetAlgorithmId(HashAlgorithmName hashAlgorithm) { switch (hashAlgorithm.Name) { case "MD5": return CapiHelper.CALG_MD5; case "SHA1": return CapiHelper.CALG_SHA1; case "SHA256": return CapiHelper.CALG_SHA_256; case "SHA384": return CapiHelper.CALG_SHA_384; case "SHA512": return CapiHelper.CALG_SHA_512; default: throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name); } } public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); if (padding == null) throw new ArgumentNullException(nameof(padding)); if (padding == RSAEncryptionPadding.Pkcs1) { return Encrypt(data, fOAEP: false); } else if (padding == RSAEncryptionPadding.OaepSHA1) { return Encrypt(data, fOAEP: true); } else { throw PaddingModeNotSupported(); } } public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); if (padding == null) throw new ArgumentNullException(nameof(padding)); if (padding == RSAEncryptionPadding.Pkcs1) { return Decrypt(data, fOAEP: false); } else if (padding == RSAEncryptionPadding.OaepSHA1) { return Decrypt(data, fOAEP: true); } else { throw PaddingModeNotSupported(); } } public override byte[] SignHash( byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (hash == null) throw new ArgumentNullException(nameof(hash)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); if (padding == null) throw new ArgumentNullException(nameof(padding)); if (padding != RSASignaturePadding.Pkcs1) throw PaddingModeNotSupported(); return SignHash(hash, GetAlgorithmId(hashAlgorithm)); } public override bool VerifyHash( byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (hash == null) throw new ArgumentNullException(nameof(hash)); if (signature == null) throw new ArgumentNullException(nameof(signature)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); if (padding == null) throw new ArgumentNullException(nameof(padding)); if (padding != RSASignaturePadding.Pkcs1) throw PaddingModeNotSupported(); return VerifyHash(hash, GetAlgorithmId(hashAlgorithm), signature); } public override string KeyExchangeAlgorithm { get { if (_parameters.KeyNumber == (int)Interop.Advapi32.KeySpec.AT_KEYEXCHANGE) { return "RSA-PKCS1-KeyEx"; } return null; } } public override string SignatureAlgorithm { get { return "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; } } private static Exception PaddingModeNotSupported() { return new CryptographicException(SR.Cryptography_InvalidPaddingMode); } private static Exception HashAlgorithmNameNullOrEmpty() { return new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm"); } private void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException(nameof(DSACryptoServiceProvider)); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Threading; using TrueCraft.API; using TrueCraft.API.World; using TrueCraft.API.Logic; using fNbt; using System.Collections; namespace TrueCraft.Core.World { public class World : IDisposable, IWorld, IEnumerable<IChunk> { public static readonly int Height = 128; public string Name { get; set; } private int _Seed; public int Seed { get { return _Seed; } set { _Seed = value; BiomeDiagram = new BiomeMap(_Seed); } } private Coordinates3D? _SpawnPoint; public Coordinates3D SpawnPoint { get { if (_SpawnPoint == null) _SpawnPoint = ChunkProvider.GetSpawn(this); return _SpawnPoint.Value; } set { _SpawnPoint = value; } } public string BaseDirectory { get; internal set; } public IDictionary<Coordinates2D, IRegion> Regions { get; set; } public IBiomeMap BiomeDiagram { get; set; } public IChunkProvider ChunkProvider { get; set; } public IBlockRepository BlockRepository { get; set; } public DateTime BaseTime { get; set; } public long Time { get { return (long)((DateTime.UtcNow - BaseTime).TotalSeconds * 20) % 24000; } set { BaseTime = DateTime.UtcNow.AddSeconds(-value / 20); } } public event EventHandler<BlockChangeEventArgs> BlockChanged; public event EventHandler<ChunkLoadedEventArgs> ChunkGenerated; public event EventHandler<ChunkLoadedEventArgs> ChunkLoaded; public World() { Regions = new Dictionary<Coordinates2D, IRegion>(); BaseTime = DateTime.UtcNow; } public World(string name) : this() { Name = name; Seed = MathHelper.Random.Next(); } public World(string name, IChunkProvider chunkProvider) : this(name) { ChunkProvider = chunkProvider; ChunkProvider.Initialize(this); } public World(string name, int seed, IChunkProvider chunkProvider) : this(name, chunkProvider) { Seed = seed; } public static World LoadWorld(string baseDirectory) { if (!Directory.Exists(baseDirectory)) throw new DirectoryNotFoundException(); var world = new World(Path.GetFileName(baseDirectory)); world.BaseDirectory = baseDirectory; if (File.Exists(Path.Combine(baseDirectory, "manifest.nbt"))) { var file = new NbtFile(Path.Combine(baseDirectory, "manifest.nbt")); world.SpawnPoint = new Coordinates3D(file.RootTag["SpawnPoint"]["X"].IntValue, file.RootTag["SpawnPoint"]["Y"].IntValue, file.RootTag["SpawnPoint"]["Z"].IntValue); world.Seed = file.RootTag["Seed"].IntValue; var providerName = file.RootTag["ChunkProvider"].StringValue; var provider = (IChunkProvider)Activator.CreateInstance(Type.GetType(providerName)); provider.Initialize(world); if (file.RootTag.Contains("Name")) world.Name = file.RootTag["Name"].StringValue; world.ChunkProvider = provider; } return world; } /// <summary> /// Finds a chunk that contains the specified block coordinates. /// </summary> public IChunk FindChunk(Coordinates3D coordinates, bool generate = true) { IChunk chunk; FindBlockPosition(coordinates, out chunk, generate); return chunk; } public IChunk GetChunk(Coordinates2D coordinates, bool generate = true) { int regionX = coordinates.X / Region.Width - ((coordinates.X < 0) ? 1 : 0); int regionZ = coordinates.Z / Region.Depth - ((coordinates.Z < 0) ? 1 : 0); var region = LoadOrGenerateRegion(new Coordinates2D(regionX, regionZ), generate); if (region == null) return null; return region.GetChunk(new Coordinates2D(coordinates.X - regionX * 32, coordinates.Z - regionZ * 32), generate); } public void GenerateChunk(Coordinates2D coordinates) { int regionX = coordinates.X / Region.Width - ((coordinates.X < 0) ? 1 : 0); int regionZ = coordinates.Z / Region.Depth - ((coordinates.Z < 0) ? 1 : 0); var region = LoadOrGenerateRegion(new Coordinates2D(regionX, regionZ)); region.GenerateChunk(new Coordinates2D(coordinates.X - regionX * 32, coordinates.Z - regionZ * 32)); } public void SetChunk(Coordinates2D coordinates, Chunk chunk) { int regionX = coordinates.X / Region.Width - ((coordinates.X < 0) ? 1 : 0); int regionZ = coordinates.Z / Region.Depth - ((coordinates.Z < 0) ? 1 : 0); var region = LoadOrGenerateRegion(new Coordinates2D(regionX, regionZ)); lock (region) { chunk.IsModified = true; region.SetChunk(new Coordinates2D(coordinates.X - regionX * 32, coordinates.Z - regionZ * 32), chunk); } } public void UnloadRegion(Coordinates2D coordinates) { lock (Regions) { Regions[coordinates].Save(Path.Combine(BaseDirectory, Region.GetRegionFileName(coordinates))); Regions.Remove(coordinates); } } public void UnloadChunk(Coordinates2D coordinates) { int regionX = coordinates.X / Region.Width - ((coordinates.X < 0) ? 1 : 0); int regionZ = coordinates.Z / Region.Depth - ((coordinates.Z < 0) ? 1 : 0); var regionPosition = new Coordinates2D(regionX, regionZ); if (!Regions.ContainsKey(regionPosition)) throw new ArgumentOutOfRangeException("coordinates"); Regions[regionPosition].UnloadChunk(new Coordinates2D(coordinates.X - regionX * 32, coordinates.Z - regionZ * 32)); } public byte GetBlockID(Coordinates3D coordinates) { IChunk chunk; coordinates = FindBlockPosition(coordinates, out chunk); return chunk.GetBlockID(coordinates); } public byte GetMetadata(Coordinates3D coordinates) { IChunk chunk; coordinates = FindBlockPosition(coordinates, out chunk); return chunk.GetMetadata(coordinates); } public byte GetSkyLight(Coordinates3D coordinates) { IChunk chunk; coordinates = FindBlockPosition(coordinates, out chunk); return chunk.GetSkyLight(coordinates); } public byte GetBlockLight(Coordinates3D coordinates) { IChunk chunk; coordinates = FindBlockPosition(coordinates, out chunk); return chunk.GetBlockLight(coordinates); } public NbtCompound GetTileEntity(Coordinates3D coordinates) { IChunk chunk; coordinates = FindBlockPosition(coordinates, out chunk); return chunk.GetTileEntity(coordinates); } public BlockDescriptor GetBlockData(Coordinates3D coordinates) { IChunk chunk; var adjustedCoordinates = FindBlockPosition(coordinates, out chunk); return GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates); } public void SetBlockData(Coordinates3D coordinates, BlockDescriptor descriptor) { IChunk chunk; var adjustedCoordinates = FindBlockPosition(coordinates, out chunk); var old = GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates); chunk.SetBlockID(adjustedCoordinates, descriptor.ID); chunk.SetMetadata(adjustedCoordinates, descriptor.Metadata); if (BlockChanged != null) BlockChanged(this, new BlockChangeEventArgs(coordinates, old, GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates))); } private BlockDescriptor GetBlockDataFromChunk(Coordinates3D adjustedCoordinates, IChunk chunk, Coordinates3D coordinates) { return new BlockDescriptor { ID = chunk.GetBlockID(adjustedCoordinates), Metadata = chunk.GetMetadata(adjustedCoordinates), BlockLight = chunk.GetBlockLight(adjustedCoordinates), SkyLight = chunk.GetSkyLight(adjustedCoordinates), Coordinates = coordinates }; } public void SetBlockID(Coordinates3D coordinates, byte value) { IChunk chunk; var adjustedCoordinates = FindBlockPosition(coordinates, out chunk); BlockDescriptor old = new BlockDescriptor(); if (BlockChanged != null) old = GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates); chunk.SetBlockID(adjustedCoordinates, value); if (BlockChanged != null) BlockChanged(this, new BlockChangeEventArgs(coordinates, old, GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates))); } public void SetMetadata(Coordinates3D coordinates, byte value) { IChunk chunk; var adjustedCoordinates = FindBlockPosition(coordinates, out chunk); BlockDescriptor old = new BlockDescriptor(); if (BlockChanged != null) old = GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates); chunk.SetMetadata(adjustedCoordinates, value); if (BlockChanged != null) BlockChanged(this, new BlockChangeEventArgs(coordinates, old, GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates))); } public void SetSkyLight(Coordinates3D coordinates, byte value) { IChunk chunk; var adjustedCoordinates = FindBlockPosition(coordinates, out chunk); BlockDescriptor old = new BlockDescriptor(); if (BlockChanged != null) old = GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates); chunk.SetSkyLight(adjustedCoordinates, value); if (BlockChanged != null) BlockChanged(this, new BlockChangeEventArgs(coordinates, old, GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates))); } public void SetBlockLight(Coordinates3D coordinates, byte value) { IChunk chunk; var adjustedCoordinates = FindBlockPosition(coordinates, out chunk); BlockDescriptor old = new BlockDescriptor(); if (BlockChanged != null) old = GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates); chunk.SetBlockLight(adjustedCoordinates, value); if (BlockChanged != null) BlockChanged(this, new BlockChangeEventArgs(coordinates, old, GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates))); } public void SetTileEntity(Coordinates3D coordinates, NbtCompound value) { IChunk chunk; coordinates = FindBlockPosition(coordinates, out chunk); chunk.SetTileEntity(coordinates, value); } public void Save() { lock (Regions) { foreach (var region in Regions) region.Value.Save(Path.Combine(BaseDirectory, Region.GetRegionFileName(region.Key))); } var file = new NbtFile(); file.RootTag.Add(new NbtCompound("SpawnPoint", new[] { new NbtInt("X", this.SpawnPoint.X), new NbtInt("Y", this.SpawnPoint.Y), new NbtInt("Z", this.SpawnPoint.Z) })); file.RootTag.Add(new NbtInt("Seed", this.Seed)); file.RootTag.Add(new NbtString("ChunkProvider", this.ChunkProvider.GetType().FullName)); file.RootTag.Add(new NbtString("Name", Name)); file.SaveToFile(Path.Combine(this.BaseDirectory, "manifest.nbt"), NbtCompression.ZLib); } public void Save(string path) { if (!Directory.Exists(path)) Directory.CreateDirectory(path); BaseDirectory = path; Save(); } private Dictionary<Thread, IChunk> ChunkCache = new Dictionary<Thread, IChunk>(); private object ChunkCacheLock = new object(); public Coordinates3D FindBlockPosition(Coordinates3D coordinates, out IChunk chunk, bool generate = true) { if (coordinates.Y < 0 || coordinates.Y >= Chunk.Height) throw new ArgumentOutOfRangeException("coordinates", "Coordinates are out of range"); int chunkX = coordinates.X / Chunk.Width; int chunkZ = coordinates.Z / Chunk.Depth; if (coordinates.X < 0) chunkX = (coordinates.X + 1) / Chunk.Width - 1; if (coordinates.Z < 0) chunkZ = (coordinates.Z + 1) / Chunk.Depth - 1; if (ChunkCache.ContainsKey(Thread.CurrentThread)) { var cache = ChunkCache[Thread.CurrentThread]; if (cache != null && chunkX == cache.Coordinates.X && chunkZ == cache.Coordinates.Z) chunk = cache; else { cache = GetChunk(new Coordinates2D(chunkX, chunkZ), generate); lock (ChunkCacheLock) ChunkCache[Thread.CurrentThread] = cache; } } else { var cache = GetChunk(new Coordinates2D(chunkX, chunkZ), generate); lock (ChunkCacheLock) ChunkCache[Thread.CurrentThread] = cache; } chunk = GetChunk(new Coordinates2D(chunkX, chunkZ), generate); return new Coordinates3D( (coordinates.X % Chunk.Width + Chunk.Width) % Chunk.Width, coordinates.Y, (coordinates.Z % Chunk.Depth + Chunk.Depth) % Chunk.Depth); } public bool IsValidPosition(Coordinates3D position) { return position.Y >= 0 && position.Y < Chunk.Height; } private Region LoadOrGenerateRegion(Coordinates2D coordinates, bool generate = true) { if (Regions.ContainsKey(coordinates)) return (Region)Regions[coordinates]; if (!generate) return null; Region region; if (BaseDirectory != null) { var file = Path.Combine(BaseDirectory, Region.GetRegionFileName(coordinates)); if (File.Exists(file)) region = new Region(coordinates, this, file); else region = new Region(coordinates, this); } else region = new Region(coordinates, this); lock (Regions) Regions[coordinates] = region; return region; } public void Dispose() { foreach (var region in Regions) region.Value.Dispose(); BlockChanged = null; ChunkGenerated = null; } protected internal void OnChunkGenerated(ChunkLoadedEventArgs e) { if (ChunkGenerated != null) ChunkGenerated(this, e); } protected internal void OnChunkLoaded(ChunkLoadedEventArgs e) { if (ChunkLoaded != null) ChunkLoaded(this, e); } public class ChunkEnumerator : IEnumerator<IChunk> { public World World { get; set; } private int Index { get; set; } private IList<IChunk> Chunks { get; set; } public ChunkEnumerator(World world) { World = world; Index = -1; var regions = world.Regions.Values.ToList(); var chunks = new List<IChunk>(); foreach (var region in regions) chunks.AddRange(region.Chunks.Values); Chunks = chunks; } public bool MoveNext() { Index++; return Index < Chunks.Count; } public void Reset() { Index = -1; } public void Dispose() { } public IChunk Current { get { return Chunks[Index]; } } object IEnumerator.Current { get { return Current; } } } public IEnumerator<IChunk> GetEnumerator() { return new ChunkEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } }
// TarOutputStream.cs // // Copyright (C) 2001 Mike Krueger // Copyright 2005 John Reilly // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; using System.IO; using System.Text; namespace ICSharpCode.SharpZipLib.Tar { /// <summary> /// The TarOutputStream writes a UNIX tar archive as an OutputStream. /// Methods are provided to put entries, and then write their contents /// by writing to this stream using write(). /// </summary> /// public public class TarOutputStream : Stream { #region Constructors /// <summary> /// Construct TarOutputStream using default block factor /// </summary> /// <param name="outputStream">stream to write to</param> public TarOutputStream(Stream outputStream) : this(outputStream, TarBuffer.DefaultBlockFactor) { } /// <summary> /// Construct TarOutputStream with user specified block factor /// </summary> /// <param name="outputStream">stream to write to</param> /// <param name="blockFactor">blocking factor</param> public TarOutputStream(Stream outputStream, int blockFactor) { if ( outputStream == null ) { throw new ArgumentNullException("outputStream"); } this.outputStream = outputStream; buffer = TarBuffer.CreateOutputTarBuffer(outputStream, blockFactor); assemblyBuffer = new byte[TarBuffer.BlockSize]; blockBuffer = new byte[TarBuffer.BlockSize]; } #endregion /// <summary> /// true if the stream supports reading; otherwise, false. /// </summary> public override bool CanRead { get { return outputStream.CanRead; } } /// <summary> /// true if the stream supports seeking; otherwise, false. /// </summary> public override bool CanSeek { get { return outputStream.CanSeek; } } /// <summary> /// true if stream supports writing; otherwise, false. /// </summary> public override bool CanWrite { get { return outputStream.CanWrite; } } /// <summary> /// length of stream in bytes /// </summary> public override long Length { get { return outputStream.Length; } } /// <summary> /// gets or sets the position within the current stream. /// </summary> public override long Position { get { return outputStream.Position; } set { outputStream.Position = value; } } /// <summary> /// set the position within the current stream /// </summary> /// <param name="offset">The offset relative to the <paramref name="origin"/> to seek to</param> /// <param name="origin">The <see cref="SeekOrigin"/> to seek from.</param> /// <returns>The new position in the stream.</returns> public override long Seek(long offset, SeekOrigin origin) { return outputStream.Seek(offset, origin); } /// <summary> /// Set the length of the current stream /// </summary> /// <param name="value">The new stream length.</param> public override void SetLength(long value) { outputStream.SetLength(value); } /// <summary> /// Read a byte from the stream and advance the position within the stream /// by one byte or returns -1 if at the end of the stream. /// </summary> /// <returns>The byte value or -1 if at end of stream</returns> public override int ReadByte() { return outputStream.ReadByte(); } /// <summary> /// read bytes from the current stream and advance the position within the /// stream by the number of bytes read. /// </summary> /// <param name="buffer">The buffer to store read bytes in.</param> /// <param name="offset">The index into the buffer to being storing bytes at.</param> /// <param name="count">The desired number of bytes to read.</param> /// <returns>The total number of bytes read, or zero if at the end of the stream. /// The number of bytes may be less than the <paramref name="count">count</paramref> /// requested if data is not avialable.</returns> public override int Read(byte[] buffer, int offset, int count) { return outputStream.Read(buffer, offset, count); } /// <summary> /// All buffered data is written to destination /// </summary> public override void Flush() { outputStream.Flush(); } /// <summary> /// Ends the TAR archive without closing the underlying OutputStream. /// The result is that the EOF block of nulls is written. /// </summary> public void Finish() { if ( IsEntryOpen ) { CloseEntry(); } WriteEofBlock(); } /// <summary> /// Ends the TAR archive and closes the underlying OutputStream. /// </summary> /// <remarks>This means that Finish() is called followed by calling the /// TarBuffer's Close().</remarks> public override void Close() { if ( !isClosed ) { isClosed = true; Finish(); buffer.Close(); } } /// <summary> /// Get the record size being used by this stream's TarBuffer. /// </summary> public int RecordSize { get { return buffer.RecordSize; } } /// <summary> /// Get the record size being used by this stream's TarBuffer. /// </summary> /// <returns> /// The TarBuffer record size. /// </returns> [Obsolete("Use RecordSize property instead")] public int GetRecordSize() { return buffer.RecordSize; } /// <summary> /// Get a value indicating wether an entry is open, requiring more data to be written. /// </summary> bool IsEntryOpen { get { return (currBytes < currSize); } } /// <summary> /// Put an entry on the output stream. This writes the entry's /// header and positions the output stream for writing /// the contents of the entry. Once this method is called, the /// stream is ready for calls to write() to write the entry's /// contents. Once the contents are written, closeEntry() /// <B>MUST</B> be called to ensure that all buffered data /// is completely written to the output stream. /// </summary> /// <param name="entry"> /// The TarEntry to be written to the archive. /// </param> public void PutNextEntry(TarEntry entry) { if ( entry == null ) { throw new ArgumentNullException("entry"); } if (entry.TarHeader.Name.Length >= TarHeader.NAMELEN) { TarHeader longHeader = new TarHeader(); longHeader.TypeFlag = TarHeader.LF_GNU_LONGNAME; longHeader.Name = longHeader.Name + "././@LongLink"; longHeader.UserId = 0; longHeader.GroupId = 0; longHeader.GroupName = ""; longHeader.UserName = ""; longHeader.LinkName = ""; longHeader.Size = entry.TarHeader.Name.Length; longHeader.WriteHeader(this.blockBuffer); this.buffer.WriteBlock(this.blockBuffer); // Add special long filename header block int nameCharIndex = 0; while (nameCharIndex < entry.TarHeader.Name.Length) { Array.Clear(blockBuffer, 0, blockBuffer.Length); TarHeader.GetAsciiBytes(entry.TarHeader.Name, nameCharIndex, this.blockBuffer, 0, TarBuffer.BlockSize); nameCharIndex += TarBuffer.BlockSize; buffer.WriteBlock(blockBuffer); } } entry.WriteEntryHeader(blockBuffer); buffer.WriteBlock(blockBuffer); currBytes = 0; currSize = entry.IsDirectory ? 0 : entry.Size; } /// <summary> /// Close an entry. This method MUST be called for all file /// entries that contain data. The reason is that we must /// buffer data written to the stream in order to satisfy /// the buffer's block based writes. Thus, there may be /// data fragments still being assembled that must be written /// to the output stream before this entry is closed and the /// next entry written. /// </summary> public void CloseEntry() { if (assemblyBufferLength > 0) { Array.Clear(assemblyBuffer, assemblyBufferLength, assemblyBuffer.Length - assemblyBufferLength); buffer.WriteBlock(assemblyBuffer); currBytes += assemblyBufferLength; assemblyBufferLength = 0; } if (currBytes < currSize) { string errorText = string.Format( "Entry closed at '{0}' before the '{1}' bytes specified in the header were written", currBytes, currSize); throw new TarException(errorText); } } /// <summary> /// Writes a byte to the current tar archive entry. /// This method simply calls Write(byte[], int, int). /// </summary> /// <param name="value"> /// The byte to be written. /// </param> public override void WriteByte(byte value) { Write(new byte[] { value }, 0, 1); } /// <summary> /// Writes bytes to the current tar archive entry. This method /// is aware of the current entry and will throw an exception if /// you attempt to write bytes past the length specified for the /// current entry. The method is also (painfully) aware of the /// record buffering required by TarBuffer, and manages buffers /// that are not a multiple of recordsize in length, including /// assembling records from small buffers. /// </summary> /// <param name = "buffer"> /// The buffer to write to the archive. /// </param> /// <param name = "offset"> /// The offset in the buffer from which to get bytes. /// </param> /// <param name = "count"> /// The number of bytes to write. /// </param> public override void Write(byte[] buffer, int offset, int count) { if ( buffer == null ) { throw new ArgumentNullException("buffer"); } if ( offset < 0 ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("offset"); #else throw new ArgumentOutOfRangeException("offset", "Cannot be negative"); #endif } if ( buffer.Length - offset < count ) { throw new ArgumentException("offset and count combination is invalid"); } if ( count < 0 ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("count"); #else throw new ArgumentOutOfRangeException("count", "Cannot be negative"); #endif } if ( (currBytes + count) > currSize ) { string errorText = string.Format("request to write '{0}' bytes exceeds size in header of '{1}' bytes", count, this.currSize); #if NETCF_1_0 throw new ArgumentOutOfRangeException("count"); #else throw new ArgumentOutOfRangeException("count", errorText); #endif } // // We have to deal with assembly!!! // The programmer can be writing little 32 byte chunks for all // we know, and we must assemble complete blocks for writing. // TODO REVIEW Maybe this should be in TarBuffer? Could that help to // eliminate some of the buffer copying. // if (assemblyBufferLength > 0) { if ((assemblyBufferLength + count ) >= blockBuffer.Length) { int aLen = blockBuffer.Length - assemblyBufferLength; Array.Copy(assemblyBuffer, 0, blockBuffer, 0, assemblyBufferLength); Array.Copy(buffer, offset, blockBuffer, assemblyBufferLength, aLen); this.buffer.WriteBlock(blockBuffer); currBytes += blockBuffer.Length; offset += aLen; count -= aLen; assemblyBufferLength = 0; } else { Array.Copy(buffer, offset, assemblyBuffer, assemblyBufferLength, count); offset += count; assemblyBufferLength += count; count -= count; } } // // When we get here we have EITHER: // o An empty "assembly" buffer. // o No bytes to write (count == 0) // while (count > 0) { if (count < blockBuffer.Length) { Array.Copy(buffer, offset, assemblyBuffer, assemblyBufferLength, count); assemblyBufferLength += count; break; } this.buffer.WriteBlock(buffer, offset); int bufferLength = blockBuffer.Length; currBytes += bufferLength; count -= bufferLength; offset += bufferLength; } } /// <summary> /// Write an EOF (end of archive) block to the tar archive. /// An EOF block consists of all zeros. /// </summary> void WriteEofBlock() { Array.Clear(blockBuffer, 0, blockBuffer.Length); buffer.WriteBlock(blockBuffer); } #region Instance Fields /// <summary> /// bytes written for this entry so far /// </summary> long currBytes; /// <summary> /// current 'Assembly' buffer length /// </summary> int assemblyBufferLength; /// <summary> /// Flag indicating wether this instance has been closed or not. /// </summary> bool isClosed; /// <summary> /// Size for the current entry /// </summary> protected long currSize; /// <summary> /// single block working buffer /// </summary> protected byte[] blockBuffer; /// <summary> /// 'Assembly' buffer used to assemble data before writing /// </summary> protected byte[] assemblyBuffer; /// <summary> /// TarBuffer used to provide correct blocking factor /// </summary> protected TarBuffer buffer; /// <summary> /// the destination stream for the archive contents /// </summary> protected Stream outputStream; #endregion } } /* The original Java file had this header: ** Authored by Timothy Gerard Endres ** <mailto:time@gjt.org> <http://www.trustice.com> ** ** This work has been placed into the public domain. ** You may use this work in any way and for any purpose you wish. ** ** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND, ** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR ** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY ** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR ** REDISTRIBUTION OF THIS SOFTWARE. ** */
// GET request message type. // Copyright (C) 2008-2010 Malcolm Crowe, Lex Li, and other contributors. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using Lextm.SharpSnmpLib.Security; namespace Lextm.SharpSnmpLib.Messaging { /// <summary> /// GET request message. /// </summary> public sealed class GetRequestMessage : ISnmpMessage { private readonly byte[] _bytes; /// <summary> /// Creates a <see cref="GetRequestMessage"/> with all contents. /// </summary> /// <param name="requestId">The request id.</param> /// <param name="version">Protocol version</param> /// <param name="community">Community name</param> /// <param name="variables">Variables</param> public GetRequestMessage(int requestId, VersionCode version, OctetString community, IList<Variable> variables) { if (variables == null) { throw new ArgumentNullException("variables"); } if (community == null) { throw new ArgumentNullException("community"); } if (version == VersionCode.V3) { throw new ArgumentException("only v1 and v2c are supported", "version"); } Version = version; Header = Header.Empty; Parameters = SecurityParameters.Create(community); var pdu = new GetRequestPdu( requestId, variables); Scope = new Scope(pdu); Privacy = DefaultPrivacyProvider.DefaultPair; _bytes = this.PackMessage(null).ToBytes(); } /// <summary> /// Initializes a new instance of the <see cref="GetRequestMessage"/> class. /// </summary> /// <param name="version">The version.</param> /// <param name="messageId">The message id.</param> /// <param name="requestId">The request id.</param> /// <param name="userName">Name of the user.</param> /// <param name="variables">The variables.</param> /// <param name="privacy">The privacy provider.</param> /// <param name="report">The report.</param> [Obsolete("Please use other overloading ones.")] public GetRequestMessage(VersionCode version, int messageId, int requestId, OctetString userName, IList<Variable> variables, IPrivacyProvider privacy, ISnmpMessage report) : this(version, messageId, requestId, userName, variables, privacy, 0xFFE3, report) { } /// <summary> /// Initializes a new instance of the <see cref="GetRequestMessage"/> class. /// </summary> /// <param name="version">The version.</param> /// <param name="messageId">The message id.</param> /// <param name="requestId">The request id.</param> /// <param name="userName">Name of the user.</param> /// <param name="variables">The variables.</param> /// <param name="privacy">The privacy provider.</param> /// <param name="maxMessageSize">Size of the max message.</param> /// <param name="report">The report.</param> public GetRequestMessage(VersionCode version, int messageId, int requestId, OctetString userName, IList<Variable> variables, IPrivacyProvider privacy, int maxMessageSize, ISnmpMessage report) { if (userName == null) { throw new ArgumentNullException("userName"); } if (variables == null) { throw new ArgumentNullException("variables"); } if (version != VersionCode.V3) { throw new ArgumentException("only v3 is supported", "version"); } if (report == null) { throw new ArgumentNullException("report"); } if (privacy == null) { throw new ArgumentNullException("privacy"); } Version = version; Privacy = privacy; Header = new Header(new Integer32(messageId), new Integer32(maxMessageSize), privacy.ToSecurityLevel() | Levels.Reportable); var parameters = report.Parameters; var authenticationProvider = Privacy.AuthenticationProvider; Parameters = new SecurityParameters( parameters.EngineId, parameters.EngineBoots, parameters.EngineTime, userName, authenticationProvider.CleanDigest, Privacy.Salt); var pdu = new GetRequestPdu( requestId, variables); var scope = report.Scope; var contextEngineId = scope.ContextEngineId == OctetString.Empty ? parameters.EngineId : scope.ContextEngineId; Scope = new Scope(contextEngineId, scope.ContextName, pdu); authenticationProvider.ComputeHash(Version, Header, Parameters, Scope, Privacy); _bytes = this.PackMessage(null).ToBytes(); } internal GetRequestMessage(VersionCode version, Header header, SecurityParameters parameters, Scope scope, IPrivacyProvider privacy, byte[] length) { if (scope == null) { throw new ArgumentNullException("scope"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (header == null) { throw new ArgumentNullException("header"); } if (privacy == null) { throw new ArgumentNullException("privacy"); } Version = version; Header = header; Parameters = parameters; Scope = scope; Privacy = privacy; _bytes = this.PackMessage(length).ToBytes(); } /// <summary> /// Gets the header. /// </summary> public Header Header { get; private set; } /// <summary> /// Gets the privacy provider. /// </summary> /// <value>The privacy provider.</value> public IPrivacyProvider Privacy { get; private set; } /// <summary> /// Version. /// </summary> public VersionCode Version { get; private set; } /// <summary> /// Converts to byte format. /// </summary> /// <returns></returns> public byte[] ToBytes() { return _bytes; } /// <summary> /// Gets the parameters. /// </summary> /// <value>The parameters.</value> public SecurityParameters Parameters { get; private set; } /// <summary> /// Gets the scope. /// </summary> /// <value>The scope.</value> public Scope Scope { get; private set; } /// <summary> /// Returns a <see cref="string"/> that represents this <see cref="GetRequestMessage"/>. /// </summary> /// <returns></returns> public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "GET request message: version: {0}; {1}; {2}", Version, this.Community(), this.Pdu()); } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Strategies.Algo File: StrategyHelper.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Strategies { using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using Ecng.Collections; using Ecng.Common; using Ecng.Configuration; using Ecng.Serialization; using MoreLinq; using StockSharp.Algo.Candles; using StockSharp.Algo.Storages; using StockSharp.Algo.Testing; using StockSharp.BusinessEntities; using StockSharp.Messages; using StockSharp.Localization; using StockSharp.Logging; /// <summary> /// Extension class for <see cref="Strategy"/>. /// </summary> public static class StrategyHelper { /// <summary> /// To create initialized object of buy order at market price. /// </summary> /// <param name="strategy">Strategy.</param> /// <param name="volume">The volume. If <see langword="null" /> value is passed, then <see cref="Strategy.Volume"/> value is used.</param> /// <returns>The initialized order object.</returns> /// <remarks> /// The order is not registered, only the object is created. /// </remarks> public static Order BuyAtMarket(this Strategy strategy, decimal? volume = null) { return strategy.CreateOrder(Sides.Buy, null, volume); } /// <summary> /// To create the initialized order object of sell order at market price. /// </summary> /// <param name="strategy">Strategy.</param> /// <param name="volume">The volume. If <see langword="null" /> value is passed, then <see cref="Strategy.Volume"/> value is used.</param> /// <returns>The initialized order object.</returns> /// <remarks> /// The order is not registered, only the object is created. /// </remarks> public static Order SellAtMarket(this Strategy strategy, decimal? volume = null) { return strategy.CreateOrder(Sides.Sell, null, volume); } /// <summary> /// To create the initialized order object for buy. /// </summary> /// <param name="strategy">Strategy.</param> /// <param name="price">Price.</param> /// <param name="volume">The volume. If <see langword="null" /> value is passed, then <see cref="Strategy.Volume"/> value is used.</param> /// <returns>The initialized order object.</returns> /// <remarks> /// The order is not registered, only the object is created. /// </remarks> public static Order BuyAtLimit(this Strategy strategy, decimal price, decimal? volume = null) { return strategy.CreateOrder(Sides.Buy, price, volume); } /// <summary> /// To create the initialized order object for sell. /// </summary> /// <param name="strategy">Strategy.</param> /// <param name="price">Price.</param> /// <param name="volume">The volume. If <see langword="null" /> value is passed, then <see cref="Strategy.Volume"/> value is used.</param> /// <returns>The initialized order object.</returns> /// <remarks> /// The order is not registered, only the object is created. /// </remarks> public static Order SellAtLimit(this Strategy strategy, decimal price, decimal? volume = null) { return strategy.CreateOrder(Sides.Sell, price, volume); } /// <summary> /// To create the initialized order object. /// </summary> /// <param name="strategy">Strategy.</param> /// <param name="direction">Order side.</param> /// <param name="price">The price. If <see langword="null" /> value is passed, the order is registered at market price.</param> /// <param name="volume">The volume. If <see langword="null" /> value is passed, then <see cref="Strategy.Volume"/> value is used.</param> /// <returns>The initialized order object.</returns> /// <remarks> /// The order is not registered, only the object is created. /// </remarks> public static Order CreateOrder(this Strategy strategy, Sides direction, decimal? price, decimal? volume = null) { if (strategy == null) throw new ArgumentNullException(nameof(strategy)); var security = strategy.Security; if (security == null) throw new InvalidOperationException(LocalizedStrings.Str1403Params.Put(strategy.Name)); var order = new Order { Portfolio = strategy.Portfolio, Security = strategy.Security, Direction = direction, Volume = volume ?? strategy.Volume, }; if (price == null) { //if (security.Board.IsSupportMarketOrders) order.Type = OrderTypes.Market; //else // order.Price = strategy.GetMarketPrice(direction) ?? 0; } else order.Price = price.Value; return order; } /// <summary> /// To close open position by market (to register the order of the type <see cref="OrderTypes.Market"/>). /// </summary> /// <param name="strategy">Strategy.</param> /// <param name="slippage">The slippage level, admissible at the order registration. It is used, if the order is registered using the limit order.</param> /// <remarks> /// The market order is not operable on all exchanges. /// </remarks> public static void ClosePosition(this Strategy strategy, decimal slippage = 0) { if (strategy == null) throw new ArgumentNullException(nameof(strategy)); var position = strategy.Position; if (position != 0) { var volume = position.Abs(); var order = position > 0 ? strategy.SellAtMarket(volume) : strategy.BuyAtMarket(volume); if (order.Type != OrderTypes.Market) { order.Price += (order.Direction == Sides.Buy ? slippage : -slippage); } strategy.RegisterOrder(order); } } /// <summary> /// To get the candle manager, associated with the passed strategy. /// </summary> /// <param name="strategy">Strategy.</param> /// <returns>The candles manager.</returns> public static ICandleManager GetCandleManager(this Strategy strategy) { if (strategy == null) throw new ArgumentNullException(nameof(strategy)); return strategy.Environment.GetValue<ICandleManager>("CandleManager"); } /// <summary> /// To set the candle manager for the strategy. /// </summary> /// <param name="strategy">Strategy.</param> /// <param name="candleManager">The candles manager.</param> public static void SetCandleManager(this Strategy strategy, ICandleManager candleManager) { if (strategy == null) throw new ArgumentNullException(nameof(strategy)); if (candleManager == null) throw new ArgumentNullException(nameof(candleManager)); strategy.Environment.SetValue("CandleManager", candleManager); } /// <summary> /// To get the strategy start-up mode (paper trading or real). /// </summary> /// <param name="strategy">Strategy.</param> /// <returns>If the paper trading mode is used - <see langword="true" />, otherwise - <see langword="false" />.</returns> public static bool GetIsEmulation(this Strategy strategy) { return strategy.Environment.GetValue("IsEmulationMode", false); } /// <summary> /// To get the strategy start-up mode (paper trading or real). /// </summary> /// <param name="strategy">Strategy.</param> /// <param name="isEmulation">If the paper trading mode is used - <see langword="true" />, otherwise - <see langword="false" />.</param> public static void SetIsEmulation(this Strategy strategy, bool isEmulation) { strategy.Environment.SetValue("IsEmulationMode", isEmulation); } /// <summary> /// To get the strategy operation mode (initialization or trade). /// </summary> /// <param name="strategy">Strategy.</param> /// <returns>If initialization is performed - <see langword="true" />, otherwise - <see langword="false" />.</returns> public static bool GetIsInitialization(this Strategy strategy) { var res = strategy.Environment.GetValue("IsInitializationMode", false); if (!res) return false; var dic = strategy.Environment.GetValue("SecurityIdInitializationMode", new Dictionary<SecurityId, bool>()); return dic.Any(p => p.Value); } /// <summary> /// To set the strategy operation mode (initialization or trade). /// </summary> /// <param name="strategy">Strategy.</param> /// <param name="isInitialization">If initialization is performed - <see langword="true" />, otherwise - <see langword="false" />.</param> public static void SetIsInitialization(this Strategy strategy, bool isInitialization) { strategy.Environment.SetValue("IsInitializationMode", isInitialization); } /// <summary> /// To set the strategy operation mode (initialization or trade). /// </summary> /// <param name="strategy">Strategy.</param> /// <param name="securityId">Security identifier.</param> /// <param name="isInitialization">If initialization is performed - <see langword="true" />, otherwise - <see langword="false" />.</param> public static void SetIsInitialization(this Strategy strategy, SecurityId securityId, bool isInitialization) { var dic = strategy.Environment.GetValue("SecurityIdInitializationMode", new Dictionary<SecurityId, bool>()); dic[securityId] = isInitialization; if (dic.All(p => !p.Value)) strategy.SetIsInitialization(false); } /// <summary> /// To restore the strategy state. /// </summary> /// <param name="strategy">Strategy.</param> /// <param name="storage">Market data storage.</param> /// <remarks> /// This method is used to load statistics, orders and trades. /// The data storage shall include the following parameters: /// 1. Settings (SettingsStorage) - statistics settings. /// 2. Statistics(SettingsStorage) - saved state of statistics. /// 3. Orders (IDictionary[Order, IEnumerable[MyTrade]]) - orders and corresponding trades. /// 4. Positions (IEnumerable[Position]) - strategy positions. /// If any of the parameters is missing, data will not be restored. /// </remarks> public static void LoadState(this Strategy strategy, SettingsStorage storage) { if (strategy == null) throw new ArgumentNullException(nameof(strategy)); if (storage == null) throw new ArgumentNullException(nameof(storage)); var settings = storage.GetValue<SettingsStorage>("Settings"); if (settings != null && settings.Count != 0) { var connector = strategy.Connector ?? ConfigManager.TryGetService<IConnector>(); if (connector != null && settings.Contains("security")) strategy.Security = connector.LookupById(settings.GetValue<string>("security")); if (connector != null && settings.Contains("portfolio")) strategy.Portfolio = connector.Portfolios.FirstOrDefault(p => p.Name == settings.GetValue<string>("portfolio")); var id = strategy.Id; strategy.Load(settings); if (strategy.Id != id) throw new InvalidOperationException(LocalizedStrings.Str1404); } var statistics = storage.GetValue<SettingsStorage>("Statistics"); if (statistics != null) { foreach (var parameter in strategy.StatisticManager.Parameters.Where(parameter => statistics.ContainsKey(parameter.Name))) { parameter.Load(statistics.GetValue<SettingsStorage>(parameter.Name)); } } var orders = storage.GetValue<IDictionary<Order, IEnumerable<MyTrade>>>("Orders"); if (orders != null) { foreach (var pair in orders) { strategy.AttachOrder(pair.Key, pair.Value); } } var positions = storage.GetValue<IEnumerable<KeyValuePair<Tuple<SecurityId, string>, decimal>>>("Positions"); if (positions != null) { strategy.PositionManager.Positions = positions; } } /// <summary> /// To get market data value for the strategy instrument. /// </summary> /// <typeparam name="T">The type of the market data field value.</typeparam> /// <param name="strategy">Strategy.</param> /// <param name="field">Market-data field.</param> /// <returns>The field value. If no data, the <see langword="null" /> will be returned.</returns> public static T GetSecurityValue<T>(this Strategy strategy, Level1Fields field) { if (strategy == null) throw new ArgumentNullException(nameof(strategy)); return strategy.GetSecurityValue<T>(strategy.Security, field); } ///// <summary> ///// To get market price for the instrument by maximal and minimal possible prices. ///// </summary> ///// <param name="strategy">Strategy.</param> ///// <param name="side">Order side.</param> ///// <returns>The market price. If there is no information on maximal and minimal possible prices, then <see langword="null" /> will be returned.</returns> //public static decimal? GetMarketPrice(this Strategy strategy, Sides side) //{ // if (strategy == null) // throw new ArgumentNullException(nameof(strategy)); // return strategy.Security.GetMarketPrice(strategy.SafeGetConnector(), side); //} /// <summary> /// To get the tracing-based order identifier. /// </summary> /// <param name="order">Order.</param> /// <returns>The tracing-based order identifier.</returns> public static string GetTraceId(this Order order) { return "{0} (0x{1:X})".Put(order.TransactionId, order.GetHashCode()); } private sealed class EquityStrategy : Strategy { private readonly Dictionary<DateTimeOffset, Order[]> _orders; private readonly Dictionary<Tuple<Security, Portfolio>, Strategy> _childStrategies; public EquityStrategy(IEnumerable<Order> orders, IDictionary<Security, decimal> openedPositions) { _orders = orders.GroupBy(o => o.Time).ToDictionary(g => g.Key, g => g.ToArray()); _childStrategies = orders.ToDictionary(GetKey, o => new Strategy { Portfolio = o.Portfolio, Security = o.Security, Position = openedPositions.TryGetValue2(o.Security) ?? 0, }); ChildStrategies.AddRange(_childStrategies.Values); } protected override void OnStarted() { base.OnStarted(); SafeGetConnector() .WhenTimeCome(_orders.Keys) .Do(time => _orders[time].ForEach(o => _childStrategies[GetKey(o)].RegisterOrder(o))) .Apply(this); } private static Tuple<Security, Portfolio> GetKey(Order order) { return Tuple.Create(order.Security, order.Portfolio); } } /// <summary> /// To emulate orders on history. /// </summary> /// <param name="orders">Orders to be emulated on history.</param> /// <param name="storageRegistry">The external storage for access to history data.</param> /// <param name="openedPositions">Trades, describing initial open positions.</param> /// <returns>The virtual strategy, containing progress of paper trades.</returns> public static Strategy EmulateOrders(this IEnumerable<Order> orders, IStorageRegistry storageRegistry, IDictionary<Security, decimal> openedPositions) { if (openedPositions == null) throw new ArgumentNullException(nameof(openedPositions)); if (storageRegistry == null) throw new ArgumentNullException(nameof(storageRegistry)); if (orders == null) throw new ArgumentNullException(nameof(orders)); var array = orders.ToArray(); if (array.IsEmpty()) throw new ArgumentOutOfRangeException(nameof(orders)); using (var connector = new RealTimeEmulationTrader<HistoryMessageAdapter>(new HistoryMessageAdapter(new IncrementalIdGenerator(), new CollectionSecurityProvider(array.Select(o => o.Security).Distinct())) { StorageRegistry = storageRegistry })) { var from = array.Min(o => o.Time); var to = from.EndOfDay(); var strategy = new EquityStrategy(array, openedPositions) { Connector = connector }; var waitHandle = new SyncObject(); //connector.UnderlyngMarketDataAdapter.StateChanged += () => //{ // if (connector.UnderlyngMarketDataAdapter.State == EmulationStates.Started) // strategy.Start(); // if (connector.UnderlyngMarketDataAdapter.State == EmulationStates.Stopped) // { // strategy.Stop(); // waitHandle.Pulse(); // } //}; connector.UnderlyngMarketDataAdapter.StartDate = from; connector.UnderlyngMarketDataAdapter.StopDate = to; connector.Connect(); //lock (waitHandle) //{ // if (connector.UnderlyngMarketDataAdapter.State != EmulationStates.Stopped) // waitHandle.Wait(); //} return strategy; } } #region Strategy rules private abstract class StrategyRule<TArg> : MarketRule<Strategy, TArg> { protected StrategyRule(Strategy strategy) : base(strategy) { if (strategy == null) throw new ArgumentNullException(nameof(strategy)); Strategy = strategy; } protected Strategy Strategy { get; } } private sealed class PnLManagerStrategyRule : StrategyRule<decimal> { private readonly Func<decimal, bool> _changed; public PnLManagerStrategyRule(Strategy strategy) : this(strategy, v => true) { Name = LocalizedStrings.PnLChange; } public PnLManagerStrategyRule(Strategy strategy, Func<decimal, bool> changed) : base(strategy) { if (changed == null) throw new ArgumentNullException(nameof(changed)); _changed = changed; Strategy.PnLChanged += OnPnLChanged; } private void OnPnLChanged() { if (_changed(Strategy.PnL)) Activate(Strategy.PnL); } protected override void DisposeManaged() { Strategy.PnLChanged -= OnPnLChanged; base.DisposeManaged(); } } private sealed class PositionManagerStrategyRule : StrategyRule<decimal> { private readonly Func<decimal, bool> _changed; public PositionManagerStrategyRule(Strategy strategy) : this(strategy, v => true) { Name = LocalizedStrings.Str1250; } public PositionManagerStrategyRule(Strategy strategy, Func<decimal, bool> changed) : base(strategy) { if (changed == null) throw new ArgumentNullException(nameof(changed)); _changed = changed; Strategy.PositionChanged += OnPositionChanged; } private void OnPositionChanged() { if (_changed(Strategy.Position)) Activate(Strategy.Position); } protected override void DisposeManaged() { Strategy.PositionChanged -= OnPositionChanged; base.DisposeManaged(); } } private sealed class NewMyTradeStrategyRule : StrategyRule<MyTrade> { public NewMyTradeStrategyRule(Strategy strategy) : base(strategy) { Name = LocalizedStrings.Str1251 + " " + strategy; Strategy.NewMyTrade += OnStrategyNewMyTrade; } private void OnStrategyNewMyTrade(MyTrade trade) { Activate(trade); } protected override void DisposeManaged() { Strategy.NewMyTrade -= OnStrategyNewMyTrade; base.DisposeManaged(); } } private sealed class OrderRegisteredStrategyRule : StrategyRule<Order> { public OrderRegisteredStrategyRule(Strategy strategy) : base(strategy) { Name = LocalizedStrings.Str1252 + " " + strategy; Strategy.OrderRegistered += Activate; Strategy.StopOrderRegistered += Activate; } protected override void DisposeManaged() { Strategy.OrderRegistered -= Activate; Strategy.StopOrderRegistered -= Activate; base.DisposeManaged(); } } private sealed class OrderChangedStrategyRule : StrategyRule<Order> { public OrderChangedStrategyRule(Strategy strategy) : base(strategy) { Name = LocalizedStrings.Str1253 + " " + strategy; Strategy.OrderChanged += Activate; Strategy.StopOrderChanged += Activate; } protected override void DisposeManaged() { Strategy.OrderChanged -= Activate; Strategy.StopOrderChanged -= Activate; base.DisposeManaged(); } } private sealed class ProcessStateChangedStrategyRule : StrategyRule<Strategy> { private readonly Func<ProcessStates, bool> _condition; public ProcessStateChangedStrategyRule(Strategy strategy, Func<ProcessStates, bool> condition) : base(strategy) { if (condition == null) throw new ArgumentNullException(nameof(condition)); _condition = condition; Strategy.ProcessStateChanged += OnProcessStateChanged; } private void OnProcessStateChanged(Strategy strategy) { if (_condition(Strategy.ProcessState)) Activate(Strategy); } protected override void DisposeManaged() { Strategy.ProcessStateChanged -= OnProcessStateChanged; base.DisposeManaged(); } } private sealed class PropertyChangedStrategyRule : StrategyRule<Strategy> { private readonly Func<Strategy, bool> _condition; public PropertyChangedStrategyRule(Strategy strategy, Func<Strategy, bool> condition) : base(strategy) { if (condition == null) throw new ArgumentNullException(nameof(condition)); _condition = condition; Strategy.PropertyChanged += OnPropertyChanged; } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { if (_condition(Strategy)) Activate(Strategy); } protected override void DisposeManaged() { Strategy.PropertyChanged -= OnPropertyChanged; base.DisposeManaged(); } } private sealed class ErrorStrategyRule : StrategyRule<Exception> { public ErrorStrategyRule(Strategy strategy) : base(strategy) { Name = strategy + LocalizedStrings.Str1254; Strategy.Error += OnError; } private void OnError(Exception error) { Activate(error); } protected override void DisposeManaged() { Strategy.Error -= OnError; base.DisposeManaged(); } } /// <summary> /// To create a rule for the event of occurrence new strategy trade. /// </summary> /// <param name="strategy">The startegy, based on which trade occurrence will be traced.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, MyTrade> WhenNewMyTrade(this Strategy strategy) { return new NewMyTradeStrategyRule(strategy); } /// <summary> /// To create a rule for event of occurrence of new strategy order. /// </summary> /// <param name="strategy">The startegy, based on which order occurrence will be traced.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, Order> WhenOrderRegistered(this Strategy strategy) { return new OrderRegisteredStrategyRule(strategy); } /// <summary> /// To create a rule for event of change of any strategy order. /// </summary> /// <param name="strategy">The startegy, based on which orders change will be traced.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, Order> WhenOrderChanged(this Strategy strategy) { return new OrderChangedStrategyRule(strategy); } /// <summary> /// To create a rule for the event of strategy position change. /// </summary> /// <param name="strategy">The startegy, based on which position change will be traced.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, decimal> WhenPositionChanged(this Strategy strategy) { return new PositionManagerStrategyRule(strategy); } /// <summary> /// To create a rule for event of position event reduction below the specified level. /// </summary> /// <param name="strategy">The startegy, based on which position change will be traced.</param> /// <param name="value">The level. If the <see cref="Unit.Type"/> type equals to <see cref="UnitTypes.Limit"/>, specified price is set. Otherwise, shift value is specified.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, decimal> WhenPositionLess(this Strategy strategy, Unit value) { if (strategy == null) throw new ArgumentNullException(nameof(strategy)); if (value == null) throw new ArgumentNullException(nameof(value)); var finishPosition = value.Type == UnitTypes.Limit ? value : strategy.Position - value; return new PositionManagerStrategyRule(strategy, pos => pos < finishPosition) { Name = LocalizedStrings.Str1255Params.Put(finishPosition) }; } /// <summary> /// To create a rule for event of position event increase above the specified level. /// </summary> /// <param name="strategy">The startegy, based on which position change will be traced.</param> /// <param name="value">The level. If the <see cref="Unit.Type"/> type equals to <see cref="UnitTypes.Limit"/>, specified price is set. Otherwise, shift value is specified.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, decimal> WhenPositionMore(this Strategy strategy, Unit value) { if (strategy == null) throw new ArgumentNullException(nameof(strategy)); if (value == null) throw new ArgumentNullException(nameof(value)); var finishPosition = value.Type == UnitTypes.Limit ? value : strategy.Position + value; return new PositionManagerStrategyRule(strategy, pos => pos > finishPosition) { Name = LocalizedStrings.Str1256Params.Put(finishPosition) }; } /// <summary> /// To create a rule for event of profit reduction below the specified level. /// </summary> /// <param name="strategy">The startegy, based on which the profit change will be traced.</param> /// <param name="value">The level. If the <see cref="Unit.Type"/> type equals to <see cref="UnitTypes.Limit"/>, specified price is set. Otherwise, shift value is specified.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, decimal> WhenPnLLess(this Strategy strategy, Unit value) { if (strategy == null) throw new ArgumentNullException(nameof(strategy)); if (value == null) throw new ArgumentNullException(nameof(value)); var finishPosition = value.Type == UnitTypes.Limit ? value : strategy.PnL - value; return new PnLManagerStrategyRule(strategy, pos => pos < finishPosition) { Name = LocalizedStrings.Str1257Params.Put(finishPosition) }; } /// <summary> /// To create a rule for event of profit increase above the specified level. /// </summary> /// <param name="strategy">The startegy, based on which the profit change will be traced.</param> /// <param name="value">The level. If the <see cref="Unit.Type"/> type equals to <see cref="UnitTypes.Limit"/>, specified price is set. Otherwise, shift value is specified.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, decimal> WhenPnLMore(this Strategy strategy, Unit value) { if (strategy == null) throw new ArgumentNullException(nameof(strategy)); if (value == null) throw new ArgumentNullException(nameof(value)); var finishPosition = value.Type == UnitTypes.Limit ? value : strategy.PnL + value; return new PnLManagerStrategyRule(strategy, pos => pos > finishPosition) { Name = LocalizedStrings.Str1258Params.Put(finishPosition) }; } /// <summary> /// To create a rule for event of profit change. /// </summary> /// <param name="strategy">The startegy, based on which the profit change will be traced.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, decimal> WhenPnLChanged(this Strategy strategy) { return new PnLManagerStrategyRule(strategy); } /// <summary> /// To create a rule for event of start of strategy operation. /// </summary> /// <param name="strategy">The startegy, based on which the start of strategy operation will be expected.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, Strategy> WhenStarted(this Strategy strategy) { return new ProcessStateChangedStrategyRule(strategy, s => s == ProcessStates.Started) { Name = strategy + LocalizedStrings.Str1259, }; } /// <summary> /// To create a rule for event of beginning of the strategy operation stop. /// </summary> /// <param name="strategy">The startegy, based on which the beginning of stop will be determined.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, Strategy> WhenStopping(this Strategy strategy) { return new ProcessStateChangedStrategyRule(strategy, s => s == ProcessStates.Stopping) { Name = strategy + LocalizedStrings.Str1260, }; } /// <summary> /// To create a rule for event full stop of strategy operation. /// </summary> /// <param name="strategy">The startegy, based on which the full stop will be expected.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, Strategy> WhenStopped(this Strategy strategy) { return new ProcessStateChangedStrategyRule(strategy, s => s == ProcessStates.Stopped) { Name = strategy + LocalizedStrings.Str1261, }; } /// <summary> /// To create a rule for event of strategy error (transition of state <see cref="Strategy.ErrorState"/> into <see cref="LogLevels.Error"/>). /// </summary> /// <param name="strategy">The startegy, based on which error will be expected.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, Exception> WhenError(this Strategy strategy) { return new ErrorStrategyRule(strategy); } /// <summary> /// To create a rule for event of strategy warning (transition of state <see cref="Strategy.ErrorState"/> into <see cref="LogLevels.Warning"/>). /// </summary> /// <param name="strategy">The startegy, based on which the warning will be expected.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, Strategy> WhenWarning(this Strategy strategy) { return new PropertyChangedStrategyRule(strategy, s => s.ErrorState == LogLevels.Warning) { Name = strategy + LocalizedStrings.Str1262, }; } #endregion #region Order actions /// <summary> /// To create an action, registering the order. /// </summary> /// <param name="rule">Rule.</param> /// <param name="order">The order to be registered.</param> /// <returns>Rule.</returns> public static IMarketRule Register(this IMarketRule rule, Order order) { if (rule == null) throw new ArgumentNullException(nameof(rule)); if (order == null) throw new ArgumentNullException(nameof(order)); return rule.Do(() => GetRuleStrategy(rule).RegisterOrder(order)); } /// <summary> /// To create an action, re-registering the order. /// </summary> /// <param name="rule">Rule.</param> /// <param name="oldOrder">The order to be re-registered.</param> /// <param name="newOrder">Information about new order.</param> /// <returns>Rule.</returns> public static IMarketRule ReRegister(this IMarketRule rule, Order oldOrder, Order newOrder) { if (rule == null) throw new ArgumentNullException(nameof(rule)); if (oldOrder == null) throw new ArgumentNullException(nameof(oldOrder)); if (newOrder == null) throw new ArgumentNullException(nameof(newOrder)); return rule.Do(() => GetRuleStrategy(rule).ReRegisterOrder(oldOrder, newOrder)); } /// <summary> /// To create an action, cancelling the order. /// </summary> /// <param name="rule">Rule.</param> /// <param name="order">The order to be cancelled.</param> /// <returns>Rule.</returns> public static IMarketRule Cancel(this IMarketRule rule, Order order) { if (rule == null) throw new ArgumentNullException(nameof(rule)); if (order == null) throw new ArgumentNullException(nameof(order)); return rule.Do(() => GetRuleStrategy(rule).CancelOrder(order)); } #endregion private static Strategy GetRuleStrategy(IMarketRule rule) { if (rule == null) throw new ArgumentNullException(nameof(rule)); var strategy = rule.Container as Strategy; if (strategy == null) throw new ArgumentException(LocalizedStrings.Str1263Params.Put(rule.Name), nameof(rule)); return strategy; } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information // // Unit tests for XmlDecryptionTransform // // Author: // Sebastien Pouliot <sebastien@ximian.com> // // Copyright (C) 2008 Novell, Inc (http://www.novell.com) // // Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. using System.IO; using System.Xml; using Xunit; namespace System.Security.Cryptography.Xml.Tests { public class UnprotectedXmlDecryptionTransform : XmlDecryptionTransform { public bool UnprotectedIsTargetElement(XmlElement inputElement, string idValue) { return base.IsTargetElement(inputElement, idValue); } public XmlNodeList UnprotectedGetInnerXml() { return base.GetInnerXml(); } } public class XmlDecryptionTransformTest { private UnprotectedXmlDecryptionTransform transform; public XmlDecryptionTransformTest() { transform = new UnprotectedXmlDecryptionTransform(); } [Fact] public void IsTargetElement_XmlElementNull() { Assert.False(transform.UnprotectedIsTargetElement(null, "value")); } [Fact] public void IsTargetElement_StringNull() { XmlDocument doc = new XmlDocument(); Assert.False(transform.UnprotectedIsTargetElement(doc.DocumentElement, null)); } [Theory] [InlineData("<a id=\"1\" />", "1", true)] [InlineData("<a ID=\"1\" />", "1", true)] [InlineData("<a Id=\"1\" />", "1", true)] [InlineData("<a iD=\"1\" />", "1", false)] [InlineData("<a id=\"1\" />", "2", false)] public void IsTargetElement_ValidXml(string xml, string id, bool expectedResult) { XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); Assert.Equal(expectedResult, transform.UnprotectedIsTargetElement(doc.DocumentElement, id)); } [Fact] public void AddExceptUri_Null() { Assert.Throws<ArgumentNullException>(() => transform.AddExceptUri(null)); } [Fact] public void EncryptedXml_NotNull() { Assert.NotNull(transform.EncryptedXml); } [Fact] public void InputTypes() { Type[] inputTypes = transform.InputTypes; Assert.Equal(2, inputTypes.Length); Assert.Contains(typeof(Stream), inputTypes); Assert.Contains(typeof(XmlDocument), inputTypes); } [Fact] public void OutputTypes() { Type[] outputTypes = transform.OutputTypes; Assert.Equal(1, outputTypes.Length); Assert.Contains(typeof(XmlDocument), outputTypes); } [Fact] public void LoadInnerXml_XmlNull() { Assert.Throws<CryptographicException>(() => transform.LoadInnerXml(null)); } [Fact] public void LoadInnerXml_XmlNoExcept() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<a />"); transform.LoadInnerXml(doc.ChildNodes); Assert.Null(transform.UnprotectedGetInnerXml()); } [Fact] public void LoadInnerXml_XmlNoUriForExcept() { XmlDocument doc = new XmlDocument(); doc.LoadXml(@"<dcrpt:Except xmlns:dcrpt=""http://www.w3.org/2002/07/decrypt#""/>"); Assert.Throws<CryptographicException>(() => transform.LoadInnerXml(doc.ChildNodes)); } [Fact] public void LoadInnerXml_XmlValidUriForExcept() { XmlDocument doc = new XmlDocument(); doc.LoadXml(@"<dcrpt:Except URI=""#item1"" xmlns:dcrpt=""http://www.w3.org/2002/07/decrypt#""/>"); transform.LoadInnerXml(doc.ChildNodes); Assert.NotNull(transform.UnprotectedGetInnerXml()); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "https://github.com/dotnet/corefx/issues/16798")] public void LoadStreamInput_CorrectXml() { XmlDocument doc = new XmlDocument(); string xml = "<root><a /><b /></root>"; doc.LoadXml(xml); using (MemoryStream memoryStream = new MemoryStream()) using (StreamWriter streamWriter = new StreamWriter(memoryStream, Text.Encoding.Unicode)) { streamWriter.Write(xml); streamWriter.Flush(); memoryStream.Position = 0; transform.LoadInput(memoryStream); XmlDocument output = (XmlDocument)transform.GetOutput(); Assert.Equal(xml, output.OuterXml); } } [Fact] public void GetOutput_WrongType() { XmlDocument doc = new XmlDocument(); string xml = "<test />"; doc.LoadXml(xml); transform.LoadInput(doc); AssertExtensions.Throws<ArgumentException>("type", () => transform.GetOutput(typeof(string))); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "https://github.com/dotnet/corefx/issues/16798")] public void GetOutput_XmlNoEncryptedData() { XmlDocument doc = new XmlDocument(); string xml = "<test />"; doc.LoadXml(xml); transform.LoadInput(doc); XmlDocument transformedDocument = (XmlDocument)transform.GetOutput(typeof(XmlDocument)); Assert.Equal(xml, transformedDocument.OuterXml); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "https://github.com/dotnet/corefx/issues/16798")] public void GetOutput_XmlWithEncryptedData() { XmlDocument doc = new XmlDocument(); string xml = "<root><a /><b /><c>To Be Encrypted</c><d /></root>"; doc.LoadXml(xml); XmlDocument transformedDocument = GetTransformedOutput(doc, "c"); Assert.NotNull(transformedDocument); Assert.Equal(xml, transformedDocument.OuterXml); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "https://github.com/dotnet/corefx/issues/16798")] public void GetOutput_XmlWithEncryptedDataInRoot() { XmlDocument doc = new XmlDocument(); string xml = "<root>To Be Encrypted</root>"; doc.LoadXml(xml); XmlDocument transformedDocument = GetTransformedOutput(doc, "//root"); Assert.NotNull(transformedDocument); Assert.Equal(xml, transformedDocument.OuterXml); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "https://github.com/dotnet/corefx/issues/16798")] public void GetOutput_XmlWithEncryptedDataAndExcept() { XmlDocument doc = new XmlDocument(); string xml = "<root><a /><b /><c>To Be Encrypted</c><d /></root>"; doc.LoadXml(xml); transform.AddExceptUri("#_notfound"); transform.AddExceptUri("#_0"); XmlDocument transformedDocument = GetTransformedOutput(doc, "c"); XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(doc.NameTable); xmlNamespaceManager.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); Assert.NotNull(transformedDocument.DocumentElement.SelectSingleNode("//enc:EncryptedData", xmlNamespaceManager)); Assert.NotEqual(xml, transformedDocument.OuterXml); } private XmlDocument GetTransformedOutput(XmlDocument doc, string nodeToEncrypt) { using (var aesAlgo = Aes.Create()) { var encryptedXml = new EncryptedXml(); encryptedXml.AddKeyNameMapping("aes", aesAlgo); XmlElement elementToEncrypt = (XmlElement)doc.DocumentElement.SelectSingleNode(nodeToEncrypt); EncryptedData encryptedData = encryptedXml.Encrypt(elementToEncrypt, "aes"); EncryptedXml.ReplaceElement(elementToEncrypt, encryptedData, false); XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(doc.NameTable); xmlNamespaceManager.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); XmlElement encryptedNode = (XmlElement)doc.DocumentElement.SelectSingleNode("//enc:EncryptedData", xmlNamespaceManager); encryptedNode.SetAttribute("ID", "#_0"); transform.LoadInput(doc); transform.EncryptedXml = encryptedXml; XmlDocument transformedDocument = (XmlDocument)transform.GetOutput(); transform.EncryptedXml = null; return transformedDocument; } } } }
using UnityEngine; using System.Collections.Generic; using System.Linq; using FluidTest1; public class FluidSimulation : MonoBehaviour { public const int MAX_PARTICLES = 1000; public const int MAX_NEIGHBORS = 75; public const float RADIUS = 0.6f; public const float VISCOSITY = 0.004f; public const float IDEAL_RADIUS = 50f; public const float MULTIPLIER = IDEAL_RADIUS / RADIUS; public const float IDEAL_RADIUS_SQ = IDEAL_RADIUS * IDEAL_RADIUS; public const float CELL_SIZE = 0.5f; private int _numActiveParticles = 0; private MyParticle[] _liquid; private List<int> _activeParticles; private Vector2[] _delta; private Vector2[] _scaledPositions; private Vector2[] _scaledVelocities; private Dictionary<int, Dictionary<int, List<int>>> _grid; private GameObject _sprite; public void Init (GameObject sprite) { _sprite = sprite; _activeParticles = new List<int>(MAX_PARTICLES); _liquid = new MyParticle[MAX_PARTICLES]; for (int i = 0; i < MAX_PARTICLES; i++) { _liquid[i] = new MyParticle(Vector2.zero, Vector2.zero, false); _liquid[i].index = i; } _delta = new Vector2[MAX_PARTICLES]; _scaledPositions = new Vector2[MAX_PARTICLES]; _scaledVelocities = new Vector2[MAX_PARTICLES]; _grid = new Dictionary<int, Dictionary<int, List<int>>>(); } public void createParticle(Vector3 screenPosition, int numParticlesToSpawn = 4) { IEnumerable<MyParticle> inactiveParticles = from particle in _liquid where particle.alive == false select particle; inactiveParticles = inactiveParticles.Take(numParticlesToSpawn); foreach (MyParticle particle in inactiveParticles) { if (_numActiveParticles < MAX_PARTICLES) { Vector2 jitter = new Vector2(Random.Range(-1f, 1f), Random.Range(-0.5f, 0.5f)); particle.position = new Vector2(screenPosition.x, screenPosition.y) + jitter; particle.velocity = Vector2.zero; particle.ci = getGridX(particle.position.x); particle.cj = getGridY(particle.position.y); if(particle.sprite == null) { GameObject newSprite = Instantiate(_sprite) as GameObject; newSprite.transform.parent = _sprite.transform.parent; particle.Visualize(newSprite); Vector3 worldPosition = Camera.main.ScreenToWorldPoint(new Vector3(particle.position.x, particle.position.y, 0)); worldPosition.Scale(new Vector3(1, 1, 0)); particle.sprite.transform.position = worldPosition; } particle.alive = true; // Create grid cell if necessary if (!_grid.ContainsKey(particle.ci)) _grid[particle.ci] = new Dictionary<int, List<int>>(); if (!_grid[particle.ci].ContainsKey(particle.cj)) _grid[particle.ci][particle.cj] = new List<int>(); _grid[particle.ci][particle.cj].Add(particle.index); _activeParticles.Add(particle.index); _numActiveParticles++; } } } public void applyLiquidConstraints(float deltaTime) { // Prepare simulation for (int i = 0; i < _numActiveParticles; i++) { int index = _activeParticles[i]; MyParticle particle = _liquid[index]; // Find neighbors findNeighbors(particle); // Scale positions and velocities _scaledPositions[index] = particle.position * MULTIPLIER; _scaledVelocities[index] = particle.velocity * MULTIPLIER; // Reset deltas _delta[index] = Vector2.zero; // Calculate pressure float p = 0.0f; float pnear = 0.0f; for (int a = 0; a < particle.neighborCount; a++) { Vector2 relativePosition = _scaledPositions[particle.neighbors[a]] - _scaledPositions[index]; float distanceSq = relativePosition.sqrMagnitude; //within idealRad check if (distanceSq < IDEAL_RADIUS_SQ) { particle.distances[a] = (float)Mathf.Sqrt(distanceSq); //if (particle.distances[a] < Settings.EPSILON) particle.distances[a] = IDEAL_RADIUS - .01f; float oneminusq = 1.0f - (particle.distances[a] / IDEAL_RADIUS); p = (p + oneminusq * oneminusq); pnear = (pnear + oneminusq * oneminusq * oneminusq); } else { particle.distances[a] = float.MaxValue; } } // Apply forces float pressure = (p - 5f) / 2.0f; //normal pressure term float presnear = pnear / 2.0f; //near particles term Vector2 change = Vector2.zero; for (int a = 0; a < particle.neighborCount; a++) { Vector2 relativePosition = _scaledPositions[particle.neighbors[a]] - _scaledPositions[index]; if (particle.distances[a] < IDEAL_RADIUS) { float q = particle.distances[a] / IDEAL_RADIUS; float oneminusq = 1.0f - q; float factor = oneminusq * (pressure + presnear * oneminusq) / (2.0F * particle.distances[a]); Vector2 d = relativePosition * factor; Vector2 relativeVelocity = _scaledVelocities[particle.neighbors[a]] - _scaledVelocities[index]; factor = VISCOSITY * oneminusq * deltaTime; d -= relativeVelocity * factor; _delta[particle.neighbors[a]] += d; change -= d; } } _delta[index] += change; } // Move particles for (int i = 0; i < _numActiveParticles; i++) { int index = _activeParticles[i]; MyParticle particle = _liquid[index]; particle.position += _delta[index] / MULTIPLIER; particle.velocity += _delta[index] / (MULTIPLIER * deltaTime); Vector3 worldPosition = Camera.main.ScreenToWorldPoint(new Vector3(particle.position.x, particle.position.y, 0)); worldPosition.Scale(new Vector3(1, 1, 0)); particle.sprite.transform.position = worldPosition; // Update particle cell int x = getGridX(particle.position.x); int y = getGridY(particle.position.y); if (particle.ci == x && particle.cj == y) { continue; } else { _grid[particle.ci][particle.cj].Remove(index); if (_grid[particle.ci][particle.cj].Count == 0) { _grid[particle.ci].Remove(particle.cj); if (_grid[particle.ci].Count == 0) { _grid.Remove(particle.ci); } } if (!_grid.ContainsKey(x)) _grid[x] = new Dictionary<int, List<int>>(); if (!_grid[x].ContainsKey(y)) _grid[x][y] = new List<int>(20); _grid[x][y].Add(index); particle.ci = x; particle.cj = y; } } } private void findNeighbors(MyParticle particle) { particle.neighborCount = 0; Dictionary<int, List<int>> gridX; List<int> gridY; for (int nx = -1; nx < 2; nx++) { for (int ny = -1; ny < 2; ny++) { int x = particle.ci + nx; int y = particle.cj + ny; if (_grid.TryGetValue(x, out gridX) && gridX.TryGetValue(y, out gridY)) { for (int a = 0; a < gridY.Count; a++) { if (gridY[a] != particle.index) { particle.neighbors[particle.neighborCount] = gridY[a]; particle.neighborCount++; if (particle.neighborCount >= MAX_NEIGHBORS) return; } } } } } } private int getGridX(float x) { return (int)Mathf.Floor(x / CELL_SIZE); } private int getGridY(float y) { return (int)Mathf.Floor(y / CELL_SIZE); } }
using System; using System.Collections; using System.Collections.Generic; using DotVVM.Framework.Compilation; using DotVVM.Framework.Compilation.Javascript; using DotVVM.Framework.Controls; using DotVVM.Framework.Binding.Properties; using DotVVM.Framework.Compilation.Javascript.Ast; using System.Reflection; using DotVVM.Framework.Utils; using System.Linq; using System.Linq.Expressions; using DotVVM.Framework.Compilation.ControlTree; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; namespace DotVVM.Framework.Binding.Expressions { /// <summary> /// A binding that gets the value from a viewmodel property. /// </summary> [BindingCompilationRequirements( required: new[] { typeof(BindingDelegate), typeof(ResultTypeBindingProperty), typeof(KnockoutExpressionBindingProperty) }, optional: new[] { typeof(BindingUpdateDelegate) })] [Options] public class ValueBindingExpression : BindingExpression, IUpdatableValueBinding, IValueBinding { public ValueBindingExpression(BindingCompilationService service, IEnumerable<object?> properties) : base(service, properties) { AddNullResolvers(); } private protected MaybePropValue<KnockoutExpressionBindingProperty> knockoutExpressions; private protected override void StoreProperty(object p) { if (p is KnockoutExpressionBindingProperty knockoutExpressions) this.knockoutExpressions.SetValue(new(knockoutExpressions)); else base.StoreProperty(p); } public override object? GetProperty(Type type, ErrorHandlingMode errorMode = ErrorHandlingMode.ThrowException) { if (type == typeof(KnockoutExpressionBindingProperty)) return knockoutExpressions.GetValue(this).GetValue(errorMode, this, type); return base.GetProperty(type, errorMode); } private protected override IEnumerable<object?> GetOutOfDictionaryProperties() => base.GetOutOfDictionaryProperties().Concat(new object?[] { knockoutExpressions.Value.Value }); public BindingDelegate BindingDelegate => this.bindingDelegate.GetValueOrThrow(this); public BindingUpdateDelegate UpdateDelegate => this.updateDelegate.GetValueOrThrow(this); public KnockoutExpressionBindingProperty KnockoutExpressionBindingProperty => this.knockoutExpressions.GetValueOrThrow(this); public ParametrizedCode KnockoutExpression => KnockoutExpressionBindingProperty.Code; public ParametrizedCode UnwrappedKnockoutExpression => KnockoutExpressionBindingProperty.UnwrappedCode; public ParametrizedCode WrappedKnockoutExpression => KnockoutExpressionBindingProperty.WrappedCode; public Type ResultType => this.resultType.GetValueOrThrow(this).Type; public class OptionsAttribute : BindingCompilationOptionsAttribute { public override IEnumerable<Delegate> GetResolvers() => new Delegate[] { new Func<KnockoutJsExpressionBindingProperty, RequiredRuntimeResourcesBindingProperty>(js => { var resources = js.Expression .DescendantNodesAndSelf() .Select(n => n.Annotation<RequiredRuntimeResourcesBindingProperty>()) .Where(n => n != null) .SelectMany(n => n!.Resources) .ToImmutableArray(); return resources.Length == 0 ? RequiredRuntimeResourcesBindingProperty.Empty : new RequiredRuntimeResourcesBindingProperty(resources); }), new Func<KnockoutJsExpressionBindingProperty, GlobalizeResourceBindingProperty?>(js => { var isGlobalizeRequired = js.Expression.DescendantNodesAndSelf() .Any(n => n.Annotation<GlobalizeResourceBindingProperty>() != null); if (isGlobalizeRequired) { return new GlobalizeResourceBindingProperty(); } return null; }) }; } #region Helpers /// Creates binding {value: _this} for a specific data context. Note that the result is cached (non-deterministically, using the <see cref="DotVVM.Framework.Runtime.Caching.IDotvvmCacheAdapter" />) public static ValueBindingExpression<T> CreateThisBinding<T>(BindingCompilationService service, DataContextStack dataContext) => service.Cache.CreateCachedBinding("ValueBindingExpression.ThisBinding", new [] { dataContext }, () => CreateBinding<T>(service, o => (T)o[0]!, dataContext)); /// Crates a new value binding expression from the specified .NET delegate and Javascript expression. Note that this operation is not very cheap and the result is not cached. public static ValueBindingExpression<T> CreateBinding<T>(BindingCompilationService service, Func<object?[], T> func, JsExpression expression, DataContextStack? dataContext = null) => new ValueBindingExpression<T>(service, new object?[] { new BindingDelegate((o, c) => func(o)), new ResultTypeBindingProperty(typeof(T)), new KnockoutJsExpressionBindingProperty(expression), dataContext }); /// Crates a new value binding expression from the specified .NET delegate and Javascript expression. Note that this operation is not very cheap and the result is not cached. public static ValueBindingExpression<T> CreateBinding<T>(BindingCompilationService service, Func<object?[], T> func, ParametrizedCode expression, DataContextStack? dataContext = null) => new ValueBindingExpression<T>(service, new object?[] { new BindingDelegate((o, c) => func(o)), new ResultTypeBindingProperty(typeof(T)), new KnockoutExpressionBindingProperty(expression, expression, expression), dataContext }); /// Crates a new value binding expression from the specified Linq.Expression. Note that this operation is quite expansive and the result is not cached (you are supposed to do it and NOT invoke this function for every request). public static ValueBindingExpression<T> CreateBinding<T>(BindingCompilationService service, Expression<Func<object?[], T>> expr, DataContextStack? dataContext) { var visitor = new ViewModelAccessReplacer(expr.Parameters.Single()); var expression = visitor.Visit(expr.Body); dataContext = dataContext ?? visitor.GetDataContext(); visitor.ValidateDataContext(dataContext); return new ValueBindingExpression<T>(service, new object?[] { new ParsedExpressionBindingProperty(BindingHelper.AnnotateStandardContextParams(expression, dataContext).OptimizeConstants()), new ResultTypeBindingProperty(typeof(T)), dataContext }); } class ViewModelAccessReplacer : ExpressionVisitor { private readonly ParameterExpression vmParameter; public ViewModelAccessReplacer(ParameterExpression vmParameter) { this.vmParameter = vmParameter; } private List<Type?> VmTypes { get; set; } = new List<Type?>(); public DataContextStack GetDataContext() { DataContextStack? c = null; foreach (var vm in VmTypes) { c = DataContextStack.Create(vm ?? typeof(object), c); } return c.NotNull(); } public void ValidateDataContext(DataContextStack? dataContext) { for (int i = 0; i < VmTypes.Count; i++, dataContext = dataContext.Parent) { var t = VmTypes[i]; if (dataContext == null) throw new Exception($"Cannot access _parent{i}, it does not exist in the data context."); if (t != null && !t.IsAssignableFrom(dataContext.DataContextType)) throw new Exception($"_parent{i} does not have type '{t}' but '{dataContext.DataContextType}'."); } } [return: NotNullIfNotNull("node")] public override Expression? Visit(Expression? node) { if (node is null) return null; if (node.NodeType == ExpressionType.Convert && node is UnaryExpression unary && unary.Operand.NodeType == ExpressionType.ArrayIndex && unary.Operand is BinaryExpression indexer && indexer.Right is ConstantExpression indexConstant && indexer.Left == vmParameter) { int index = (int)indexConstant.Value!; while (VmTypes.Count <= index) VmTypes.Add(null); if (VmTypes[index]?.IsAssignableFrom(unary.Type) != true) { if (VmTypes[index] == null || unary.Type.IsAssignableFrom(VmTypes[index])) VmTypes[index] = unary.Type; else throw new Exception("Unsatisfiable view model type constraint"); } return Expression.Parameter(unary.Type, "_parent" + index); } if (node == vmParameter) throw new NotSupportedException(); return base.Visit(node); } } public IValueBinding GetListIndexer() { return (IValueBinding)this.GetProperty<DataSourceCurrentElementBinding>().Binding; } #endregion } public class ValueBindingExpression<T> : ValueBindingExpression, IValueBinding<T>, IUpdatableValueBinding<T> { public new BindingDelegate<T> BindingDelegate => base.BindingDelegate.ToGeneric<T>(); public new BindingUpdateDelegate<T> UpdateDelegate => base.UpdateDelegate.ToGeneric<T>(); public ValueBindingExpression(BindingCompilationService service, IEnumerable<object?> properties) : base(service, properties) { } } }
// 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; /// <summary> /// System.Byte.Parse(System.String) /// </summary> public class ByteParse1 { public static int Main(string[] args) { ByteParse1 parse1 = new ByteParse1(); TestLibrary.TestFramework.BeginTestCase("Testing System.Byte.Parse(System.String)..."); if (parse1.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("[Negtive]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; retVal = NegTest5() && retVal; retVal = NegTest6() && retVal; retVal = NegTest7() && retVal; return retVal; } public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Verify byteString is between Byte.MinValue and Byte.MaxValue..."); try { string byteString = "99"; Byte myByte = Byte.Parse(byteString); if (myByte != 99) { TestLibrary.TestFramework.LogError("001","The value should be equal to byteString.ToInt..."); } } catch (Exception e) { TestLibrary.TestFramework.LogError("002","Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Verify byteString contains +..."); try { string byteString = "+99"; Byte myByte = Byte.Parse(byteString); if (myByte != 99) { TestLibrary.TestFramework.LogError("003","The value should be equal to byteString.ToInt..."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004","Unexcepted exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Verify byteString is equal to Byte.MaxValue..."); try { string byteString = "255"; Byte myByte = Byte.Parse(byteString); if (myByte != 255) { TestLibrary.TestFramework.LogError("005", "byteString should be equal to Byte.MaxValue!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Verify byteString is equal to Byte.MinValue..."); try { string byteString = "0"; Byte myByte = Byte.Parse(byteString); if (myByte != 0) { TestLibrary.TestFramework.LogError("007", "byteString should be equal to Byte.MinValue!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Verify OverFlowException is thrown when byteString is greater than Byte.MaxValue..."); try { string byteString = "256"; Byte myByte = Byte.Parse(byteString); TestLibrary.TestFramework.LogError("009","No exception occurs!"); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Verify OverFlowException is thrown when byteString is less than Byte.MinValue..."); try { string byteString = "-1"; Byte myByte = Byte.Parse(byteString); TestLibrary.TestFramework.LogError("011","No exception occurs!"); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("012","Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Verify ArgumentNullException occurs when byteString is null..."); try { string byteString = null; Byte myByte = Byte.Parse(byteString); TestLibrary.TestFramework.LogError("013", "No exception occurs!"); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("014","Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Verify byteString is between Byte.MaxValue and Byte.MinValue and contains plus..."); try { string byteString = "plus222"; Byte myByte = Byte.Parse(byteString); TestLibrary.TestFramework.LogError("015", "No exception occurs!"); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("016", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool NegTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Verify byteString contains underline..."); try { string byteString = "1_2_3"; Byte myByte = Byte.Parse(byteString); TestLibrary.TestFramework.LogError("017", "No exception occurs!"); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("018", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool NegTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Verify byteString contains only characters..."); try { string byteString = "hello"; Byte myByte = Byte.Parse(byteString); TestLibrary.TestFramework.LogError("017", "No exception occurs!"); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("018", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool NegTest7() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Verify byteString is an empty string..."); try { string byteString = ""; Byte myByte = Byte.Parse(byteString); TestLibrary.TestFramework.LogError("017", "No exception occurs!"); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("018", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } }
//Copyright 2017 by Josip Medved <jmedved@jmedved.com> (www.medo64.com) MIT License //2018-11-25: Refactored which file gets used if application is not installed. //2017-11-05: Suppress exception on UnauthorizedAccessException. //2017-10-09: Support for /opt installation on Linux. //2017-04-29: Added IsAssumedInstalled property. // Added Reset and DeleteAll methods. //2017-04-26: Renamed from Properties. // Added \0 escape sequence. // Fixed alignment issues. //2017-04-17: First version. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Text; namespace Medo.Configuration { /// <summary> /// Provides cached access to reading and writing settings. /// This class is thread-safe. /// </summary> /// <remarks> /// File name is the same as name of the &lt;executable&gt;.cfg under windows or .&lt;executable&gt; under Linux. /// File format is as follows: /// * hash characters (#) denotes comment. /// * key and value are colon (:) separated although equals (=) is also supported. /// * backslash (\) is used for escaping. /// </remarks> public static class Config { /// <summary> /// Returns the value for the specified key. /// </summary> /// <param name="key">Key.</param> /// <param name="defaultValue">The value to return if the key does not exist.</param> /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static string Read(string key, string defaultValue) { key = key?.Trim() ?? throw new ArgumentNullException(nameof(key), "Key cannot be null."); if (key.Length == 0) { throw new ArgumentOutOfRangeException(nameof(key), "Key cannot be empty."); } lock (SyncReadWrite) { if (!IsLoaded) { Load(); } if (OverridePropertiesFile != null) { return OverridePropertiesFile.ReadOne(key) ?? DefaultPropertiesFile.ReadOne(key) ?? defaultValue; } else { return DefaultPropertiesFile.ReadOne(key) ?? defaultValue; } } } /// <summary> /// Returns all the values for the specified key. /// </summary> /// <param name="key">Key.</param> /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static IEnumerable<string> Read(string key) { key = key?.Trim() ?? throw new ArgumentNullException(nameof(key), "Key cannot be null."); if (key.Length == 0) { throw new ArgumentOutOfRangeException(nameof(key), "Key cannot be empty."); } lock (SyncReadWrite) { if (!IsLoaded) { Load(); } if (OverridePropertiesFile != null) { var list = new List<string>(OverridePropertiesFile.ReadMany(key)); if (list.Count > 0) { return list; } } return DefaultPropertiesFile.ReadMany(key); } } /// <summary> /// Returns the value for the specified key. /// </summary> /// <param name="key">Key.</param> /// <param name="defaultValue">The value to return if the key does not exist.</param> /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static bool Read(string key, bool defaultValue) { if (Read(key, null) is string value) { if (bool.TryParse(value, out var result)) { return result; } else if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var resultInt)) { return (resultInt != 0); } } return defaultValue; } /// <summary> /// Returns the value for the specified key. /// </summary> /// <param name="key">Key.</param> /// <param name="defaultValue">The value to return if the key does not exist.</param> /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static int Read(string key, int defaultValue) { if (Read(key, null) is string value) { if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return result; } } return defaultValue; } /// <summary> /// Returns the value for the specified key. /// </summary> /// <param name="key">Key.</param> /// <param name="defaultValue">The value to return if the key does not exist.</param> /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static long Read(string key, long defaultValue) { if (Read(key, null) is string value) { if (long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return result; } } return defaultValue; } /// <summary> /// Returns the value for the specified key. /// </summary> /// <param name="key">Key.</param> /// <param name="defaultValue">The value to return if the key does not exist.</param> /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static double Read(string key, double defaultValue) { if (Read(key, null) is string value) { if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { return result; } } return defaultValue; } /// <summary> /// Writes the value for the specified key. /// If the specified key does not exist, it is created. /// </summary> /// <param name="key">Key.</param> /// <param name="value">The value to write.</param> /// <exception cref="ArgumentNullException">Key cannot be null. -or- Value cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static void Write(string key, string value) { key = key?.Trim() ?? throw new ArgumentNullException(nameof(key), "Key cannot be null."); if (key.Length == 0) { throw new ArgumentOutOfRangeException(nameof(key), "Key cannot be empty."); } if (value == null) { throw new ArgumentNullException(nameof(key), "Value cannot be null."); } lock (SyncReadWrite) { if (!IsLoaded) { Load(); } DefaultPropertiesFile.WriteOne(key, value); if (ImmediateSave) { Save(); } } } /// <summary> /// Writes the values for the specified key. /// If the specified key does not exist, it is created. /// If value is null or empty, key is deleted. /// </summary> /// <param name="key">Key.</param> /// <param name="value">The value to write.</param> /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static void Write(string key, IEnumerable<string> value) { key = key?.Trim() ?? throw new ArgumentNullException(nameof(key), "Key cannot be null."); if (key.Length == 0) { throw new ArgumentOutOfRangeException(nameof(key), "Key cannot be empty."); } lock (SyncReadWrite) { if (!IsLoaded) { Load(); } DefaultPropertiesFile.WriteMany(key, value); if (ImmediateSave) { Save(); } } } /// <summary> /// Writes the value for the specified key. /// If the specified key does not exist, it is created. /// </summary> /// <param name="key">Key.</param> /// <param name="value">The value to write.</param>4 /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static void Write(string key, bool value) { Write(key, value ? "true" : "false"); //not using ToString() because it would capitalize first letter } /// <summary> /// Writes the value for the specified key. /// If the specified key does not exist, it is created. /// </summary> /// <param name="key">Key.</param> /// <param name="value">The value to write.</param>4 /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static void Write(string key, int value) { Write(key, value.ToString(CultureInfo.InvariantCulture)); } /// <summary> /// Writes the value for the specified key. /// If the specified key does not exist, it is created. /// </summary> /// <param name="key">Key.</param> /// <param name="value">The value to write.</param>4 /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static void Write(string key, long value) { Write(key, value.ToString(CultureInfo.InvariantCulture)); } /// <summary> /// Writes the value for the specified key. /// If the specified key does not exist, it is created. /// </summary> /// <param name="key">Key.</param> /// <param name="value">The value to write.</param>4 /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static void Write(string key, double value) { Write(key, value.ToString("r", CultureInfo.InvariantCulture)); } /// <summary> /// Deletes key. /// </summary> /// <param name="key">Key.</param> /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static void Delete(string key) { key = key?.Trim() ?? throw new ArgumentNullException(nameof(key), "Key cannot be null."); if (key.Length == 0) { throw new ArgumentOutOfRangeException(nameof(key), "Key cannot be empty."); } lock (SyncReadWrite) { if (!IsLoaded) { Load(); } DefaultPropertiesFile.Delete(key); if (ImmediateSave) { Save(); } } } #region Loading and saving private static bool IsInitialized { get; set; } private static bool IsLoaded { get; set; } private static PropertiesFile DefaultPropertiesFile; private static PropertiesFile OverridePropertiesFile; private static readonly object SyncReadWrite = new object(); private static bool _isAssumedInstalled; /// <summary> /// Gets/sets if application is assumed to be installed. /// Application is considered installed if it is located in Program Files directory (or opt). /// Setting value to true before loading files will force assumption of installation status. /// </summary> public static bool IsAssumedInstalled { get { lock (SyncReadWrite) { if (!IsInitialized) { Initialize(); } return _isAssumedInstalled; } } set { if (IsInitialized) { throw new InvalidOperationException("Cannot set value once config has been loaded."); } _isAssumedInstalled = value; } } private static string _fileName; /// <summary> /// Gets/sets the name of the file used for settings. /// Settings are always written to this file but reading might be done from override file first /// If executable is located under Program Files, properties file will be in Application Data. /// If executable is located in some other directory, a local file will be used. /// </summary> /// <exception cref="ArgumentNullException">Value cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Value is not a valid path.</exception> public static string FileName { get { lock (SyncReadWrite) { if (!IsInitialized) { Initialize(); } return _fileName; } } set { lock (SyncReadWrite) { if (!IsInitialized) { Initialize(); } if (value == null) { throw new ArgumentNullException(nameof(value), "Value cannot be null."); } else if (value.IndexOfAny(Path.GetInvalidPathChars()) >= 0) { throw new ArgumentOutOfRangeException(nameof(value), "Value is not a valid path."); } else { _fileName = value; IsLoaded = false; //force loading } } } } private static string _overrideFileName; /// <summary> /// Gets/sets the name of the file used for settings override. /// Settings stored in this file are always read first and never written. /// If executable is located under Program Files, override properties file will be in executable's directory. /// If executable is located in some other directory, no override file will be used. /// If application is installed under /opt on Linux, override config file will be located under /etc/opt. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Value is not a valid path.</exception> public static string OverrideFileName { get { lock (SyncReadWrite) { if (!IsInitialized) { Initialize(); } return _overrideFileName; } } set { lock (SyncReadWrite) { if (!IsInitialized) { Initialize(); } if ((value != null) && (value.IndexOfAny(Path.GetInvalidPathChars()) >= 0)) { throw new ArgumentOutOfRangeException(nameof(value), "Value is not a valid path."); } else { _overrideFileName = value; IsLoaded = false; } } } } /// <summary> /// Loads all settings from a file. /// Returns true if file was found. /// </summary> /// <param name="fileName">File name to use.</param> public static bool Load(string fileName) { lock (SyncReadWrite) { FileName = fileName; OverrideFileName = null; return Load(); } } /// <summary> /// Loads all settings from a file. /// Returns true if file was found. /// </summary> public static bool Load() { var sw = Stopwatch.StartNew(); try { lock (SyncReadWrite) { OverridePropertiesFile = (OverrideFileName != null) ? new PropertiesFile(OverrideFileName, isOverride: true) : null; DefaultPropertiesFile = new PropertiesFile(FileName); IsLoaded = true; return DefaultPropertiesFile.FileExists; } } finally { Debug.WriteLine("[Settings] Primary: " + FileName); Debug.WriteLine("[Settings] Override: " + OverrideFileName); Debug.WriteLine("[Settings] Load completed in " + sw.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture) + " milliseconds."); } } /// <summary> /// Saves all settings to a file. /// Returns true if action is successful. /// </summary> public static bool Save() { var sw = Stopwatch.StartNew(); try { lock (SyncReadWrite) { if (!IsLoaded) { Load(); } return DefaultPropertiesFile.Save(); } } finally { Debug.WriteLine("[Settings] Save completed in " + sw.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture) + " milliseconds."); } } /// <summary> /// Deletes all settings. /// </summary> public static void DeleteAll() { lock (SyncReadWrite) { if (!IsLoaded) { Load(); } DefaultPropertiesFile.DeleteAll(); if (ImmediateSave) { Save(); } } Debug.WriteLine("[Settings] Settings deleted."); } /// <summary> /// Resets configuration. This includes file names and installation status. /// </summary> public static void Reset() { lock (SyncReadWrite) { _isAssumedInstalled = false; IsLoaded = false; IsInitialized = false; } } /// <summary> /// Gets/sets if setting is saved immediately. /// </summary> public static bool ImmediateSave { get; set; } = true; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "Lower case form of application name is only used to generate properties file name which is not compared against other text.")] private static void Initialize() { var assembly = Assembly.GetEntryAssembly(); string companyValue = null; string productValue = null; string titleValue = null; #if NETSTANDARD1_6 var attributes = assembly.GetCustomAttributes(); #else var attributes = assembly.GetCustomAttributes(true); #endif foreach (var attribute in attributes) { if (attribute is AssemblyCompanyAttribute companyAttribute) { companyValue = companyAttribute.Company.Trim(); } if (attribute is AssemblyProductAttribute productAttribute) { productValue = productAttribute.Product.Trim(); } if (attribute is AssemblyTitleAttribute titleAttribute) { titleValue = titleAttribute.Title.Trim(); } } var company = companyValue ?? ""; var application = productValue ?? titleValue ?? assembly.GetName().Name; var executablePath = assembly.Location; var baseFileName = IsOSWindows ? application + ".cfg" : "." + application.ToLowerInvariant(); var userFilePath = IsOSWindows ? Path.Combine(Environment.GetEnvironmentVariable("AppData"), company, application, baseFileName) : Path.Combine(Environment.GetEnvironmentVariable("HOME") ?? "~", baseFileName); var localFilePath = Path.Combine(Path.GetDirectoryName(executablePath), baseFileName); if (IsOSWindows) { #if NETSTANDARD1_6 var isPF = executablePath.StartsWith(AddDirectorySuffixIfNeeded(Environment.GetEnvironmentVariable("ProgramFiles")), StringComparison.OrdinalIgnoreCase); var isPF32 = executablePath.StartsWith(AddDirectorySuffixIfNeeded(Environment.GetEnvironmentVariable("ProgramFiles(x86)")), StringComparison.OrdinalIgnoreCase); var isPF64 = executablePath.StartsWith(AddDirectorySuffixIfNeeded(Environment.GetEnvironmentVariable("ProgramW6432")), StringComparison.OrdinalIgnoreCase); var isUserPF = executablePath.StartsWith(AddDirectorySuffixIfNeeded(Path.Combine(Environment.GetEnvironmentVariable("LOCALAPPDATA"), "Programs")), StringComparison.OrdinalIgnoreCase); #else var isPF = executablePath.StartsWith(AddDirectorySuffixIfNeeded(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)), StringComparison.OrdinalIgnoreCase); var isPF32 = executablePath.StartsWith(AddDirectorySuffixIfNeeded(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)), StringComparison.OrdinalIgnoreCase); var isPF64 = executablePath.StartsWith(AddDirectorySuffixIfNeeded(Environment.GetEnvironmentVariable("ProgramW6432")), StringComparison.OrdinalIgnoreCase); var isUserPF = executablePath.StartsWith(AddDirectorySuffixIfNeeded(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs")), StringComparison.OrdinalIgnoreCase); #endif var isInstalled = isPF || isPF32 || isPF64 || isUserPF || _isAssumedInstalled; if (isInstalled) { //if in program files, assume user config is first, use local file as override _isAssumedInstalled = true; _fileName = userFilePath; _overrideFileName = File.Exists(localFilePath) ? localFilePath : null; } else { //if outside of program files, assume local file only _isAssumedInstalled = false; _fileName = localFilePath; _overrideFileName = null; } } else { //Linux var isOpt = executablePath.StartsWith(Path.DirectorySeparatorChar + "opt" + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase); var isBin = executablePath.StartsWith(Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase); var isUsrBin = executablePath.StartsWith(Path.DirectorySeparatorChar + "usr" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase); var isInstalled = isOpt || isBin || isUsrBin || _isAssumedInstalled; if (isInstalled) { _isAssumedInstalled = true; _fileName = userFilePath; if (isOpt) { //change override file location to /etc/opt/<app>/<app>.cfg var globalFilePath = Path.DirectorySeparatorChar + "etc" + Path.Combine(Path.GetDirectoryName(executablePath), application.ToLowerInvariant() + ".conf"); _overrideFileName = File.Exists(globalFilePath) ? globalFilePath : null; } else { _overrideFileName = File.Exists(localFilePath) ? localFilePath : null; } } else { //if outside of program files, assume local file only _isAssumedInstalled = false; _fileName = localFilePath; _overrideFileName = null; } } IsInitialized = true; } private static string AddDirectorySuffixIfNeeded(string path) { if (string.IsNullOrEmpty(path)) { return ""; } path = path.Trim(); if (path.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)) { return path; } return path + Path.DirectorySeparatorChar; } #if NETSTANDARD2_0 || NETSTANDARD1_6 private static bool IsOSWindows => System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows); #else private static bool IsOSWindows => (Path.DirectorySeparatorChar == '\\'); //not fool-proof but good enough #endif #region PropertiesFile private class PropertiesFile { private static readonly Encoding Utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); private static readonly StringComparer KeyComparer = StringComparer.OrdinalIgnoreCase; private static readonly StringComparison KeyComparison = StringComparison.OrdinalIgnoreCase; private readonly string FileName; private readonly string LineEnding; private readonly List<LineData> Lines = new List<LineData>(); public PropertiesFile(string fileName, bool isOverride = false) { FileName = fileName; string fileContent = null; try { fileContent = File.ReadAllText(fileName, Utf8); } catch (IOException) { } catch (UnauthorizedAccessException) { } string lineEnding = null; if (fileContent != null) { var currLine = new StringBuilder(); var lineEndingDetermined = false; char prevChar = '\0'; foreach (var ch in fileContent) { if (ch == '\n') { if (prevChar == '\r') { //CRLF pair if (!lineEndingDetermined) { lineEnding = "\r\n"; lineEndingDetermined = true; } } else { if (!lineEndingDetermined) { lineEnding = "\n"; lineEndingDetermined = true; } processLine(currLine); currLine.Clear(); } } else if (ch == '\r') { processLine(currLine); if (!lineEndingDetermined) { lineEnding = "\r"; } //do not set as determined as there is possibility of trailing LF } else { if (lineEnding != null) { lineEndingDetermined = true; } //if there was a line ending before, mark it as determined currLine.Append(ch); } prevChar = ch; } FileExists = true; processLine(currLine); } LineEnding = lineEnding ?? Environment.NewLine; void processLine(StringBuilder line) { var lineText = line.ToString(); line.Clear(); char? valueSeparator = null; var sbKey = new StringBuilder(); var sbValue = new StringBuilder(); var sbComment = new StringBuilder(); var sbWhitespace = new StringBuilder(); var sbEscapeLong = new StringBuilder(); string separatorPrefix = null; string separatorSuffix = null; string commentPrefix = null; var state = State.Default; var prevState = State.Default; foreach (var ch in lineText) { switch (state) { case State.Default: if (char.IsWhiteSpace(ch)) { } else if (ch == '#') { sbComment.Append(ch); state = State.Comment; } else if (ch == '\\') { state = State.KeyEscape; } else { sbKey.Append(ch); state = State.Key; } break; case State.Comment: sbComment.Append(ch); break; case State.Key: if (char.IsWhiteSpace(ch)) { valueSeparator = ch; state = State.SeparatorOrValue; } else if ((ch == ':') || (ch == '=')) { valueSeparator = ch; state = State.ValueOrWhitespace; } else if (ch == '#') { sbComment.Append(ch); state = State.Comment; } else if (ch == '\\') { state = State.KeyEscape; } else { sbKey.Append(ch); } break; case State.SeparatorOrValue: if (char.IsWhiteSpace(ch)) { } else if ((ch == ':') || (ch == '=')) { valueSeparator = ch; state = State.ValueOrWhitespace; } else if (ch == '#') { sbComment.Append(ch); state = State.Comment; } else if (ch == '\\') { state = State.ValueEscape; } else { sbValue.Append(ch); state = State.Value; } break; case State.ValueOrWhitespace: if (char.IsWhiteSpace(ch)) { } else if (ch == '#') { sbComment.Append(ch); state = State.Comment; } else if (ch == '\\') { state = State.ValueEscape; } else { sbValue.Append(ch); state = State.Value; } break; case State.Value: if (char.IsWhiteSpace(ch)) { state = State.ValueOrComment; } else if (ch == '#') { sbComment.Append(ch); state = State.Comment; } else if (ch == '\\') { state = State.ValueEscape; } else { sbValue.Append(ch); } break; case State.ValueOrComment: if (char.IsWhiteSpace(ch)) { } else if (ch == '#') { sbComment.Append(ch); state = State.Comment; } else if (ch == '\\') { sbValue.Append(sbWhitespace); state = State.ValueEscape; } else { sbValue.Append(sbWhitespace); sbValue.Append(ch); state = State.Value; } break; case State.KeyEscape: case State.ValueEscape: if (ch == 'u') { state = (state == State.KeyEscape) ? State.KeyEscapeLong : State.ValueEscapeLong; } else { char newCh; switch (ch) { case '0': newCh = '\0'; break; case 'b': newCh = '\b'; break; case 't': newCh = '\t'; break; case 'n': newCh = '\n'; break; case 'r': newCh = '\r'; break; case '_': newCh = ' '; break; default: newCh = ch; break; } if (state == State.KeyEscape) { sbKey.Append(newCh); } else { sbValue.Append(newCh); } state = (state == State.KeyEscape) ? State.Key : State.Value; } break; case State.KeyEscapeLong: case State.ValueEscapeLong: sbEscapeLong.Append(ch); if (sbEscapeLong.Length == 4) { if (int.TryParse(sbEscapeLong.ToString(), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var chValue)) { if (state == State.KeyEscape) { sbKey.Append((char)chValue); } else { sbValue.Append((char)chValue); } } state = (state == State.KeyEscapeLong) ? State.Key : State.Value; } break; } if (char.IsWhiteSpace(ch) && (prevState != State.KeyEscape) && (prevState != State.ValueEscape) && (prevState != State.KeyEscapeLong) && (prevState != State.ValueEscapeLong)) { sbWhitespace.Append(ch); } else if (state != prevState) { //on state change, clean comment prefix if ((state == State.ValueOrWhitespace) && (separatorPrefix == null)) { separatorPrefix = sbWhitespace.ToString(); sbWhitespace.Clear(); } else if ((state == State.Value) && (separatorSuffix == null)) { separatorSuffix = sbWhitespace.ToString(); sbWhitespace.Clear(); } else if ((state == State.Comment) && (commentPrefix == null)) { commentPrefix = sbWhitespace.ToString(); sbWhitespace.Clear(); } else if ((state == State.Key) || (state == State.ValueOrWhitespace) || (state == State.Value)) { sbWhitespace.Clear(); } } prevState = state; } Lines.Add(new LineData(sbKey.ToString(), separatorPrefix, valueSeparator, separatorSuffix, sbValue.ToString(), commentPrefix, sbComment.ToString())); } #if DEBUG foreach (var line in Lines) { if (!string.IsNullOrEmpty(line.Key)) { Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "[Settings] {0}{2}: {1}", line.Key, line.Value, (isOverride ? "*" : ""))); } } #endif } public bool FileExists { get; } //false if there was an error during load public bool Save() { string fileContent = string.Join(LineEnding, Lines); try { var directoryPath = Path.GetDirectoryName(FileName); if (!Directory.Exists(directoryPath)) { var directoryStack = new Stack<string>(); do { directoryStack.Push(directoryPath); directoryPath = Path.GetDirectoryName(directoryPath); } while (!Directory.Exists(directoryPath)); while (directoryStack.Count > 0) { try { Directory.CreateDirectory(directoryStack.Pop()); } catch (IOException) { break; } catch (UnauthorizedAccessException) { break; } } } File.WriteAllText(FileName, fileContent, Utf8); return true; } catch (IOException) { return false; } catch (UnauthorizedAccessException) { return false; } } private enum State { Default, Comment, Key, KeyEscape, KeyEscapeLong, SeparatorOrValue, ValueOrWhitespace, Value, ValueEscape, ValueEscapeLong, ValueOrComment, } private class LineData { public LineData() : this(null, null, null, null, null, null, null) { } public LineData(LineData template, string key, string value) : this(key, template?.SeparatorPrefix ?? "", template?.Separator ?? ':', template?.SeparatorSuffix ?? " ", value, null, null) { if (template != null) { var firstKeyTotalLength = (template.Key?.Length ?? 0) + (template.SeparatorPrefix?.Length ?? 0) + 1 + (template.SeparatorSuffix?.Length ?? 0); var totalLengthWithoutSuffix = key.Length + (template.SeparatorPrefix?.Length ?? 0) + 1; var maxSuffixLength = firstKeyTotalLength - totalLengthWithoutSuffix; if (maxSuffixLength < 1) { maxSuffixLength = 1; } //leave at least one space if (SeparatorSuffix.Length > maxSuffixLength) { SeparatorSuffix = SeparatorSuffix.Substring(0, maxSuffixLength); } } } public LineData(string key, string separatorPrefix, char? separator, string separatorSuffix, string value, string commentPrefix, string comment) { Key = key; SeparatorPrefix = separatorPrefix; Separator = separator ?? ':'; SeparatorSuffix = separatorSuffix; Value = value; CommentPrefix = commentPrefix; Comment = comment; } public string Key { get; set; } public string SeparatorPrefix { get; set; } public char Separator { get; } public string SeparatorSuffix { get; set; } public string Value { get; set; } public string CommentPrefix { get; } public string Comment { get; } public override string ToString() { var sb = new StringBuilder(); if (!string.IsNullOrEmpty(Key)) { EscapeIntoStringBuilder(sb, Key, isKey: true); if (!string.IsNullOrEmpty(Value)) { if ((Separator == ':') || (Separator == '=')) { sb.Append(SeparatorPrefix); sb.Append(Separator); sb.Append(SeparatorSuffix); } else { sb.Append(string.IsNullOrEmpty(SeparatorSuffix) ? " " : SeparatorSuffix); } EscapeIntoStringBuilder(sb, Value ?? ""); } else { //try to preserve formatting in case of spaces (thus omitted) sb.Append(SeparatorPrefix); switch (Separator) { case ':': sb.Append(":"); break; case '=': sb.Append("="); break; } sb.Append(SeparatorSuffix); } } if (!string.IsNullOrEmpty(Comment)) { if (!string.IsNullOrEmpty(CommentPrefix)) { sb.Append(CommentPrefix); } sb.Append(Comment); } return sb.ToString(); } private static void EscapeIntoStringBuilder(StringBuilder sb, string text, bool isKey = false) { for (int i = 0; i < text.Length; i++) { var ch = text[i]; switch (ch) { case '\\': sb.Append(@"\\"); break; case '\0': sb.Append(@"\0"); break; case '\b': sb.Append(@"\b"); break; case '\t': sb.Append(@"\t"); break; case '\r': sb.Append(@"\r"); break; case '\n': sb.Append(@"\n"); break; case '#': sb.Append(@"\#"); break; default: if (char.IsControl(ch)) { sb.Append(((int)ch).ToString("X4", CultureInfo.InvariantCulture)); } else if (ch == ' ') { if ((i == 0) || (i == (text.Length - 1)) || isKey) { sb.Append(@"\_"); } else { sb.Append(ch); } } else if (char.IsWhiteSpace(ch)) { switch (ch) { case '\0': sb.Append(@"\0"); break; case '\b': sb.Append(@"\b"); break; case '\t': sb.Append(@"\t"); break; case '\n': sb.Append(@"\n"); break; case '\r': sb.Append(@"\r"); break; default: sb.Append(((int)ch).ToString("X4", CultureInfo.InvariantCulture)); break; } } else if (ch == '\\') { sb.Append(@"\\"); } else { sb.Append(ch); } break; } } } public bool IsEmpty => string.IsNullOrEmpty(Key) && string.IsNullOrEmpty(Value) && string.IsNullOrEmpty(CommentPrefix) && string.IsNullOrEmpty(Comment); } private Dictionary<string, int> CachedEntries; private void FillCache() { CachedEntries = new Dictionary<string, int>(KeyComparer); for (var i = 0; i < Lines.Count; i++) { var line = Lines[i]; if (!line.IsEmpty) { if (CachedEntries.ContainsKey(line.Key)) { CachedEntries[line.Key] = i; //last key takes precedence } else { CachedEntries.Add(line.Key, i); } } } } public string ReadOne(string key) { if (CachedEntries == null) { FillCache(); } return CachedEntries.TryGetValue(key, out var lineNumber) ? Lines[lineNumber].Value : null; } public IEnumerable<string> ReadMany(string key) { if (CachedEntries == null) { FillCache(); } foreach (var line in Lines) { if (string.Equals(key, line.Key, KeyComparison)) { yield return line.Value; } } } public void WriteOne(string key, string value) { if (CachedEntries == null) { FillCache(); } if (CachedEntries.TryGetValue(key, out var lineIndex)) { var data = Lines[lineIndex]; data.Key = key; data.Value = value; } else { var hasLines = (Lines.Count > 0); var newData = new LineData(hasLines ? Lines[0] : null, key, value); if (!hasLines) { CachedEntries.Add(key, Lines.Count); Lines.Add(newData); Lines.Add(new LineData()); } else if (!Lines[Lines.Count - 1].IsEmpty) { CachedEntries.Add(key, Lines.Count); Lines.Add(newData); } else { CachedEntries.Add(key, Lines.Count - 1); Lines.Insert(Lines.Count - 1, newData); } } } public void WriteMany(string key, IEnumerable<string> values) { if (CachedEntries == null) { FillCache(); } if (CachedEntries.TryGetValue(key, out var lineIndex)) { int lastIndex = 0; LineData lastLine = null; for (var i = Lines.Count - 1; i >= 0; i--) { //find insertion point var line = Lines[i]; if (string.Equals(key, line.Key, KeyComparison)) { if (lastLine == null) { lastLine = line; lastIndex = i; } else { lastIndex--; } Lines.RemoveAt(i); } } var hasLines = (Lines.Count > 0); foreach (var value in values) { Lines.Insert(lastIndex, new LineData(lastLine ?? (hasLines ? Lines[0] : null), key, value)); lastIndex++; } FillCache(); } else { var hasLines = (Lines.Count > 0); if (!hasLines) { foreach (var value in values) { CachedEntries[key] = Lines.Count; Lines.Add(new LineData(null, key, value)); } Lines.Add(new LineData()); } else if (!Lines[Lines.Count - 1].IsEmpty) { foreach (var value in values) { CachedEntries[key] = Lines.Count; Lines.Add(new LineData(Lines[0], key, value)); } } else { foreach (var value in values) { CachedEntries[key] = Lines.Count - 1; Lines.Insert(Lines.Count - 1, new LineData(Lines[0], key, value)); } } } } public void Delete(string key) { if (CachedEntries == null) { FillCache(); } CachedEntries.Remove(key); for (var i = Lines.Count - 1; i >= 0; i--) { var line = Lines[i]; if (string.Equals(key, line.Key, KeyComparison)) { Lines.RemoveAt(i); } } } public void DeleteAll() { Lines.Clear(); FillCache(); } } #endregion #endregion } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// An employment agency. /// </summary> public class EmploymentAgency_Core : TypeCore, ILocalBusiness { public EmploymentAgency_Core() { this._TypeId = 94; this._Id = "EmploymentAgency"; this._Schema_Org_Url = "http://schema.org/EmploymentAgency"; string label = ""; GetLabel(out label, "EmploymentAgency", typeof(EmploymentAgency_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{155}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The larger organization that this local business is a branch of, if any. /// </summary> private BranchOf_Core branchOf; public BranchOf_Core BranchOf { get { return branchOf; } set { branchOf = value; SetPropertyInstance(branchOf); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>). /// </summary> private CurrenciesAccepted_Core currenciesAccepted; public CurrenciesAccepted_Core CurrenciesAccepted { get { return currenciesAccepted; } set { currenciesAccepted = value; SetPropertyInstance(currenciesAccepted); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Cash, credit card, etc. /// </summary> private PaymentAccepted_Core paymentAccepted; public PaymentAccepted_Core PaymentAccepted { get { return paymentAccepted; } set { paymentAccepted = value; SetPropertyInstance(paymentAccepted); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// The price range of the business, for example <code>$$$</code>. /// </summary> private PriceRange_Core priceRange; public PriceRange_Core PriceRange { get { return priceRange; } set { priceRange = value; SetPropertyInstance(priceRange); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
// // ContextBackendHandler.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // Alex Corrado <corrado@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using AppKit; using CoreGraphics; using ObjCRuntime; using Xwt.Backends; using Xwt.Drawing; namespace Xwt.Mac { class CGContextBackend { public CGContext Context; public CGSize Size; public CGAffineTransform? InverseViewTransform; public ContextStatus CurrentStatus = new ContextStatus (); public double ScaleFactor = 1; public StyleSet Styles; } class ContextStatus { public object Pattern; public double GlobalAlpha = 1; public CGColor GlobalColor = null; public ContextStatus Previous; } public class MacContextBackendHandler: ContextBackendHandler { const double degrees = System.Math.PI / 180d; public override double GetScaleFactor (object backend) { var ct = (CGContextBackend) backend; return ct.ScaleFactor; } public override void Save (object backend) { var ct = (CGContextBackend) backend; ct.Context.SaveState (); ct.CurrentStatus = new ContextStatus { Pattern = ct.CurrentStatus.Pattern, GlobalAlpha = ct.CurrentStatus.GlobalAlpha, GlobalColor = ct.CurrentStatus.GlobalColor, Previous = ct.CurrentStatus, }; } public override void Restore (object backend) { var ct = (CGContextBackend) backend; ct.Context.RestoreState (); if (ct.CurrentStatus.Previous != null) { ct.CurrentStatus = ct.CurrentStatus.Previous; } } public override void SetGlobalAlpha (object backend, double alpha) { var ct = (CGContextBackend) backend; ct.CurrentStatus.GlobalAlpha = alpha; ct.Context.SetAlpha ((float)alpha); } public override void SetStyles (object backend, StyleSet styles) { ((CGContextBackend)backend).Styles = styles; } public override void Arc (object backend, double xc, double yc, double radius, double angle1, double angle2) { CGContext ctx = ((CGContextBackend)backend).Context; ctx.AddArc ((float)xc, (float)yc, (float)radius, (float)(angle1 * degrees), (float)(angle2 * degrees), false); } public override void ArcNegative (object backend, double xc, double yc, double radius, double angle1, double angle2) { CGContext ctx = ((CGContextBackend)backend).Context; ctx.AddArc ((float)xc, (float)yc, (float)radius, (float)(angle1 * degrees), (float)(angle2 * degrees), true); } public override void Clip (object backend) { ((CGContextBackend)backend).Context.Clip (); } public override void ClipPreserve (object backend) { CGContext ctx = ((CGContextBackend)backend).Context; using (CGPath oldPath = ctx.CopyPath ()) { ctx.Clip (); ctx.AddPath (oldPath); } } public override void ClosePath (object backend) { ((CGContextBackend)backend).Context.ClosePath (); } public override void CurveTo (object backend, double x1, double y1, double x2, double y2, double x3, double y3) { ((CGContextBackend)backend).Context.AddCurveToPoint ((float)x1, (float)y1, (float)x2, (float)y2, (float)x3, (float)y3); } public override void Fill (object backend) { CGContextBackend gc = (CGContextBackend)backend; CGContext ctx = gc.Context; SetupContextForDrawing (ctx); if (gc.CurrentStatus.Pattern is GradientInfo) { MacGradientBackendHandler.Draw (ctx, ((GradientInfo)gc.CurrentStatus.Pattern)); } else if (gc.CurrentStatus.Pattern is ImagePatternInfo) { SetupPattern (gc); ctx.DrawPath (CGPathDrawingMode.Fill); } else { ctx.DrawPath (CGPathDrawingMode.Fill); } } public override void FillPreserve (object backend) { CGContext ctx = ((CGContextBackend)backend).Context; using (CGPath oldPath = ctx.CopyPath ()) { Fill (backend); ctx.AddPath (oldPath); } } public override void LineTo (object backend, double x, double y) { ((CGContextBackend)backend).Context.AddLineToPoint ((float)x, (float)y); } public override void MoveTo (object backend, double x, double y) { ((CGContextBackend)backend).Context.MoveTo ((float)x, (float)y); } public override void NewPath (object backend) { ((CGContextBackend)backend).Context.BeginPath (); } public override void Rectangle (object backend, double x, double y, double width, double height) { ((CGContextBackend)backend).Context.AddRect (new CGRect ((nfloat)x, (nfloat)y, (nfloat)width, (nfloat)height)); } public override void RelCurveTo (object backend, double dx1, double dy1, double dx2, double dy2, double dx3, double dy3) { CGContext ctx = ((CGContextBackend)backend).Context; CGPoint p = ctx.GetPathCurrentPoint (); ctx.AddCurveToPoint ((float)(p.X + dx1), (float)(p.Y + dy1), (float)(p.X + dx2), (float)(p.Y + dy2), (float)(p.X + dx3), (float)(p.Y + dy3)); } public override void RelLineTo (object backend, double dx, double dy) { CGContext ctx = ((CGContextBackend)backend).Context; CGPoint p = ctx.GetPathCurrentPoint (); ctx.AddLineToPoint ((float)(p.X + dx), (float)(p.Y + dy)); } public override void RelMoveTo (object backend, double dx, double dy) { CGContext ctx = ((CGContextBackend)backend).Context; CGPoint p = ctx.GetPathCurrentPoint (); ctx.MoveTo ((float)(p.X + dx), (float)(p.Y + dy)); } public override void Stroke (object backend) { CGContext ctx = ((CGContextBackend)backend).Context; SetupContextForDrawing (ctx); ctx.DrawPath (CGPathDrawingMode.Stroke); } public override void StrokePreserve (object backend) { CGContext ctx = ((CGContextBackend)backend).Context; SetupContextForDrawing (ctx); using (CGPath oldPath = ctx.CopyPath ()) { ctx.DrawPath (CGPathDrawingMode.Stroke); ctx.AddPath (oldPath); } } public override void SetColor (object backend, Xwt.Drawing.Color color) { CGContextBackend gc = (CGContextBackend)backend; gc.CurrentStatus.Pattern = null; // Store the current color for TextLayout using NSLayoutManager gc.CurrentStatus.GlobalColor = color.ToCGColor (); CGContext ctx = gc.Context; ctx.SetFillColorSpace (Util.DeviceRGBColorSpace); ctx.SetStrokeColorSpace (Util.DeviceRGBColorSpace); ctx.SetFillColor ((float)color.Red, (float)color.Green, (float)color.Blue, (float)color.Alpha); ctx.SetStrokeColor ((float)color.Red, (float)color.Green, (float)color.Blue, (float)color.Alpha); } public override void SetLineWidth (object backend, double width) { ((CGContextBackend)backend).Context.SetLineWidth ((float)width); } public override void SetLineDash (object backend, double offset, params double[] pattern) { var array = new nfloat[pattern.Length]; for (int n=0; n<pattern.Length; n++) array [n] = (float) pattern[n]; ((CGContextBackend)backend).Context.SetLineDash ((nfloat)offset, array); } public override void SetPattern (object backend, object p) { CGContextBackend gc = (CGContextBackend)backend; var toolkit = ApplicationContext.Toolkit; gc.CurrentStatus.Pattern = toolkit.GetSafeBackend (p); } void SetupPattern (CGContextBackend gc) { gc.Context.SetPatternPhase (new CGSize (0, 0)); if (gc.CurrentStatus.Pattern is GradientInfo) return; if (gc.CurrentStatus.Pattern is ImagePatternInfo) { var pi = (ImagePatternInfo) gc.CurrentStatus.Pattern; var bounds = new CGRect (CGPoint.Empty, new CGSize (pi.Image.Size.Width, pi.Image.Size.Height)); var t = CGAffineTransform.Multiply (CGAffineTransform.MakeScale (1f, -1f), gc.Context.GetCTM ()); CGPattern pattern; if (pi.Image is CustomImage) { pattern = new CGPattern (bounds, t, bounds.Width, bounds.Height, CGPatternTiling.ConstantSpacing, true, c => { c.TranslateCTM (0, bounds.Height); c.ScaleCTM (1f, -1f); ((CustomImage)pi.Image).DrawInContext (c); }); } else { var empty = CGRect.Empty; CGImage cgimg = pi.Image.AsCGImage (ref empty, null, null); pattern = new CGPattern (bounds, t, bounds.Width, bounds.Height, CGPatternTiling.ConstantSpacing, true, c => c.DrawImage (bounds, cgimg)); } using (pattern) { CGContext ctx = gc.Context; var alpha = new[] { (nfloat)pi.Alpha }; ctx.SetFillColorSpace(Util.PatternColorSpace); ctx.SetStrokeColorSpace(Util.PatternColorSpace); ctx.SetFillPattern(pattern, alpha); ctx.SetStrokePattern(pattern, alpha); } } } public override void DrawTextLayout (object backend, TextLayout layout, double x, double y) { CGContext ctx = ((CGContextBackend)backend).Context; SetupContextForDrawing (ctx); var li = ApplicationContext.Toolkit.GetSafeBackend (layout); MacTextLayoutBackendHandler.Draw ((CGContextBackend)backend, li, x, y); } public override void DrawImage (object backend, ImageDescription img, double x, double y) { var srcRect = new Rectangle (Point.Zero, img.Size); var destRect = new Rectangle (x, y, img.Size.Width, img.Size.Height); DrawImage (backend, img, srcRect, destRect); } public override void DrawImage (object backend, ImageDescription img, Rectangle srcRect, Rectangle destRect) { var cb = (CGContextBackend)backend; CGContext ctx = cb.Context; // Add the styles that have been globaly set to the context img.Styles = img.Styles.AddRange (cb.Styles); img.Alpha *= cb.CurrentStatus.GlobalAlpha; ctx.SaveState (); ctx.SetAlpha ((float)img.Alpha); double rx = destRect.Width / srcRect.Width; double ry = destRect.Height / srcRect.Height; ctx.AddRect (new CGRect ((nfloat)destRect.X, (nfloat)destRect.Y, (nfloat)destRect.Width, (nfloat)destRect.Height)); ctx.Clip (); ctx.TranslateCTM ((float)(destRect.X - (srcRect.X * rx)), (float)(destRect.Y - (srcRect.Y * ry))); ctx.ScaleCTM ((float)rx, (float)ry); NSImage image = (NSImage)img.Backend; if (image is CustomImage) { ((CustomImage)image).DrawInContext ((CGContextBackend)backend, img); } else { var size = new CGSize ((nfloat)img.Size.Width, (nfloat)img.Size.Height); var rr = new CGRect (0, 0, size.Width, size.Height); ctx.ScaleCTM (1f, -1f); ctx.DrawImage (new CGRect (0, -size.Height, size.Width, size.Height), image.AsCGImage (ref rr, NSGraphicsContext.CurrentContext, null)); } ctx.RestoreState (); } public override void Rotate (object backend, double angle) { ((CGContextBackend)backend).Context.RotateCTM ((float)(angle * degrees)); } public override void Scale (object backend, double scaleX, double scaleY) { ((CGContextBackend)backend).Context.ScaleCTM ((float)scaleX, (float)scaleY); } public override void Translate (object backend, double tx, double ty) { ((CGContextBackend)backend).Context.TranslateCTM ((float)tx, (float)ty); } public override void ModifyCTM (object backend, Matrix m) { CGAffineTransform t = new CGAffineTransform ((float)m.M11, (float)m.M12, (float)m.M21, (float)m.M22, (float)m.OffsetX, (float)m.OffsetY); ((CGContextBackend)backend).Context.ConcatCTM (t); } public override Matrix GetCTM (object backend) { CGAffineTransform t = GetContextTransform ((CGContextBackend)backend); Matrix ctm = new Matrix (t.A, t.B, t.C, t.D, t.Tx, t.Ty); return ctm; } public override object CreatePath () { return new CGPath (); } public override object CopyPath (object backend) { return ((CGContextBackend)backend).Context.CopyPath (); } public override void AppendPath (object backend, object otherBackend) { CGContext dest = ((CGContextBackend)backend).Context; CGContextBackend src = otherBackend as CGContextBackend; if (src != null) { using (var path = src.Context.CopyPath ()) dest.AddPath (path); } else { dest.AddPath ((CGPath)otherBackend); } } public override bool IsPointInFill (object backend, double x, double y) { return ((CGContextBackend)backend).Context.PathContainsPoint (new CGPoint ((nfloat)x, (nfloat)y), CGPathDrawingMode.Fill); } public override bool IsPointInStroke (object backend, double x, double y) { return ((CGContextBackend)backend).Context.PathContainsPoint (new CGPoint ((nfloat)x, (nfloat)y), CGPathDrawingMode.Stroke); } public override void Dispose (object backend) { ((CGContextBackend)backend).Context.Dispose (); } static CGAffineTransform GetContextTransform (CGContextBackend gc) { CGAffineTransform t = gc.Context.GetCTM (); // The CTM returned above actually includes the full view transform. // We only want the transform that is applied to the context, so concat // the inverse of the view transform to nullify that part. if (gc.InverseViewTransform.HasValue) t.Multiply (gc.InverseViewTransform.Value); return t; } static void SetupContextForDrawing (CGContext ctx) { if (ctx.IsPathEmpty ()) return; // setup pattern drawing to better match the behavior of Cairo var drawPoint = ctx.GetCTM ().TransformPoint (ctx.GetPathBoundingBox ().Location); var patternPhase = new CGSize (drawPoint.X, drawPoint.Y); if (patternPhase != CGSize.Empty) ctx.SetPatternPhase (patternPhase); } } }
/* ==================================================================== 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 NPOI.HWPF.Model.Types; using System; using NPOI.Util; namespace NPOI.HWPF.UserModel { public class ParagraphProperties : PAPAbstractType { private bool jcLogical = false; public ParagraphProperties() { SetAnld(new byte[84]); SetPhe(new byte[12]); } public override Object Clone() { ParagraphProperties pp = (ParagraphProperties)base.Clone(); byte[] anld=GetAnld(); byte[] anldcopy=new byte[anld.Length]; Array.Copy(anld,anldcopy,anld.Length); pp.SetAnld(anldcopy); pp.SetBrcTop((BorderCode)GetBrcTop().Clone()); pp.SetBrcLeft((BorderCode)GetBrcLeft().Clone()); pp.SetBrcBottom((BorderCode)GetBrcBottom().Clone()); pp.SetBrcRight((BorderCode)GetBrcRight().Clone()); pp.SetBrcBetween((BorderCode)GetBrcBetween().Clone()); pp.SetBrcBar((BorderCode)GetBrcBar().Clone()); pp.SetDcs((DropCapSpecifier)GetDcs().Clone()); pp.SetLspd((LineSpacingDescriptor)GetLspd().Clone()); pp.SetShd((ShadingDescriptor)GetShd().Clone()); byte[] phe = GetPhe(); byte[] phecopy = new byte[phe.Length]; Array.Copy(phe, phecopy, phe.Length); pp.SetPhe(phecopy); return pp; } public BorderCode GetBarBorder() { return base.GetBrcBar(); } public BorderCode GetBottomBorder() { return base.GetBrcBottom(); } public DropCapSpecifier GetDropCap() { return base.GetDcs(); } public int GetFirstLineIndent() { return base.GetDxaLeft1(); } public int GetFontAlignment() { return base.GetWAlignFont(); } public int GetIndentFromLeft() { return base.GetDxaLeft(); } public int GetIndentFromRight() { return base.GetDxaRight(); } public int GetJustification() { if (jcLogical) { if (!GetFBiDi()) return GetJc(); switch (GetJc()) { case 0: return 2; case 2: return 0; default: return GetJc(); } } return GetJc(); } public BorderCode GetLeftBorder() { return base.GetBrcLeft(); } public LineSpacingDescriptor GetLineSpacing() { return base.GetLspd(); } public BorderCode GetRightBorder() { return base.GetBrcRight(); } public ShadingDescriptor GetShading() { return base.GetShd(); } public int GetSpacingAfter() { return base.GetDyaAfter(); } public int GetSpacingBefore() { return base.GetDyaBefore(); } public BorderCode GetTopBorder() { return base.GetBrcTop(); } public bool IsAutoHyphenated() { return !base.GetFNoAutoHyph(); } public bool IsBackward() { return base.IsFBackward(); } public bool IsKinsoku() { return base.GetFKinsoku(); } public bool IsLineNotNumbered() { return base.GetFNoLnn(); } public bool IsSideBySide() { return base.GetFSideBySide(); } public bool IsVertical() { return base.IsFVertical(); } public bool IsWidowControlled() { return base.GetFWidowControl(); } public bool IsWordWrapped() { return base.GetFWordWrap(); } public bool keepOnPage() { return base.GetFKeep(); } public bool keepWithNext() { return base.GetFKeepFollow(); } public bool pageBreakBefore() { return base.GetFPageBreakBefore(); } public void SetAutoHyphenated(bool auto) { base.SetFNoAutoHyph(!auto); } public void SetBackward(bool bward) { base.SetFBackward(bward); } public void SetBarBorder(BorderCode bar) { base.SetBrcBar(bar); } public void SetBottomBorder(BorderCode bottom) { base.SetBrcBottom(bottom); } public void SetDropCap(DropCapSpecifier dcs) { base.SetDcs(dcs); } public void SetFirstLineIndent(int first) { base.SetDxaLeft1(first); } public void SetFontAlignment(int align) { base.SetWAlignFont(align); } public void SetIndentFromLeft(int dxaLeft) { base.SetDxaLeft(dxaLeft); } public void SetIndentFromRight(int dxaRight) { base.SetDxaRight(dxaRight); } public void SetJustification(byte jc) { base.SetJc(jc); this.jcLogical = false; } public void SetJustificationLogical(byte jc) { base.SetJc(jc); this.jcLogical = true; } public void SetKeepOnPage(bool fKeep) { base.SetFKeep(fKeep); } public void SetKeepWithNext(bool fKeepFollow) { base.SetFKeepFollow(fKeepFollow); } public void SetKinsoku(bool kinsoku) { base.SetFKinsoku(kinsoku); } public void SetLeftBorder(BorderCode left) { base.SetBrcLeft(left); } public void SetLineNotNumbered(bool fNoLnn) { base.SetFNoLnn(fNoLnn); } public void SetLineSpacing(LineSpacingDescriptor lspd) { base.SetLspd(lspd); } public void SetPageBreakBefore(bool fPageBreak) { base.SetFPageBreakBefore(fPageBreak); } public void SetRightBorder(BorderCode right) { base.SetBrcRight(right); } public void SetShading(ShadingDescriptor shd) { base.SetShd(shd); } public void SetSideBySide(bool fSideBySide) { base.SetFSideBySide(fSideBySide); } public void SetSpacingAfter(int after) { base.SetDyaAfter(after); } public void SetSpacingBefore(int before) { base.SetDyaBefore(before); } public void SetTopBorder(BorderCode top) { base.SetBrcTop(top); } public void SetVertical(bool vertical) { base.SetFVertical(vertical); } public void SetWidowControl(bool widowControl) { base.SetFWidowControl(widowControl); } public void SetWordWrapped(bool wrap) { base.SetFWordWrap(wrap); } } }
// ReSharper disable All using System.Collections.Generic; using System.Dynamic; using System.Net; using System.Net.Http; using System.Web.Http; using Frapid.ApplicationState.Cache; using Frapid.ApplicationState.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Frapid.Account.DataAccess; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.Framework; using Frapid.Framework.Extensions; namespace Frapid.Account.Api { /// <summary> /// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Users. /// </summary> [RoutePrefix("api/v1.0/account/user")] public class UserController : FrapidApiController { /// <summary> /// The User repository. /// </summary> private readonly IUserRepository UserRepository; public UserController() { this._LoginId = AppUsers.GetCurrent().View.LoginId.To<long>(); this._UserId = AppUsers.GetCurrent().View.UserId.To<int>(); this._OfficeId = AppUsers.GetCurrent().View.OfficeId.To<int>(); this._Catalog = AppUsers.GetCatalog(); this.UserRepository = new Frapid.Account.DataAccess.User { _Catalog = this._Catalog, _LoginId = this._LoginId, _UserId = this._UserId }; } public UserController(IUserRepository repository, string catalog, LoginView view) { this._LoginId = view.LoginId.To<long>(); this._UserId = view.UserId.To<int>(); this._OfficeId = view.OfficeId.To<int>(); this._Catalog = catalog; this.UserRepository = repository; } public long _LoginId { get; } public int _UserId { get; private set; } public int _OfficeId { get; private set; } public string _Catalog { get; } /// <summary> /// Creates meta information of "user" entity. /// </summary> /// <returns>Returns the "user" meta information to perform CRUD operation.</returns> [AcceptVerbs("GET", "HEAD")] [Route("meta")] [Route("~/api/account/user/meta")] [Authorize] public EntityView GetEntityView() { if (this._LoginId == 0) { return new EntityView(); } return new EntityView { PrimaryKey = "user_id", Columns = new List<EntityColumn>() { new EntityColumn { ColumnName = "user_id", PropertyName = "UserId", DataType = "int", DbDataType = "int4", IsNullable = false, IsPrimaryKey = true, IsSerial = true, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "email", PropertyName = "Email", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 100 }, new EntityColumn { ColumnName = "password", PropertyName = "Password", DataType = "string", DbDataType = "text", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "office_id", PropertyName = "OfficeId", DataType = "int", DbDataType = "int4", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "role_id", PropertyName = "RoleId", DataType = "int", DbDataType = "int4", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "name", PropertyName = "Name", DataType = "string", DbDataType = "varchar", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 100 }, new EntityColumn { ColumnName = "phone", PropertyName = "Phone", DataType = "string", DbDataType = "varchar", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 100 }, new EntityColumn { ColumnName = "status", PropertyName = "Status", DataType = "bool", DbDataType = "bool", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "audit_user_id", PropertyName = "AuditUserId", DataType = "int", DbDataType = "int4", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "audit_ts", PropertyName = "AuditTs", DataType = "DateTime", DbDataType = "timestamptz", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 } } }; } /// <summary> /// Counts the number of users. /// </summary> /// <returns>Returns the count of the users.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count")] [Route("~/api/account/user/count")] [Authorize] public long Count() { try { return this.UserRepository.Count(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns all collection of user. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("all")] [Route("~/api/account/user/all")] [Authorize] public IEnumerable<Frapid.Account.Entities.User> GetAll() { try { return this.UserRepository.GetAll(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns collection of user for export. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("export")] [Route("~/api/account/user/export")] [Authorize] public IEnumerable<dynamic> Export() { try { return this.UserRepository.Export(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns an instance of user. /// </summary> /// <param name="userId">Enter UserId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("{userId}")] [Route("~/api/account/user/{userId}")] [Authorize] public Frapid.Account.Entities.User Get(int userId) { try { return this.UserRepository.Get(userId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } [AcceptVerbs("GET", "HEAD")] [Route("get")] [Route("~/api/account/user/get")] [Authorize] public IEnumerable<Frapid.Account.Entities.User> Get([FromUri] int[] userIds) { try { return this.UserRepository.Get(userIds); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the first instance of user. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("first")] [Route("~/api/account/user/first")] [Authorize] public Frapid.Account.Entities.User GetFirst() { try { return this.UserRepository.GetFirst(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the previous instance of user. /// </summary> /// <param name="userId">Enter UserId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("previous/{userId}")] [Route("~/api/account/user/previous/{userId}")] [Authorize] public Frapid.Account.Entities.User GetPrevious(int userId) { try { return this.UserRepository.GetPrevious(userId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the next instance of user. /// </summary> /// <param name="userId">Enter UserId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("next/{userId}")] [Route("~/api/account/user/next/{userId}")] [Authorize] public Frapid.Account.Entities.User GetNext(int userId) { try { return this.UserRepository.GetNext(userId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the last instance of user. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("last")] [Route("~/api/account/user/last")] [Authorize] public Frapid.Account.Entities.User GetLast() { try { return this.UserRepository.GetLast(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 users on each page, sorted by the property UserId. /// </summary> /// <returns>Returns the first page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("")] [Route("~/api/account/user")] [Authorize] public IEnumerable<Frapid.Account.Entities.User> GetPaginatedResult() { try { return this.UserRepository.GetPaginatedResult(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 users on each page, sorted by the property UserId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <returns>Returns the requested page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("page/{pageNumber}")] [Route("~/api/account/user/page/{pageNumber}")] [Authorize] public IEnumerable<Frapid.Account.Entities.User> GetPaginatedResult(long pageNumber) { try { return this.UserRepository.GetPaginatedResult(pageNumber); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of users using the supplied filter(s). /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the count of filtered users.</returns> [AcceptVerbs("POST")] [Route("count-where")] [Route("~/api/account/user/count-where")] [Authorize] public long CountWhere([FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.UserRepository.CountWhere(f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 users on each page, sorted by the property UserId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("POST")] [Route("get-where/{pageNumber}")] [Route("~/api/account/user/get-where/{pageNumber}")] [Authorize] public IEnumerable<Frapid.Account.Entities.User> GetWhere(long pageNumber, [FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.UserRepository.GetWhere(pageNumber, f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of users using the supplied filter name. /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns the count of filtered users.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count-filtered/{filterName}")] [Route("~/api/account/user/count-filtered/{filterName}")] [Authorize] public long CountFiltered(string filterName) { try { return this.UserRepository.CountFiltered(filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 users on each page, sorted by the property UserId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("GET", "HEAD")] [Route("get-filtered/{pageNumber}/{filterName}")] [Route("~/api/account/user/get-filtered/{pageNumber}/{filterName}")] [Authorize] public IEnumerable<Frapid.Account.Entities.User> GetFiltered(long pageNumber, string filterName) { try { return this.UserRepository.GetFiltered(pageNumber, filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Displayfield is a lightweight key/value collection of users. /// </summary> /// <returns>Returns an enumerable key/value collection of users.</returns> [AcceptVerbs("GET", "HEAD")] [Route("display-fields")] [Route("~/api/account/user/display-fields")] [Authorize] public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields() { try { return this.UserRepository.GetDisplayFields(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// A custom field is a user defined field for users. /// </summary> /// <returns>Returns an enumerable custom field collection of users.</returns> [AcceptVerbs("GET", "HEAD")] [Route("custom-fields")] [Route("~/api/account/user/custom-fields")] [Authorize] public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields() { try { return this.UserRepository.GetCustomFields(null); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// A custom field is a user defined field for users. /// </summary> /// <returns>Returns an enumerable custom field collection of users.</returns> [AcceptVerbs("GET", "HEAD")] [Route("custom-fields/{resourceId}")] [Route("~/api/account/user/custom-fields/{resourceId}")] [Authorize] public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId) { try { return this.UserRepository.GetCustomFields(resourceId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Adds or edits your instance of User class. /// </summary> /// <param name="user">Your instance of users class to add or edit.</param> [AcceptVerbs("POST")] [Route("add-or-edit")] [Route("~/api/account/user/add-or-edit")] [Authorize] public object AddOrEdit([FromBody]Newtonsoft.Json.Linq.JArray form) { dynamic user = form[0].ToObject<ExpandoObject>(JsonHelper.GetJsonSerializer()); List<Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject<List<Frapid.DataAccess.Models.CustomField>>(JsonHelper.GetJsonSerializer()); if (user == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { return this.UserRepository.AddOrEdit(user, customFields); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Adds your instance of User class. /// </summary> /// <param name="user">Your instance of users class to add.</param> [AcceptVerbs("POST")] [Route("add/{user}")] [Route("~/api/account/user/add/{user}")] [Authorize] public void Add(Frapid.Account.Entities.User user) { if (user == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { this.UserRepository.Add(user); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Edits existing record with your instance of User class. /// </summary> /// <param name="user">Your instance of User class to edit.</param> /// <param name="userId">Enter the value for UserId in order to find and edit the existing record.</param> [AcceptVerbs("PUT")] [Route("edit/{userId}")] [Route("~/api/account/user/edit/{userId}")] [Authorize] public void Edit(int userId, [FromBody] Frapid.Account.Entities.User user) { if (user == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { this.UserRepository.Update(user, userId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } private List<ExpandoObject> ParseCollection(JArray collection) { return JsonConvert.DeserializeObject<List<ExpandoObject>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings()); } /// <summary> /// Adds or edits multiple instances of User class. /// </summary> /// <param name="collection">Your collection of User class to bulk import.</param> /// <returns>Returns list of imported userIds.</returns> /// <exception cref="DataAccessException">Thrown when your any User class in the collection is invalid or malformed.</exception> [AcceptVerbs("POST")] [Route("bulk-import")] [Route("~/api/account/user/bulk-import")] [Authorize] public List<object> BulkImport([FromBody]JArray collection) { List<ExpandoObject> userCollection = this.ParseCollection(collection); if (userCollection == null || userCollection.Count.Equals(0)) { return null; } try { return this.UserRepository.BulkImport(userCollection); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Deletes an existing instance of User class via UserId. /// </summary> /// <param name="userId">Enter the value for UserId in order to find and delete the existing record.</param> [AcceptVerbs("DELETE")] [Route("delete/{userId}")] [Route("~/api/account/user/delete/{userId}")] [Authorize] public void Delete(int userId) { try { this.UserRepository.Delete(userId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } } }
using System; /// <summary> /// String.GetHashCode() /// Returns the hash code for this string. /// </summary> class StringGetHashCode { private const int c_MIN_STRING_LEN = 8; private const int c_MAX_STRING_LEN = 256; private const int c_MAX_SHORT_STR_LEN = 31;//short string (<32 chars) private const int c_MIN_LONG_STR_LEN = 257;//long string ( >256 chars) private const int c_MAX_LONG_STR_LEN = 65535; private const string c_POS_TEST_PREFIX = "PosTest"; private const string c_NEG_TEST_PREFIX = "NegTest"; private const string c_GREEK_SIGMA_STR_A = "\x03C2\x03C3\x03A3\x03C2\x03C3"; private const string c_GREEK_SIGMA_STR_B = "\x03A3\x03A3\x03A3\x03C3\x03C2"; private int totalTestCount; private int posTestCount; private int negTestCount; private int passedTestCount; private int failedTestCount; private enum TestType { PositiveTest = 1, NegativeTest = 2 }; private enum TestResult { NotRun = 0, PassedTest = 1, FailedTest = 2 }; internal struct Parameters { public string strSrc; public string DataString { get { string str, strA; int lenA; if (null == strSrc) { strA = "null"; lenA = 0; } else { strA = strSrc; lenA = strSrc.Length; } str = string.Format("\n[String value]\nSource: \"{0}\"\n[String length]\n {1}", strA, lenA); return str; } } } //Default constructor to ininitial all kind of test counts public StringGetHashCode() { totalTestCount = posTestCount = negTestCount = 0; passedTestCount = failedTestCount = 0; } #region Methods for all test scenarioes //Update (postive or negative) and total test count at the beginning of test scenario private void UpdateCounts(TestType testType) { if (TestType.PositiveTest == testType) { posTestCount++; totalTestCount++; return; } if (TestType.NegativeTest == testType) { negTestCount++; totalTestCount++; return; } } //Update failed or passed test counts at the end of test scenario private void UpdateCounts(TestResult testResult) { if (TestResult.PassedTest == testResult) { passedTestCount++; return; } if (TestResult.FailedTest == testResult) { failedTestCount++; return; } } //Generate standard error number string //i.e "9", "12" is not proper. Instead they should be "009", "012" private string GenerateErrorNum(int errorNum) { string temp = errorNum.ToString(); string errorNumStr = new string('0', 3 - temp.Length) + temp; return errorNumStr; } //Generate testId string //i.e "P9", "N12" is not proper. Instead they should be "P009", "N012" private string GenerateTestId(TestType testType) { string temp, testId; if (testType == TestType.PositiveTest) { temp = this.posTestCount.ToString(); testId = "P" + new string('0', 3 - temp.Length) + temp; } else { temp = this.negTestCount.ToString(); testId = "N" + new string('0', 3 - temp.Length) + temp; } return testId; } #endregion public static int Main() { StringGetHashCode sge = new StringGetHashCode(); TestLibrary.TestFramework.BeginTestCase("for method: System.String.GetHashCode()"); if (sge.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; return retVal; } #region Positive test scenarioes #region Normal tests public bool PosTest1() { Parameters paras; const string c_TEST_DESC = "Random string"; paras.strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); return ExecutePosTest(paras, c_TEST_DESC); } #endregion #region String.Empty, "\0" and null public bool PosTest2() { Parameters paras; const string c_TEST_DESC = "String.Empty"; paras.strSrc = String.Empty; return ExecutePosTest(paras, c_TEST_DESC); } public bool PosTest3() { Parameters paras; const string c_TEST_DESC = "\"\0\""; paras.strSrc = "\0"; return ExecutePosTest(paras, c_TEST_DESC); } #endregion #endregion // end for positive test scenarioes #region Helper methods for positive test scenarioes private bool ExecutePosTest(Parameters paras, string testDesc) { bool retVal = true; UpdateCounts(TestType.PositiveTest); string testId = GenerateTestId(TestType.PositiveTest); TestResult testResult = TestResult.NotRun; string testInfo = c_POS_TEST_PREFIX + this.posTestCount.ToString() + ": " + testDesc; object actualValue = null; TestLibrary.TestFramework.BeginScenario(testInfo); try { actualValue = this.CallTestMethod(paras); if (null == actualValue) { string errorDesc = "Enumerator is not retrieved as expected, actually it is null"; errorDesc += paras.DataString + "\nTest scenario Id: " + testId; TestLibrary.TestFramework.LogError(GenerateErrorNum(totalTestCount << 1 - 1) + " TestId -" + testId, errorDesc); testResult = TestResult.FailedTest; retVal = false; } testResult = TestResult.PassedTest; } catch (Exception e) { TestLibrary.TestFramework.LogError(GenerateErrorNum(totalTestCount << 1) + " TestId -" + testId, "Unexpected exception: " + e + paras.DataString); testResult = TestResult.FailedTest; retVal = false; } UpdateCounts(testResult); return retVal; } #endregion //Involke the test method private int CallTestMethod(Parameters paras) { return paras.strSrc.GetHashCode(); } #region helper methods for generating test data private bool GetBoolean() { Int32 i = this.GetInt32(1, 2); return (i == 1) ? true : false; } //Get a non-negative integer between minValue and maxValue private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } private Int32 Min(Int32 i1, Int32 i2) { return (i1 <= i2) ? i1 : i2; } private Int32 Max(Int32 i1, Int32 i2) { return (i1 >= i2) ? i1 : i2; } private char GetUpperChar() { Char c; // Grab an ASCII letter c = Convert.ToChar(TestLibrary.Generator.GetInt16(-55) % 26 + 'A'); return c; } #endregion }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using System.Linq; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Wireless.V1 { /// <summary> /// ReadRatePlanOptions /// </summary> public class ReadRatePlanOptions : ReadOptions<RatePlanResource> { /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } /// <summary> /// FetchRatePlanOptions /// </summary> public class FetchRatePlanOptions : IOptions<RatePlanResource> { /// <summary> /// The SID that identifies the resource to fetch /// </summary> public string PathSid { get; } /// <summary> /// Construct a new FetchRatePlanOptions /// </summary> /// <param name="pathSid"> The SID that identifies the resource to fetch </param> public FetchRatePlanOptions(string pathSid) { PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// CreateRatePlanOptions /// </summary> public class CreateRatePlanOptions : IOptions<RatePlanResource> { /// <summary> /// An application-defined string that uniquely identifies the resource /// </summary> public string UniqueName { get; set; } /// <summary> /// A string to describe the resource /// </summary> public string FriendlyName { get; set; } /// <summary> /// Whether SIMs can use GPRS/3G/4G/LTE data connectivity /// </summary> public bool? DataEnabled { get; set; } /// <summary> /// The total data usage in Megabytes that the Network allows during one month on the home network /// </summary> public int? DataLimit { get; set; } /// <summary> /// The model used to meter data usage /// </summary> public string DataMetering { get; set; } /// <summary> /// Whether SIMs can make, send, and receive SMS using Commands /// </summary> public bool? MessagingEnabled { get; set; } /// <summary> /// Deprecated /// </summary> public bool? VoiceEnabled { get; set; } /// <summary> /// Whether SIMs can roam on networks other than the home network in the United States /// </summary> public bool? NationalRoamingEnabled { get; set; } /// <summary> /// The services that SIMs capable of using GPRS/3G/4G/LTE data connectivity can use outside of the United States /// </summary> public List<string> InternationalRoaming { get; set; } /// <summary> /// The total data usage in Megabytes that the Network allows during one month on non-home networks in the United States /// </summary> public int? NationalRoamingDataLimit { get; set; } /// <summary> /// The total data usage (download and upload combined) in Megabytes that the Network allows during one month when roaming outside the United States /// </summary> public int? InternationalRoamingDataLimit { get; set; } /// <summary> /// Construct a new CreateRatePlanOptions /// </summary> public CreateRatePlanOptions() { InternationalRoaming = new List<string>(); } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (UniqueName != null) { p.Add(new KeyValuePair<string, string>("UniqueName", UniqueName)); } if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (DataEnabled != null) { p.Add(new KeyValuePair<string, string>("DataEnabled", DataEnabled.Value.ToString().ToLower())); } if (DataLimit != null) { p.Add(new KeyValuePair<string, string>("DataLimit", DataLimit.ToString())); } if (DataMetering != null) { p.Add(new KeyValuePair<string, string>("DataMetering", DataMetering)); } if (MessagingEnabled != null) { p.Add(new KeyValuePair<string, string>("MessagingEnabled", MessagingEnabled.Value.ToString().ToLower())); } if (VoiceEnabled != null) { p.Add(new KeyValuePair<string, string>("VoiceEnabled", VoiceEnabled.Value.ToString().ToLower())); } if (NationalRoamingEnabled != null) { p.Add(new KeyValuePair<string, string>("NationalRoamingEnabled", NationalRoamingEnabled.Value.ToString().ToLower())); } if (InternationalRoaming != null) { p.AddRange(InternationalRoaming.Select(prop => new KeyValuePair<string, string>("InternationalRoaming", prop))); } if (NationalRoamingDataLimit != null) { p.Add(new KeyValuePair<string, string>("NationalRoamingDataLimit", NationalRoamingDataLimit.ToString())); } if (InternationalRoamingDataLimit != null) { p.Add(new KeyValuePair<string, string>("InternationalRoamingDataLimit", InternationalRoamingDataLimit.ToString())); } return p; } } /// <summary> /// UpdateRatePlanOptions /// </summary> public class UpdateRatePlanOptions : IOptions<RatePlanResource> { /// <summary> /// The SID that identifies the resource to update /// </summary> public string PathSid { get; } /// <summary> /// An application-defined string that uniquely identifies the resource /// </summary> public string UniqueName { get; set; } /// <summary> /// A string to describe the resource /// </summary> public string FriendlyName { get; set; } /// <summary> /// Construct a new UpdateRatePlanOptions /// </summary> /// <param name="pathSid"> The SID that identifies the resource to update </param> public UpdateRatePlanOptions(string pathSid) { PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (UniqueName != null) { p.Add(new KeyValuePair<string, string>("UniqueName", UniqueName)); } if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } return p; } } /// <summary> /// DeleteRatePlanOptions /// </summary> public class DeleteRatePlanOptions : IOptions<RatePlanResource> { /// <summary> /// The SID that identifies the resource to delete /// </summary> public string PathSid { get; } /// <summary> /// Construct a new DeleteRatePlanOptions /// </summary> /// <param name="pathSid"> The SID that identifies the resource to delete </param> public DeleteRatePlanOptions(string pathSid) { PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } }
//----------------------------------------------------------------------- // <copyright file="AuthTests.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>no summary</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.IO.IsolatedStorage; using System.Reflection; using System.Text; using Csla; using Csla.Serialization; using Csla.Rules; using Csla.Test.Security; using UnitDriven; using System.Diagnostics; #if NUNIT using NUnit.Framework; using TestClass = NUnit.Framework.TestFixtureAttribute; using TestInitialize = NUnit.Framework.SetUpAttribute; using TestCleanup = NUnit.Framework.TearDownAttribute; using TestMethod = NUnit.Framework.TestAttribute; #elif MSTEST using Microsoft.VisualStudio.TestTools.UnitTesting; #endif namespace Csla.Test.Authorization { #if TESTING [DebuggerNonUserCode] [DebuggerStepThrough] #endif [TestClass()] public class AuthTests { private DataPortal.DpRoot root = DataPortal.DpRoot.NewRoot(); [TestCleanup] public void Cleanup() { ApplicationContext.RuleSet = ApplicationContext.DefaultRuleSet; } [TestMethod()] public void TestAuthCloneRules() { ApplicationContext.GlobalContext.Clear(); #pragma warning disable CS0436 // Type conflicts with imported type Security.TestPrincipal.SimulateLogin(); #pragma warning restore CS0436 // Type conflicts with imported type Assert.AreEqual(true, Csla.ApplicationContext.User.IsInRole("Admin")); #region "Pre Cloning Tests" //Is it denying read properly? Assert.AreEqual("[DenyReadOnProperty] Can't read property", root.DenyReadOnProperty, "Read should have been denied 1"); //Is it denying write properly? root.DenyWriteOnProperty = "DenyWriteOnProperty"; Assert.AreEqual("[DenyWriteOnProperty] Can't write variable", root.Auth, "Write should have been denied 2"); //Is it denying both read and write properly? Assert.AreEqual("[DenyReadWriteOnProperty] Can't read property", root.DenyReadWriteOnProperty, "Read should have been denied 3"); root.DenyReadWriteOnProperty = "DenyReadWriteONproperty"; Assert.AreEqual("[DenyReadWriteOnProperty] Can't write variable", root.Auth, "Write should have been denied 4"); //Is it allowing both read and write properly? Assert.AreEqual(root.AllowReadWriteOnProperty, root.Auth, "Read should have been allowed 5"); root.AllowReadWriteOnProperty = "No value"; Assert.AreEqual("No value", root.Auth, "Write should have been allowed 6"); #endregion #region "After Cloning Tests" //Do they work under cloning as well? DataPortal.DpRoot NewRoot = root.Clone(); ApplicationContext.GlobalContext.Clear(); //Is it denying read properly? Assert.AreEqual("[DenyReadOnProperty] Can't read property", NewRoot.DenyReadOnProperty, "Read should have been denied 7"); //Is it denying write properly? NewRoot.DenyWriteOnProperty = "DenyWriteOnProperty"; Assert.AreEqual("[DenyWriteOnProperty] Can't write variable", NewRoot.Auth, "Write should have been denied 8"); //Is it denying both read and write properly? Assert.AreEqual("[DenyReadWriteOnProperty] Can't read property", NewRoot.DenyReadWriteOnProperty, "Read should have been denied 9"); NewRoot.DenyReadWriteOnProperty = "DenyReadWriteONproperty"; Assert.AreEqual("[DenyReadWriteOnProperty] Can't write variable", NewRoot.Auth, "Write should have been denied 10"); //Is it allowing both read and write properly? Assert.AreEqual(NewRoot.AllowReadWriteOnProperty, NewRoot.Auth, "Read should have been allowed 11"); NewRoot.AllowReadWriteOnProperty = "AllowReadWriteOnProperty"; Assert.AreEqual("AllowReadWriteOnProperty", NewRoot.Auth, "Write should have been allowed 12"); #endregion #pragma warning disable CS0436 // Type conflicts with imported type Security.TestPrincipal.SimulateLogout(); #pragma warning restore CS0436 // Type conflicts with imported type } [TestMethod()] public void TestAuthBeginEditRules() { ApplicationContext.GlobalContext.Clear(); #pragma warning disable CS0436 // Type conflicts with imported type Security.TestPrincipal.SimulateLogin(); #pragma warning restore CS0436 // Type conflicts with imported type Assert.AreEqual(true, System.Threading.Thread.CurrentPrincipal.IsInRole("Admin")); root.Data = "Something new"; root.BeginEdit(); #region "Pre-Testing" root.Data = "Something new 1"; //Is it denying read properly? Assert.AreEqual("[DenyReadOnProperty] Can't read property", root.DenyReadOnProperty, "Read should have been denied"); //Is it denying write properly? root.DenyWriteOnProperty = "DenyWriteOnProperty"; Assert.AreEqual("[DenyWriteOnProperty] Can't write variable", root.Auth, "Write should have been denied"); //Is it denying both read and write properly? Assert.AreEqual("[DenyReadWriteOnProperty] Can't read property", root.DenyReadWriteOnProperty, "Read should have been denied"); root.DenyReadWriteOnProperty = "DenyReadWriteONproperty"; Assert.AreEqual("[DenyReadWriteOnProperty] Can't write variable", root.Auth, "Write should have been denied"); //Is it allowing both read and write properly? Assert.AreEqual(root.AllowReadWriteOnProperty, root.Auth, "Read should have been allowed"); root.AllowReadWriteOnProperty = "No value"; Assert.AreEqual("No value", root.Auth, "Write should have been allowed"); #endregion #region "Cancel Edit" //Cancel the edit and see if the authorization rules still work root.CancelEdit(); //Is it denying read properly? Assert.AreEqual("[DenyReadOnProperty] Can't read property", root.DenyReadOnProperty, "Read should have been denied"); //Is it denying write properly? root.DenyWriteOnProperty = "DenyWriteOnProperty"; Assert.AreEqual("[DenyWriteOnProperty] Can't write variable", root.Auth, "Write should have been denied"); //Is it denying both read and write properly? Assert.AreEqual("[DenyReadWriteOnProperty] Can't read property", root.DenyReadWriteOnProperty, "Read should have been denied"); root.DenyReadWriteOnProperty = "DenyReadWriteONproperty"; Assert.AreEqual("[DenyReadWriteOnProperty] Can't write variable", root.Auth, "Write should have been denied"); //Is it allowing both read and write properly? Assert.AreEqual(root.AllowReadWriteOnProperty, root.Auth, "Read should have been allowed"); root.AllowReadWriteOnProperty = "No value"; Assert.AreEqual("No value", root.Auth, "Write should have been allowed"); #endregion #region "Apply Edit" //Apply this edit and see if the authorization rules still work //Is it denying read properly? Assert.AreEqual("[DenyReadOnProperty] Can't read property", root.DenyReadOnProperty, "Read should have been denied"); //Is it denying write properly? root.DenyWriteOnProperty = "DenyWriteOnProperty"; Assert.AreEqual("[DenyWriteOnProperty] Can't write variable", root.Auth, "Write should have been denied"); //Is it denying both read and write properly? Assert.AreEqual("[DenyReadWriteOnProperty] Can't read property", root.DenyReadWriteOnProperty, "Read should have been denied"); root.DenyReadWriteOnProperty = "DenyReadWriteONproperty"; Assert.AreEqual("[DenyReadWriteOnProperty] Can't write variable", root.Auth, "Write should have been denied"); //Is it allowing both read and write properly? Assert.AreEqual(root.AllowReadWriteOnProperty, root.Auth, "Read should have been allowed"); root.AllowReadWriteOnProperty = "No value"; Assert.AreEqual("No value", root.Auth, "Write should have been allowed"); #endregion #pragma warning disable CS0436 // Type conflicts with imported type Security.TestPrincipal.SimulateLogout(); #pragma warning restore CS0436 // Type conflicts with imported type } [TestMethod()] public void TestAuthorizationAfterEditCycle() { Csla.ApplicationContext.GlobalContext.Clear(); Csla.Test.Security.PermissionsRoot pr = Csla.Test.Security.PermissionsRoot.NewPermissionsRoot(); #pragma warning disable CS0436 // Type conflicts with imported type Csla.Test.Security.TestPrincipal.SimulateLogin(); #pragma warning restore CS0436 // Type conflicts with imported type pr.FirstName = "something"; pr.BeginEdit(); pr.FirstName = "ba"; pr.CancelEdit(); #pragma warning disable CS0436 // Type conflicts with imported type Csla.Test.Security.TestPrincipal.SimulateLogout(); #pragma warning restore CS0436 // Type conflicts with imported type Csla.Test.Security.PermissionsRoot prClone = pr.Clone(); #pragma warning disable CS0436 // Type conflicts with imported type Csla.Test.Security.TestPrincipal.SimulateLogin(); #pragma warning restore CS0436 // Type conflicts with imported type prClone.FirstName = "somethiansdfasdf"; #pragma warning disable CS0436 // Type conflicts with imported type Csla.Test.Security.TestPrincipal.SimulateLogout(); #pragma warning restore CS0436 // Type conflicts with imported type } [ExpectedException(typeof(Csla.Security.SecurityException))] [TestMethod] public void TestUnauthorizedAccessToGet() { Csla.ApplicationContext.GlobalContext.Clear(); PermissionsRoot pr = PermissionsRoot.NewPermissionsRoot(); //this should throw an exception, since only admins have access to this property string something = pr.FirstName; } [ExpectedException(typeof(Csla.Security.SecurityException))] [TestMethod] public void TestUnauthorizedAccessToSet() { PermissionsRoot pr = PermissionsRoot.NewPermissionsRoot(); //will cause an exception, because only admins can write to property pr.FirstName = "test"; } [TestMethod] public void TestAuthorizedAccess() { Csla.ApplicationContext.GlobalContext.Clear(); #pragma warning disable CS0436 // Type conflicts with imported type Csla.Test.Security.TestPrincipal.SimulateLogin(); #pragma warning restore CS0436 // Type conflicts with imported type PermissionsRoot pr = PermissionsRoot.NewPermissionsRoot(); //should work, because we are now logged in as an admin pr.FirstName = "something"; string something = pr.FirstName; Assert.AreEqual(true, System.Threading.Thread.CurrentPrincipal.IsInRole("Admin")); //set to null so the other testmethods continue to throw exceptions #pragma warning disable CS0436 // Type conflicts with imported type Csla.Test.Security.TestPrincipal.SimulateLogout(); #pragma warning restore CS0436 // Type conflicts with imported type Assert.AreEqual(false, System.Threading.Thread.CurrentPrincipal.IsInRole("Admin")); } [TestMethod] public void TestAuthExecute() { Csla.ApplicationContext.GlobalContext.Clear(); #pragma warning disable CS0436 // Type conflicts with imported type Csla.Test.Security.TestPrincipal.SimulateLogin(); #pragma warning restore CS0436 // Type conflicts with imported type PermissionsRoot pr = PermissionsRoot.NewPermissionsRoot(); //should work, because we are now logged in as an admin pr.DoWork(); Assert.AreEqual(true, System.Threading.Thread.CurrentPrincipal.IsInRole("Admin")); //set to null so the other testmethods continue to throw exceptions #pragma warning disable CS0436 // Type conflicts with imported type Csla.Test.Security.TestPrincipal.SimulateLogout(); #pragma warning restore CS0436 // Type conflicts with imported type Assert.AreEqual(false, System.Threading.Thread.CurrentPrincipal.IsInRole("Admin")); } [TestMethod] [ExpectedException(typeof(Csla.Security.SecurityException))] public void TestUnAuthExecute() { Csla.ApplicationContext.GlobalContext.Clear(); Assert.AreEqual(false, Csla.ApplicationContext.User.IsInRole("Admin")); PermissionsRoot pr = PermissionsRoot.NewPermissionsRoot(); //should fail, because we're not an admin pr.DoWork(); } [TestMethod] public void TestAuthRuleSetsOnStaticHasPermissionMethodsWhenAddingAuthzRuleSetExplicitly() { var root = PermissionsRoot.NewPermissionsRoot(); #pragma warning disable CS0436 // Type conflicts with imported type Csla.Test.Security.TestPrincipal.SimulateLogin(); #pragma warning restore CS0436 // Type conflicts with imported type Assert.IsTrue(System.Threading.Thread.CurrentPrincipal.IsInRole("Admin")); Assert.IsFalse(System.Threading.Thread.CurrentPrincipal.IsInRole("User")); // implicit usage of ApplicationContext.RuleSet ApplicationContext.RuleSet = ApplicationContext.DefaultRuleSet; Assert.IsFalse(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot))); ApplicationContext.RuleSet = "custom1"; Assert.IsTrue(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot))); ApplicationContext.RuleSet = "custom2"; Assert.IsTrue(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot))); ApplicationContext.RuleSet = ApplicationContext.DefaultRuleSet; // directly specifying which ruleset to use Assert.IsFalse(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot), ApplicationContext.DefaultRuleSet)); Assert.IsTrue(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot), "custom1")); Assert.IsTrue(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot), "custom2")); #pragma warning disable CS0436 // Type conflicts with imported type Csla.Test.Security.TestPrincipal.SimulateLogout(); #pragma warning restore CS0436 // Type conflicts with imported type } [TestMethod] public void TestAuthRuleSetsOnStaticHasPermissionMethodsWhenAddingAuthzRuleSetUsingApplicationContextRuleSet() { var root = PermissionsRoot2.NewPermissionsRoot(); #pragma warning disable CS0436 // Type conflicts with imported type Csla.Test.Security.TestPrincipal.SimulateLogin(); #pragma warning restore CS0436 // Type conflicts with imported type Assert.IsTrue(System.Threading.Thread.CurrentPrincipal.IsInRole("Admin")); Assert.IsFalse(System.Threading.Thread.CurrentPrincipal.IsInRole("User")); //BusinessRules.AddRule(typeof(PermissionsRoot), new IsInRole(AuthorizationActions.DeleteObject, "User"), ApplicationContext.DefaultRuleSet); //BusinessRules.AddRule(typeof(PermissionsRoot), new IsInRole(AuthorizationActions.DeleteObject, "Admin"), "custom1"); //BusinessRules.AddRule(typeof(PermissionsRoot), new IsInRole(AuthorizationActions.DeleteObject, "User", "Admin"), "custom2"); // implicit usage of ApplicationContext.RuleSet ApplicationContext.RuleSet = ApplicationContext.DefaultRuleSet; Assert.IsFalse(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot2))); ApplicationContext.RuleSet = "custom1"; Assert.IsTrue(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot2))); ApplicationContext.RuleSet = "custom2"; Assert.IsTrue(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot2))); ApplicationContext.RuleSet = ApplicationContext.DefaultRuleSet; // directly specifying which ruleset to use Assert.IsFalse(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot2), ApplicationContext.DefaultRuleSet)); Assert.IsTrue(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot2), "custom1")); Assert.IsTrue(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot2), "custom2")); #pragma warning disable CS0436 // Type conflicts with imported type Csla.Test.Security.TestPrincipal.SimulateLogout(); #pragma warning restore CS0436 // Type conflicts with imported type } [TestMethod] public void TestAuthRulesCleanupAndAddAgainWhenExceptionIsThrownInAddObjectBusinessRules() { RootException.Counter = 0; ApplicationContext.RuleSet = ApplicationContext.DefaultRuleSet; // AddObjectAuthorizations should throw exception try { BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(RootException)); } catch (Exception ex) { Assert.IsInstanceOfType(ex, typeof(TargetInvocationException)); Assert.IsInstanceOfType(ex.InnerException, typeof(ArgumentException)); } // AddObjectAuthorizations should be called again and // should throw exception again try { BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(RootException)); } catch (Exception ex) { Assert.IsInstanceOfType(ex, typeof(TargetInvocationException)); Assert.IsInstanceOfType(ex.InnerException, typeof(ArgumentException)); } Assert.IsTrue(RootException.Counter == 2); } [TestMethod] public void AuthorizeRemoveFromList() { var root = new RootList(); root.RemoveAt(0); } [TestMethod] public void PerTypeAuthEditObject() { ApplicationContext.DataPortalActivator = new PerTypeAuthDPActivator(); try { Assert.IsFalse(BusinessRules.HasPermission(AuthorizationActions.EditObject, typeof(PerTypeAuthRoot))); } finally { Csla.ApplicationContext.DataPortalActivator = null; } } [TestMethod] public void PerTypeAuthEditObjectViaInterface() { ApplicationContext.DataPortalActivator = new PerTypeAuthDPActivator(); try { Assert.IsFalse(BusinessRules.HasPermission(AuthorizationActions.EditObject, typeof(IPerTypeAuthRoot))); } finally { Csla.ApplicationContext.DataPortalActivator = null; } } [TestMethod] public void PerTypeAuthCreateWithCriteria() { Assert.IsTrue( BusinessRules.HasPermission( AuthorizationActions.CreateObject, typeof(PermissionRootWithCriteria), new object[] { new PermissionRootWithCriteria.Criteria() })); Assert.IsFalse( BusinessRules.HasPermission( AuthorizationActions.CreateObject, typeof(PermissionRootWithCriteria), new[] { new object() })); Assert.IsFalse( BusinessRules.HasPermission( AuthorizationActions.CreateObject, typeof(PermissionRootWithCriteria), (object[])null)); } [TestMethod] public void PerTypeAuthFetchWithCriteria() { Assert.IsTrue( BusinessRules.HasPermission( AuthorizationActions.GetObject, typeof(PermissionRootWithCriteria), new object[] { new PermissionRootWithCriteria.Criteria() })); Assert.IsFalse( BusinessRules.HasPermission( AuthorizationActions.GetObject, typeof(PermissionRootWithCriteria), new[] { new object() })); Assert.IsFalse( BusinessRules.HasPermission( AuthorizationActions.GetObject, typeof(PermissionRootWithCriteria), (object[])null)); } [TestMethod] public void PerTypeAuthDeleteWithCriteria() { Assert.IsTrue( BusinessRules.HasPermission( AuthorizationActions.DeleteObject, typeof(PermissionRootWithCriteria), new object[] { new PermissionRootWithCriteria.Criteria() })); Assert.IsFalse( BusinessRules.HasPermission( AuthorizationActions.DeleteObject, typeof(PermissionRootWithCriteria), new[] { new object() })); Assert.IsFalse( BusinessRules.HasPermission( AuthorizationActions.DeleteObject, typeof(PermissionRootWithCriteria), (object[])null)); } } public class PerTypeAuthDPActivator : Server.IDataPortalActivator { public object CreateInstance(Type requestedType) { return Activator.CreateInstance(ResolveType(requestedType)); } public void FinalizeInstance(object obj) { } public void InitializeInstance(object obj) { } public Type ResolveType(Type requestedType) { if (requestedType.Equals(typeof(IPerTypeAuthRoot))) return typeof(PerTypeAuthRoot); else return requestedType; } } public interface IPerTypeAuthRoot { } [Serializable] public class PerTypeAuthRoot : BusinessBase<PerTypeAuthRoot>, IPerTypeAuthRoot { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static void AddObjectAuthorizationRules() { Csla.Rules.BusinessRules.AddRule( typeof(PerTypeAuthRoot), new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.EditObject, "Test")); } } [Serializable] public class RootList : BusinessListBase<RootList, ChildItem> { public RootList() { using (SuppressListChangedEvents) { Add(Csla.DataPortal.CreateChild<ChildItem>()); } } } [Serializable] public class ChildItem : BusinessBase<ChildItem> { protected override void AddBusinessRules() { base.AddBusinessRules(); BusinessRules.AddRule(new NoAuth(AuthorizationActions.DeleteObject)); } private class NoAuth : Csla.Rules.AuthorizationRule { public NoAuth(AuthorizationActions action) : base(action) {} protected override void Execute(IAuthorizationContext context) { context.HasPermission = false; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime.InteropServices; using System.Threading.Tasks; using Xunit; namespace System.IO.Compression.Test { public class zip_ReadTests { [Fact] public static async Task ReadNormal() { await ZipTest.IsZipSameAsDirAsync( ZipTest.zfile("normal.zip"), ZipTest.zfolder("normal"), ZipArchiveMode.Read); await ZipTest.IsZipSameAsDirAsync( ZipTest.zfile("fake64.zip"), ZipTest.zfolder("small"), ZipArchiveMode.Read); await ZipTest.IsZipSameAsDirAsync( ZipTest.zfile("empty.zip"), ZipTest.zfolder("empty"), ZipArchiveMode.Read); await ZipTest.IsZipSameAsDirAsync( ZipTest.zfile("appended.zip"), ZipTest.zfolder("small"), ZipArchiveMode.Read); await ZipTest.IsZipSameAsDirAsync( ZipTest.zfile("prepended.zip"), ZipTest.zfolder("small"), ZipArchiveMode.Read); await ZipTest.IsZipSameAsDirAsync( ZipTest.zfile("emptydir.zip"), ZipTest.zfolder("emptydir"), ZipArchiveMode.Read); await ZipTest.IsZipSameAsDirAsync( ZipTest.zfile("small.zip"), ZipTest.zfolder("small"), ZipArchiveMode.Read); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // [ActiveIssue(846, PlatformID.AnyUnix)] { await ZipTest.IsZipSameAsDirAsync( ZipTest.zfile("unicode.zip"), ZipTest.zfolder("unicode"), ZipArchiveMode.Read); } } [Fact] public static async Task ReadStreaming() { //don't include large, because that means loading the whole thing in memory await TestStreamingRead(ZipTest.zfile("normal.zip"), ZipTest.zfolder("normal")); await TestStreamingRead(ZipTest.zfile("fake64.zip"), ZipTest.zfolder("small")); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // [ActiveIssue(846, PlatformID.AnyUnix)] { await TestStreamingRead(ZipTest.zfile("unicode.zip"), ZipTest.zfolder("unicode")); } await TestStreamingRead(ZipTest.zfile("empty.zip"), ZipTest.zfolder("empty")); await TestStreamingRead(ZipTest.zfile("appended.zip"), ZipTest.zfolder("small")); await TestStreamingRead(ZipTest.zfile("prepended.zip"), ZipTest.zfolder("small")); await TestStreamingRead(ZipTest.zfile("emptydir.zip"), ZipTest.zfolder("emptydir")); } private static async Task TestStreamingRead(String zipFile, String directory) { using (var stream = await StreamHelpers.CreateTempCopyStream(zipFile)) { Stream wrapped = new WrappedStream(stream, true, false, false, null); ZipTest.IsZipSameAsDir(wrapped, directory, ZipArchiveMode.Read, false, false); Assert.False(wrapped.CanRead, "Wrapped stream should be closed at this point"); //check that it was closed } } [Fact] public static async Task ReadStreamOps() { using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip")), ZipArchiveMode.Read)) { foreach (ZipArchiveEntry e in archive.Entries) { using (Stream s = e.Open()) { Assert.True(s.CanRead, "Can read to read archive"); Assert.False(s.CanWrite, "Can't write to read archive"); Assert.False(s.CanSeek, "Can't seek on archive"); Assert.Equal(ZipTest.LengthOfUnseekableStream(s), e.Length); //"Length is not correct on unseekable stream" } } } } [Fact] public static async Task ReadInterleaved() { using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip")))) { ZipArchiveEntry e1 = archive.GetEntry("first.txt"); ZipArchiveEntry e2 = archive.GetEntry("notempty/second.txt"); //read all of e1 and e2's contents Byte[] e1readnormal = new Byte[e1.Length]; Byte[] e2readnormal = new Byte[e2.Length]; Byte[] e1interleaved = new Byte[e1.Length]; Byte[] e2interleaved = new Byte[e2.Length]; using (Stream e1s = e1.Open()) { ZipTest.ReadBytes(e1s, e1readnormal, e1.Length); } using (Stream e2s = e2.Open()) { ZipTest.ReadBytes(e2s, e2readnormal, e2.Length); } //now read interleaved, assume we are working with < 4gb files const Int32 bytesAtATime = 15; using (Stream e1s = e1.Open(), e2s = e2.Open()) { Int32 e1pos = 0; Int32 e2pos = 0; while (e1pos < e1.Length || e2pos < e2.Length) { if (e1pos < e1.Length) { Int32 e1bytesRead = e1s.Read(e1interleaved, e1pos, bytesAtATime + e1pos > e1.Length ? (Int32)e1.Length - e1pos : bytesAtATime); e1pos += e1bytesRead; } if (e2pos < e2.Length) { Int32 e2bytesRead = e2s.Read(e2interleaved, e2pos, bytesAtATime + e2pos > e2.Length ? (Int32)e2.Length - e2pos : bytesAtATime); e2pos += e2bytesRead; } } } //now compare to original read ZipTest.ArraysEqual<Byte>(e1readnormal, e1interleaved, e1readnormal.Length); ZipTest.ArraysEqual<Byte>(e2readnormal, e2interleaved, e2readnormal.Length); //now read one entry interleaved Byte[] e1selfInterleaved1 = new Byte[e1.Length]; Byte[] e1selfInterleaved2 = new Byte[e2.Length]; using (Stream s1 = e1.Open(), s2 = e1.Open()) { Int32 s1pos = 0; Int32 s2pos = 0; while (s1pos < e1.Length || s2pos < e1.Length) { if (s1pos < e1.Length) { Int32 s1bytesRead = s1.Read(e1interleaved, s1pos, bytesAtATime + s1pos > e1.Length ? (Int32)e1.Length - s1pos : bytesAtATime); s1pos += s1bytesRead; } if (s2pos < e1.Length) { Int32 s2bytesRead = s2.Read(e2interleaved, s2pos, bytesAtATime + s2pos > e1.Length ? (Int32)e1.Length - s2pos : bytesAtATime); s2pos += s2bytesRead; } } } //now compare to original read ZipTest.ArraysEqual<Byte>(e1readnormal, e1selfInterleaved1, e1readnormal.Length); ZipTest.ArraysEqual<Byte>(e1readnormal, e1selfInterleaved2, e1readnormal.Length); } } [Fact] public static async Task ReadModeInvalidOpsTest() { ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip")), ZipArchiveMode.Read); ZipArchiveEntry e = archive.GetEntry("first.txt"); //should also do it on deflated stream //on archive Assert.Throws<NotSupportedException>(() => archive.CreateEntry("hi there")); //"Should not be able to create entry" //on entry Assert.Throws<NotSupportedException>(() => e.Delete()); //"Should not be able to delete entry" //Throws<NotSupportedException>(() => e.MoveTo("dirka")); Assert.Throws<NotSupportedException>(() => e.LastWriteTime = new DateTimeOffset()); //"Should not be able to update time" //on stream Stream s = e.Open(); Assert.Throws<NotSupportedException>(() => s.Flush()); //"Should not be able to flush on read stream" Assert.Throws<NotSupportedException>(() => s.WriteByte(25)); //"should not be able to write to read stream" Assert.Throws<NotSupportedException>(() => s.Position = 4); //"should not be able to seek on read stream" Assert.Throws<NotSupportedException>(() => s.Seek(0, SeekOrigin.Begin)); //"should not be able to seek on read stream" Assert.Throws<NotSupportedException>(() => s.SetLength(0)); //"should not be able to resize read stream" archive.Dispose(); //after disposed Assert.Throws<ObjectDisposedException>(() => { var x = archive.Entries; }); //"Should not be able to get entries on disposed archive" Assert.Throws<NotSupportedException>(() => archive.CreateEntry("dirka")); //"should not be able to create on disposed archive" Assert.Throws<ObjectDisposedException>(() => e.Open()); //"should not be able to open on disposed archive" Assert.Throws<NotSupportedException>(() => e.Delete()); //"should not be able to delete on disposed archive" Assert.Throws<ObjectDisposedException>(() => { e.LastWriteTime = new DateTimeOffset(); }); //"Should not be able to update on disposed archive" Assert.Throws<NotSupportedException>(() => s.ReadByte()); //"should not be able to read on disposed archive" s.Dispose(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.ServiceBus.UnitTests.Management { using System; using System.Linq; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Microsoft.Azure.ServiceBus.Core; using Microsoft.Azure.ServiceBus.Management; using Xunit; public class ManagementClientTests { [Fact] [LiveTest] [DisplayTestMethodName] public async Task BasicQueueCrudTest() { var queueName = Guid.NewGuid().ToString("D").Substring(0, 8); var client = new ManagementClient(new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString)); try { var qd = new QueueDescription(queueName) { AutoDeleteOnIdle = TimeSpan.FromHours(1), DefaultMessageTimeToLive = TimeSpan.FromDays(2), DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1), EnableBatchedOperations = true, EnableDeadLetteringOnMessageExpiration = true, EnablePartitioning = false, ForwardDeadLetteredMessagesTo = null, ForwardTo = null, LockDuration = TimeSpan.FromSeconds(45), MaxDeliveryCount = 8, MaxSizeInMB = 2048, RequiresDuplicateDetection = true, RequiresSession = true, UserMetadata = nameof(BasicQueueCrudTest) }; qd.AuthorizationRules.Add(new SharedAccessAuthorizationRule( "allClaims", new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen })); var finalQ = await client.CreateQueueAsync(qd); Assert.Equal(qd, finalQ); var getQ = await client.GetQueueAsync(qd.Path); Assert.Equal(qd, getQ); getQ.EnableBatchedOperations = false; getQ.MaxDeliveryCount = 9; getQ.AuthorizationRules.Clear(); getQ.AuthorizationRules.Add(new SharedAccessAuthorizationRule( "noManage", new[] { AccessRights.Send, AccessRights.Listen })); var updatedQ = await client.UpdateQueueAsync(getQ); Assert.Equal(getQ, updatedQ); var exists = await client.QueueExistsAsync(queueName); Assert.True(exists); var queues = await client.GetQueuesAsync(); Assert.True(queues.Count >= 1); Assert.Contains(queues, e => e.Path.Equals(queueName, StringComparison.OrdinalIgnoreCase)); await client.DeleteQueueAsync(updatedQ.Path); await Assert.ThrowsAsync<MessagingEntityNotFoundException>( async () => { await client.GetQueueAsync(qd.Path); }); exists = await client.QueueExistsAsync(queueName); Assert.False(exists); } catch { await SafeDeleteQueue(client, queueName); throw; } finally { await client.CloseAsync(); } } [Fact] [LiveTest] [DisplayTestMethodName] public async Task BasicTopicCrudTest() { var topicName = Guid.NewGuid().ToString("D").Substring(0, 8); var client = new ManagementClient(new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString)); try { var td = new TopicDescription(topicName) { AutoDeleteOnIdle = TimeSpan.FromHours(1), DefaultMessageTimeToLive = TimeSpan.FromDays(2), DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1), EnableBatchedOperations = true, EnablePartitioning = false, MaxSizeInMB = 2048, RequiresDuplicateDetection = true, UserMetadata = nameof(BasicTopicCrudTest) }; td.AuthorizationRules.Add(new SharedAccessAuthorizationRule( "allClaims", new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen })); var createdT = await client.CreateTopicAsync(td); Assert.Equal(td, createdT); var getT = await client.GetTopicAsync(td.Path); Assert.Equal(td, getT); getT.EnableBatchedOperations = false; getT.DefaultMessageTimeToLive = TimeSpan.FromDays(3); var updatedT = await client.UpdateTopicAsync(getT); Assert.Equal(getT, updatedT); var exists = await client.TopicExistsAsync(topicName); Assert.True(exists); var topics = await client.GetTopicsAsync(); Assert.True(topics.Count >= 1); Assert.Contains(topics, e => e.Path.Equals(topicName, StringComparison.OrdinalIgnoreCase)); await client.DeleteTopicAsync(updatedT.Path); await Assert.ThrowsAsync<MessagingEntityNotFoundException>( async () => { await client.GetTopicAsync(td.Path); }); exists = await client.TopicExistsAsync(topicName); Assert.False(exists); } catch { await SafeDeleteTopic(client, topicName); throw; } finally { await client.CloseAsync(); } } [Fact] [LiveTest] [DisplayTestMethodName] public async Task BasicSubscriptionCrudTest() { var topicName = Guid.NewGuid().ToString("D").Substring(0, 8); var client = new ManagementClient(new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString)); try { await client.CreateTopicAsync(topicName); var subscriptionName = Guid.NewGuid().ToString("D").Substring(0, 8); var sd = new SubscriptionDescription(topicName, subscriptionName) { AutoDeleteOnIdle = TimeSpan.FromHours(1), DefaultMessageTimeToLive = TimeSpan.FromDays(2), EnableDeadLetteringOnMessageExpiration = true, EnableBatchedOperations = false, ForwardDeadLetteredMessagesTo = null, ForwardTo = null, LockDuration = TimeSpan.FromSeconds(45), MaxDeliveryCount = 8, RequiresSession = true, UserMetadata = nameof(BasicSubscriptionCrudTest) }; var createdS = await client.CreateSubscriptionAsync(sd); Assert.Equal(sd, createdS); var getS = await client.GetSubscriptionAsync(sd.TopicPath, sd.SubscriptionName); Assert.Equal(sd, getS); getS.DefaultMessageTimeToLive = TimeSpan.FromDays(3); getS.MaxDeliveryCount = 9; var updatedS = await client.UpdateSubscriptionAsync(getS); Assert.Equal(getS, updatedS); var exists = await client.SubscriptionExistsAsync(topicName, subscriptionName); Assert.True(exists); var subs = await client.GetSubscriptionsAsync(topicName); Assert.Equal(1, subs.Count); await client.DeleteSubscriptionAsync(sd.TopicPath, sd.SubscriptionName); await Assert.ThrowsAsync<MessagingEntityNotFoundException>( async () => { await client.GetSubscriptionAsync(sd.TopicPath, sd.SubscriptionName); }); await client.DeleteTopicAsync(sd.TopicPath); exists = await client.SubscriptionExistsAsync(topicName, subscriptionName); Assert.False(exists); } catch { await SafeDeleteTopic(client, topicName); throw; } finally { await client.CloseAsync(); } } [Fact] [LiveTest] [DisplayTestMethodName] public async Task BasicRulesCrudTest() { var topicName = Guid.NewGuid().ToString("D").Substring(0, 8); var subscriptionName = Guid.NewGuid().ToString("D").Substring(0, 8); var client = new ManagementClient(new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString)); try { await client.CreateTopicAsync(topicName); await client.CreateSubscriptionAsync( new SubscriptionDescription(topicName, subscriptionName), new RuleDescription("rule0", new FalseFilter())); var sqlFilter = new SqlFilter("stringValue = @stringParam AND intValue = @intParam AND longValue = @longParam AND dateValue = @dateParam AND timeSpanValue = @timeSpanParam"); sqlFilter.Parameters.Add("@stringParam", "string"); sqlFilter.Parameters.Add("@intParam", (int)1); sqlFilter.Parameters.Add("@longParam", (long)12); sqlFilter.Parameters.Add("@dateParam", DateTime.UtcNow); sqlFilter.Parameters.Add("@timeSpanParam", TimeSpan.FromDays(1)); var rule1 = new RuleDescription { Name = "rule1", Filter = sqlFilter, Action = new SqlRuleAction("SET a='b'") }; await client.CreateRuleAsync(topicName, subscriptionName, rule1); var correlationFilter = new CorrelationFilter() { ContentType = "contentType", CorrelationId = "correlationId", Label = "label", MessageId = "messageId", ReplyTo = "replyTo", ReplyToSessionId = "replyToSessionId", SessionId = "sessionId", To = "to" }; correlationFilter.Properties.Add("customKey", "customValue"); var rule2 = new RuleDescription() { Name = "rule2", Filter = correlationFilter, Action = null }; await client.CreateRuleAsync(topicName, subscriptionName, rule2); var rules = await client.GetRulesAsync(topicName, subscriptionName); Assert.True(rules.Count == 3); Assert.Equal("rule0", rules[0].Name); Assert.Equal(rule1, rules[1]); Assert.Equal(rule2, rules[2]); ((CorrelationFilter)rule2.Filter).CorrelationId = "correlationIdModified"; var updatedRule2 = await client.UpdateRuleAsync(topicName, subscriptionName, rule2); Assert.Equal(rule2, updatedRule2); var defaultRule = await client.GetRuleAsync(topicName, subscriptionName, "rule0"); Assert.NotNull(defaultRule); await client.DeleteRuleAsync(topicName, subscriptionName, "rule0"); await Assert.ThrowsAsync<MessagingEntityNotFoundException>( async () => { await client.GetRuleAsync(topicName, subscriptionName, "rule0"); }); await client.DeleteTopicAsync(topicName); } catch { await SafeDeleteTopic(client, topicName); throw; } finally { await client.CloseAsync(); } } [Fact] [LiveTest] [DisplayTestMethodName] public async Task GetQueueRuntimeInfoTest() { var queueName = Guid.NewGuid().ToString("D").Substring(0, 8); var client = new ManagementClient(new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString)); var qClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName); try { // Fixing Created Time var qd = await client.CreateQueueAsync(queueName); // Changing Last Updated Time qd.AutoDeleteOnIdle = TimeSpan.FromMinutes(100); var updatedQ = await client.UpdateQueueAsync(qd); // Populating 1 active message, 1 dead letter message and 1 scheduled message // Changing Last Accessed Time await qClient.SendAsync(new Message() { MessageId = "1" }); await qClient.SendAsync(new Message() { MessageId = "2" }); await qClient.SendAsync(new Message() { MessageId = "3", ScheduledEnqueueTimeUtc = DateTime.UtcNow.AddDays(1) }); var msg = await qClient.InnerReceiver.ReceiveAsync(); await qClient.DeadLetterAsync(msg.SystemProperties.LockToken); var runtimeInfos = await client.GetQueuesRuntimeInfoAsync(); Assert.True(runtimeInfos.Count > 0); var runtimeInfo = runtimeInfos.FirstOrDefault(e => e.Path.Equals(queueName, StringComparison.OrdinalIgnoreCase)); Assert.NotNull(runtimeInfo); Assert.Equal(queueName, runtimeInfo.Path); Assert.True(runtimeInfo.CreatedAt < runtimeInfo.UpdatedAt); Assert.True(runtimeInfo.UpdatedAt < runtimeInfo.AccessedAt); Assert.Equal(1, runtimeInfo.MessageCountDetails.ActiveMessageCount); Assert.Equal(1, runtimeInfo.MessageCountDetails.DeadLetterMessageCount); Assert.Equal(1, runtimeInfo.MessageCountDetails.ScheduledMessageCount); Assert.Equal(3, runtimeInfo.MessageCount); Assert.True(runtimeInfo.SizeInBytes > 0); var singleRuntimeInfo = await client.GetQueueRuntimeInfoAsync(runtimeInfo.Path); Assert.Equal(runtimeInfo.AccessedAt, singleRuntimeInfo.AccessedAt); Assert.Equal(runtimeInfo.CreatedAt, singleRuntimeInfo.CreatedAt); Assert.Equal(runtimeInfo.UpdatedAt, singleRuntimeInfo.UpdatedAt); Assert.Equal(runtimeInfo.MessageCount, singleRuntimeInfo.MessageCount); Assert.Equal(runtimeInfo.MessageCountDetails.ActiveMessageCount, singleRuntimeInfo.MessageCountDetails.ActiveMessageCount); Assert.Equal(runtimeInfo.MessageCountDetails.DeadLetterMessageCount, singleRuntimeInfo.MessageCountDetails.DeadLetterMessageCount); Assert.Equal(runtimeInfo.MessageCountDetails.ScheduledMessageCount, singleRuntimeInfo.MessageCountDetails.ScheduledMessageCount); Assert.Equal(runtimeInfo.SizeInBytes, singleRuntimeInfo.SizeInBytes); await client.DeleteQueueAsync(queueName); } catch { await SafeDeleteQueue(client, queueName); throw; } finally { await qClient.CloseAsync(); await client.CloseAsync(); } } [Fact] [LiveTest] [DisplayTestMethodName] public async Task GetSubscriptionRuntimeInfoTest() { var topicName = Guid.NewGuid().ToString("D").Substring(0, 8); var subscriptionName = Guid.NewGuid().ToString("D").Substring(0, 8); var client = new ManagementClient(new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString)); var sender = new MessageSender(TestUtility.NamespaceConnectionString, topicName); var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, EntityNameHelper.FormatSubscriptionPath(topicName, subscriptionName)); try { var td = await client.CreateTopicAsync(topicName); // Changing Last Updated Time td.AutoDeleteOnIdle = TimeSpan.FromMinutes(100); await client.UpdateTopicAsync(td); var sd = await client.CreateSubscriptionAsync(topicName, subscriptionName); // Changing Last Updated Time for subscription sd.AutoDeleteOnIdle = TimeSpan.FromMinutes(100); await client.UpdateSubscriptionAsync(sd); // Populating 1 active message, 1 dead letter message and 1 scheduled message // Changing Last Accessed Time await sender.SendAsync(new Message() { MessageId = "1" }); await sender.SendAsync(new Message() { MessageId = "2" }); await sender.SendAsync(new Message() { MessageId = "3", ScheduledEnqueueTimeUtc = DateTime.UtcNow.AddDays(1) }); var msg = await receiver.ReceiveAsync(); await receiver.DeadLetterAsync(msg.SystemProperties.LockToken); var subscriptionsRI = await client.GetSubscriptionsRuntimeInfoAsync(topicName); var subscriptionRI = subscriptionsRI.FirstOrDefault(s => subscriptionName.Equals(s.SubscriptionName, StringComparison.OrdinalIgnoreCase)); Assert.Equal(topicName, subscriptionRI.TopicPath); Assert.Equal(subscriptionName, subscriptionRI.SubscriptionName); Assert.True(subscriptionRI.CreatedAt < subscriptionRI.UpdatedAt); Assert.True(subscriptionRI.UpdatedAt < subscriptionRI.AccessedAt); Assert.Equal(1, subscriptionRI.MessageCountDetails.ActiveMessageCount); Assert.Equal(1, subscriptionRI.MessageCountDetails.DeadLetterMessageCount); Assert.Equal(0, subscriptionRI.MessageCountDetails.ScheduledMessageCount); Assert.Equal(2, subscriptionRI.MessageCount); var singleSubscriptionRI = await client.GetSubscriptionRuntimeInfoAsync(topicName, subscriptionName); Assert.Equal(subscriptionRI.CreatedAt, singleSubscriptionRI.CreatedAt); Assert.Equal(subscriptionRI.AccessedAt, singleSubscriptionRI.AccessedAt); Assert.Equal(subscriptionRI.UpdatedAt, singleSubscriptionRI.UpdatedAt); Assert.Equal(subscriptionRI.SubscriptionName, singleSubscriptionRI.SubscriptionName); Assert.Equal(subscriptionRI.MessageCount, singleSubscriptionRI.MessageCount); Assert.Equal(subscriptionRI.MessageCountDetails.ActiveMessageCount, singleSubscriptionRI.MessageCountDetails.ActiveMessageCount); Assert.Equal(subscriptionRI.MessageCountDetails.DeadLetterMessageCount, singleSubscriptionRI.MessageCountDetails.DeadLetterMessageCount); Assert.Equal(subscriptionRI.MessageCountDetails.ScheduledMessageCount, singleSubscriptionRI.MessageCountDetails.ScheduledMessageCount); Assert.Equal(subscriptionRI.TopicPath, singleSubscriptionRI.TopicPath); await client.DeleteSubscriptionAsync(topicName, subscriptionName); await client.DeleteTopicAsync(topicName); } catch { await SafeDeleteTopic(client, topicName); throw; } finally { await sender.CloseAsync(); await receiver.CloseAsync(); await client.CloseAsync(); } } [Fact] [LiveTest] [DisplayTestMethodName] public async Task GetTopicRuntimeInfoTest() { var topicName = Guid.NewGuid().ToString("D").Substring(0, 8); var subscriptionName = Guid.NewGuid().ToString("D").Substring(0, 8); var client = new ManagementClient(new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString)); var sender = new MessageSender(TestUtility.NamespaceConnectionString, topicName); try { var td = await client.CreateTopicAsync(topicName); // Changing Last Updated Time td.AutoDeleteOnIdle = TimeSpan.FromMinutes(100); await client.UpdateTopicAsync(td); await client.CreateSubscriptionAsync(topicName, subscriptionName); // Populating 1 active message and 1 scheduled message // Changing Last Accessed Time await sender.SendAsync(new Message() { MessageId = "1" }); await sender.SendAsync(new Message() { MessageId = "2" }); await sender.SendAsync(new Message() { MessageId = "3", ScheduledEnqueueTimeUtc = DateTime.UtcNow.AddDays(1) }); var topicsRI = await client.GetTopicsRuntimeInfoAsync(); var topicRI = topicsRI.FirstOrDefault(t => topicName.Equals(t.Path, StringComparison.OrdinalIgnoreCase)); Assert.Equal(topicName, topicRI.Path); Assert.True(topicRI.CreatedAt < topicRI.UpdatedAt); Assert.True(topicRI.UpdatedAt < topicRI.AccessedAt); Assert.Equal(0, topicRI.MessageCountDetails.ActiveMessageCount); Assert.Equal(0, topicRI.MessageCountDetails.DeadLetterMessageCount); Assert.Equal(1, topicRI.MessageCountDetails.ScheduledMessageCount); Assert.Equal(1, topicRI.SubscriptionCount); Assert.True(topicRI.SizeInBytes > 0); var singleTopicRI = await client.GetTopicRuntimeInfoAsync(topicRI.Path); Assert.Equal(topicRI.AccessedAt, singleTopicRI.AccessedAt); Assert.Equal(topicRI.CreatedAt, singleTopicRI.CreatedAt); Assert.Equal(topicRI.UpdatedAt, singleTopicRI.UpdatedAt); Assert.Equal(topicRI.MessageCountDetails.ActiveMessageCount, singleTopicRI.MessageCountDetails.ActiveMessageCount); Assert.Equal(topicRI.MessageCountDetails.DeadLetterMessageCount, singleTopicRI.MessageCountDetails.DeadLetterMessageCount); Assert.Equal(topicRI.MessageCountDetails.ScheduledMessageCount, singleTopicRI.MessageCountDetails.ScheduledMessageCount); Assert.Equal(topicRI.SizeInBytes, singleTopicRI.SizeInBytes); Assert.Equal(topicRI.SubscriptionCount, singleTopicRI.SubscriptionCount); await client.DeleteSubscriptionAsync(topicName, subscriptionName); await client.DeleteTopicAsync(topicName); } catch { await SafeDeleteTopic(client, topicName); throw; } finally { await sender.CloseAsync(); await client.CloseAsync(); } } [Fact] [LiveTest] [DisplayTestMethodName] public async Task MessagingEntityNotFoundExceptionTest() { var client = new ManagementClient(new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString)); try { await Assert.ThrowsAsync<MessagingEntityNotFoundException>( async () => { await client.GetQueueAsync("NonExistingPath"); }); await Assert.ThrowsAsync<MessagingEntityNotFoundException>( async () => { await client.GetSubscriptionAsync("NonExistingTopic", "NonExistingPath"); }); await Assert.ThrowsAsync<MessagingEntityNotFoundException>( async () => { await client.UpdateQueueAsync(new QueueDescription("NonExistingPath")); }); await Assert.ThrowsAsync<MessagingEntityNotFoundException>( async () => { await client.UpdateTopicAsync(new TopicDescription("NonExistingPath")); }); await Assert.ThrowsAsync<MessagingEntityNotFoundException>( async () => { await client.UpdateSubscriptionAsync(new SubscriptionDescription("NonExistingTopic", "NonExistingPath")); }); await Assert.ThrowsAsync<MessagingEntityNotFoundException>( async () => { await client.DeleteQueueAsync("NonExistingPath"); }); await Assert.ThrowsAsync<MessagingEntityNotFoundException>( async () => { await client.DeleteTopicAsync("NonExistingPath"); }); await Assert.ThrowsAsync<MessagingEntityNotFoundException>( async () => { await client.DeleteSubscriptionAsync("NonExistingTopic", "NonExistingPath"); }); var queueName = Guid.NewGuid().ToString("D").Substring(0, 8); var topicName = Guid.NewGuid().ToString("D").Substring(0, 8); try { await client.CreateQueueAsync(queueName); await client.CreateTopicAsync(topicName); await Assert.ThrowsAsync<MessagingEntityNotFoundException>( async () => { await client.GetQueueAsync(topicName); }); await Assert.ThrowsAsync<MessagingEntityNotFoundException>( async () => { await client.GetTopicAsync(queueName); }); // Cleanup await client.DeleteQueueAsync(queueName); await client.DeleteTopicAsync(topicName); } catch { await Task.WhenAll(SafeDeleteQueue(client, queueName), SafeDeleteTopic(client, topicName)); throw; } } finally { await client.CloseAsync(); } } [Fact] [LiveTest] [DisplayTestMethodName] public async Task MessagingEntityAlreadyExistsExceptionTest() { var queueName = Guid.NewGuid().ToString("D").Substring(0, 8); var topicName = Guid.NewGuid().ToString("D").Substring(0, 8); var subscriptionName = Guid.NewGuid().ToString("D").Substring(0, 8); var client = new ManagementClient(new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString)); try { await client.CreateQueueAsync(queueName); await client.CreateTopicAsync(topicName); await client.CreateSubscriptionAsync(topicName, subscriptionName); await Assert.ThrowsAsync<MessagingEntityAlreadyExistsException>( async () => { await client.CreateQueueAsync(queueName); }); await Assert.ThrowsAsync<MessagingEntityAlreadyExistsException>( async () => { await client.CreateTopicAsync(topicName); }); await Assert.ThrowsAsync<MessagingEntityAlreadyExistsException>( async () => { await client.CreateSubscriptionAsync(topicName, subscriptionName); }); // Cleanup await client.DeleteQueueAsync(queueName); await client.DeleteTopicAsync(topicName); } catch { await Task.WhenAll(SafeDeleteTopic(client, topicName), SafeDeleteQueue(client, queueName)); throw; } finally { await client.CloseAsync(); } } public static IEnumerable<object[]> TestData_EntityNameValidationTest => new[] { new object[] {"qq@", true}, new object[] {"qq/", true}, new object[] {"/qq", true}, new object[] {"qq\\", true}, new object[] {"q/q", false}, new object[] {"qq?", true}, new object[] {"qq#", true}, }; [Theory] [MemberData(nameof(TestData_EntityNameValidationTest))] [LiveTest] [DisplayTestMethodName] public void EntityNameValidationTest(string entityName, bool isPathSeparatorAllowed) { Assert.Throws<ArgumentException>( () => { if (isPathSeparatorAllowed) { EntityNameHelper.CheckValidQueueName(entityName); } else { EntityNameHelper.CheckValidSubscriptionName(entityName); } }); } [Fact] [LiveTest] [DisplayTestMethodName] public async Task ForwardingEntitySetupTest() { // queueName --Fwd to--> destinationName --fwd dlq to--> dqlDestinationName var queueName = Guid.NewGuid().ToString("D").Substring(0, 8); var destinationName = Guid.NewGuid().ToString("D").Substring(0, 8); var dlqDestinationName = Guid.NewGuid().ToString("D").Substring(0, 8); var client = new ManagementClient(new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString)); var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); try { var dlqDestinationQ = await client.CreateQueueAsync(dlqDestinationName); var destinationQ = await client.CreateQueueAsync( new QueueDescription(destinationName) { ForwardDeadLetteredMessagesTo = dlqDestinationName }); var qd = new QueueDescription(queueName) { ForwardTo = destinationName }; var baseQ = await client.CreateQueueAsync(qd); await sender.SendAsync(new Message() { MessageId = "mid" }); await sender.CloseAsync(); var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, destinationName); var msg = await receiver.ReceiveAsync(); Assert.NotNull(msg); Assert.Equal("mid", msg.MessageId); await receiver.DeadLetterAsync(msg.SystemProperties.LockToken); await receiver.CloseAsync(); receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, dlqDestinationName); msg = await receiver.ReceiveAsync(); Assert.NotNull(msg); Assert.Equal("mid", msg.MessageId); await receiver.CompleteAsync(msg.SystemProperties.LockToken); await receiver.CloseAsync(); await client.DeleteQueueAsync(queueName); await client.DeleteQueueAsync(destinationName); await client.DeleteQueueAsync(dlqDestinationName); } catch { await Task.WhenAll(SafeDeleteQueue(client, queueName), SafeDeleteQueue(client, destinationName), SafeDeleteQueue(client, dlqDestinationName)); throw; } finally { await client.CloseAsync(); } } [Fact] [LiveTest] [DisplayTestMethodName] public void AuthRulesEqualityCheckTest() { var qd = new QueueDescription("a"); var rule1 = new SharedAccessAuthorizationRule("sendListen", new List<AccessRights> { AccessRights.Listen, AccessRights.Send }); var rule2 = new SharedAccessAuthorizationRule("manage", new List<AccessRights> { AccessRights.Listen, AccessRights.Send, AccessRights.Manage }); qd.AuthorizationRules.Add(rule1); qd.AuthorizationRules.Add(rule2); var qd2 = new QueueDescription("a"); qd2.AuthorizationRules.Add(new SharedAccessAuthorizationRule(rule2.KeyName, rule2.PrimaryKey, rule2.SecondaryKey, rule2.Rights)); qd2.AuthorizationRules.Add(new SharedAccessAuthorizationRule(rule1.KeyName, rule1.PrimaryKey, rule1.SecondaryKey, rule1.Rights)); Assert.Equal(qd, qd2); } [Fact] [LiveTest] [DisplayTestMethodName] public async Task QueueDescriptionParsedFromResponseEqualityCheckTest() { var client = new ManagementClient(new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString)); var name = Guid.NewGuid().ToString("D").Substring(0, 8); try { var queueDescription = new QueueDescription(name); var createdQueueDescription = await client.CreateQueueAsync(queueDescription); var identicalQueueDescription = new QueueDescription(name); Assert.Equal(identicalQueueDescription, createdQueueDescription); await client.DeleteQueueAsync(name); } catch { await SafeDeleteQueue(client, name); throw; } finally { await client.CloseAsync(); } } [Fact] [LiveTest] [DisplayTestMethodName] public async Task TopicDescriptionParsedFromResponseEqualityCheckTest() { var client = new ManagementClient(new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString)); var name = Guid.NewGuid().ToString("D").Substring(0, 8); try { var topicDescription = new TopicDescription(name); var createdTopicDescription = await client.CreateTopicAsync(topicDescription); var identicalTopicDescription = new TopicDescription(name); Assert.Equal(identicalTopicDescription, createdTopicDescription); await client.DeleteTopicAsync(name); } catch { await SafeDeleteTopic(client, name); throw; } finally { await client.CloseAsync(); } } [Fact] [LiveTest] [DisplayTestMethodName] public async Task SqlFilterParamsTest() { var client = new ManagementClient(new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString)); var topicName = Guid.NewGuid().ToString("D").Substring(0, 8); var subscriptionName = Guid.NewGuid().ToString("D").Substring(0, 8); try { await client.CreateTopicAsync(topicName); await client.CreateSubscriptionAsync(topicName, subscriptionName); SqlFilter sqlFilter = new SqlFilter( "PROPERTY(@propertyName) = @stringPropertyValue " + "AND PROPERTY(intProperty) = @intPropertyValue " + "AND PROPERTY(longProperty) = @longPropertyValue " + "AND PROPERTY(boolProperty) = @boolPropertyValue " + "AND PROPERTY(doubleProperty) = @doublePropertyValue ") { Parameters = { { "@propertyName", "MyProperty" }, { "@stringPropertyValue", "string" }, { "@intPropertyValue", 3 }, { "@longPropertyValue", 3L }, { "@boolPropertyValue", true }, { "@doublePropertyValue", (double)3.0 }, } }; var rule = await client.CreateRuleAsync(topicName, subscriptionName, new RuleDescription("rule1", sqlFilter)); Assert.Equal(sqlFilter, rule.Filter); await client.DeleteTopicAsync(topicName); } catch { await SafeDeleteTopic(client, topicName); throw; } finally { await client.CloseAsync(); } } [Fact] [LiveTest] [DisplayTestMethodName] public async Task CorrelationFilterPropertiesTest() { var topicName = Guid.NewGuid().ToString("D").Substring(0, 8); var subscriptionName = Guid.NewGuid().ToString("D").Substring(0, 8); var client = new ManagementClient(new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString)); try { await client.CreateTopicAsync(topicName); await client.CreateSubscriptionAsync(topicName, subscriptionName); var sClient = new SubscriptionClient(TestUtility.NamespaceConnectionString, topicName, subscriptionName); var filter = new CorrelationFilter(); filter.Properties.Add("stringKey", "stringVal"); filter.Properties.Add("intKey", 5); filter.Properties.Add("dateTimeKey", DateTime.UtcNow); var rule = await client.CreateRuleAsync(topicName, subscriptionName, new RuleDescription("rule1", filter)); Assert.True(filter.Properties.Count == 3); Assert.Equal(filter, rule.Filter); await client.DeleteTopicAsync(topicName); } catch { await SafeDeleteTopic(client, topicName); throw; } finally { await client.CloseAsync(); } } [Fact] [LiveTest] [DisplayTestMethodName] public async Task GetNamespaceInfoTest() { var client = new ManagementClient(new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString)); try { var nsInfo = await client.GetNamespaceInfoAsync(); Assert.NotNull(nsInfo); Assert.Equal(MessagingSku.Standard, nsInfo.MessagingSku); // Most CI systems generally use standard, hence this check just to ensure the API is working. Assert.Equal(NamespaceType.ServiceBus, nsInfo.NamespaceType); // Common namespace type used for testing is messaging. } finally { await client.CloseAsync(); } } private async Task SafeDeleteQueue(ManagementClient client, string name, [CallerMemberName] string caller = null) { try { await (client?.DeleteQueueAsync(name) ?? Task.CompletedTask); } catch (Exception ex) { TestUtility.Log($"{ caller } could not delete the queue [{ name }]. Error: [{ ex.Message }]"); } } private async Task SafeDeleteTopic(ManagementClient client, string name, [CallerMemberName] string caller = null) { try { await (client?.DeleteTopicAsync(name) ?? Task.CompletedTask); } catch (Exception ex) { TestUtility.Log($"{ caller } could not delete the topic [{ name }]. Error: [{ ex.Message }]"); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Globalization { using System; using System.Runtime.Serialization; using System.Threading; using System.Diagnostics.Contracts; // Gregorian Calendars use Era Info // Note: We shouldn't have to serialize this since the info doesn't change, but we have been. // (We really only need the calendar #, and maybe culture) [Serializable] internal class EraInfo { internal int era; // The value of the era. internal long ticks; // The time in ticks when the era starts internal int yearOffset; // The offset to Gregorian year when the era starts. // Gregorian Year = Era Year + yearOffset // Era Year = Gregorian Year - yearOffset internal int minEraYear; // Min year value in this era. Generally, this value is 1, but this may // be affected by the DateTime.MinValue; internal int maxEraYear; // Max year value in this era. (== the year length of the era + 1) [OptionalField(VersionAdded = 4)] internal String eraName; // The era name [OptionalField(VersionAdded = 4)] internal String abbrevEraName; // Abbreviated Era Name [OptionalField(VersionAdded = 4)] internal String englishEraName; // English era name internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear) { this.era = era; this.yearOffset = yearOffset; this.minEraYear = minEraYear; this.maxEraYear = maxEraYear; this.ticks = new DateTime(startYear, startMonth, startDay).Ticks; } internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear, String eraName, String abbrevEraName, String englishEraName) { this.era = era; this.yearOffset = yearOffset; this.minEraYear = minEraYear; this.maxEraYear = maxEraYear; this.ticks = new DateTime(startYear, startMonth, startDay).Ticks; this.eraName = eraName; this.abbrevEraName = abbrevEraName; this.englishEraName = englishEraName; } } // This calendar recognizes two era values: // 0 CurrentEra (AD) // 1 BeforeCurrentEra (BC) [Serializable] internal class GregorianCalendarHelper { // 1 tick = 100ns = 10E-7 second // Number of ticks per time unit internal const long TicksPerMillisecond = 10000; internal const long TicksPerSecond = TicksPerMillisecond * 1000; internal const long TicksPerMinute = TicksPerSecond * 60; internal const long TicksPerHour = TicksPerMinute * 60; internal const long TicksPerDay = TicksPerHour * 24; // Number of milliseconds per time unit internal const int MillisPerSecond = 1000; internal const int MillisPerMinute = MillisPerSecond * 60; internal const int MillisPerHour = MillisPerMinute * 60; internal const int MillisPerDay = MillisPerHour * 24; // Number of days in a non-leap year internal const int DaysPerYear = 365; // Number of days in 4 years internal const int DaysPer4Years = DaysPerYear * 4 + 1; // Number of days in 100 years internal const int DaysPer100Years = DaysPer4Years * 25 - 1; // Number of days in 400 years internal const int DaysPer400Years = DaysPer100Years * 4 + 1; // Number of days from 1/1/0001 to 1/1/10000 internal const int DaysTo10000 = DaysPer400Years * 25 - 366; internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay; internal const int DatePartYear = 0; internal const int DatePartDayOfYear = 1; internal const int DatePartMonth = 2; internal const int DatePartDay = 3; // // This is the max Gregorian year can be represented by DateTime class. The limitation // is derived from DateTime class. // internal int MaxYear { get { return (m_maxYear); } } internal static readonly int[] DaysToMonth365 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; internal static readonly int[] DaysToMonth366 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; // Strictly these don't need serialized since they can be recreated from the calendar id [OptionalField(VersionAdded = 1)] internal int m_maxYear = 9999; [OptionalField(VersionAdded = 1)] internal int m_minYear; internal Calendar m_Cal; // Era information doesn't need serialized, its constant for the same calendars (ie: we can recreate it from the calendar id) [OptionalField(VersionAdded = 1)] internal EraInfo[] m_EraInfo; [OptionalField(VersionAdded = 1)] internal int[] m_eras = null; // m_minDate is existing here just to keep the serialization compatibility. // it has nothing to do with the code anymore. [OptionalField(VersionAdded = 1)] internal DateTime m_minDate; // Construct an instance of gregorian calendar. internal GregorianCalendarHelper(Calendar cal, EraInfo[] eraInfo) { m_Cal = cal; m_EraInfo = eraInfo; // m_minDate is existing here just to keep the serialization compatibility. // it has nothing to do with the code anymore. m_minDate = m_Cal.MinSupportedDateTime; m_maxYear = m_EraInfo[0].maxEraYear; m_minYear = m_EraInfo[0].minEraYear;; } /*=================================GetGregorianYear========================== **Action: Get the Gregorian year value for the specified year in an era. **Returns: The Gregorian year value. **Arguments: ** year the year value in Japanese calendar ** era the Japanese emperor era value. **Exceptions: ** ArgumentOutOfRangeException if year value is invalid or era value is invalid. ============================================================================*/ internal int GetGregorianYear(int year, int era) { if (year < 0) { throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); if (era == Calendar.CurrentEra) { era = m_Cal.CurrentEraValue; } for (int i = 0; i < m_EraInfo.Length; i++) { if (era == m_EraInfo[i].era) { if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), m_EraInfo[i].minEraYear, m_EraInfo[i].maxEraYear)); } return (m_EraInfo[i].yearOffset + year); } } throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } internal bool IsValidYear(int year, int era) { if (year < 0) { return false; } if (era == Calendar.CurrentEra) { era = m_Cal.CurrentEraValue; } for (int i = 0; i < m_EraInfo.Length; i++) { if (era == m_EraInfo[i].era) { if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear) { return false; } return true; } } return false; } // Returns a given date part of this DateTime. This method is used // to compute the year, day-of-year, month, or day part. internal virtual int GetDatePart(long ticks, int part) { CheckTicksRange(ticks); // n = number of days since 1/1/0001 int n = (int)(ticks / TicksPerDay); // y400 = number of whole 400-year periods since 1/1/0001 int y400 = n / DaysPer400Years; // n = day number within 400-year period n -= y400 * DaysPer400Years; // y100 = number of whole 100-year periods within 400-year period int y100 = n / DaysPer100Years; // Last 100-year period has an extra day, so decrement result if 4 if (y100 == 4) y100 = 3; // n = day number within 100-year period n -= y100 * DaysPer100Years; // y4 = number of whole 4-year periods within 100-year period int y4 = n / DaysPer4Years; // n = day number within 4-year period n -= y4 * DaysPer4Years; // y1 = number of whole years within 4-year period int y1 = n / DaysPerYear; // Last year has an extra day, so decrement result if 4 if (y1 == 4) y1 = 3; // If year was requested, compute and return it if (part == DatePartYear) { return (y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1); } // n = day number within year n -= y1 * DaysPerYear; // If day-of-year was requested, return it if (part == DatePartDayOfYear) { return (n + 1); } // Leap year calculation looks different from IsLeapYear since y1, y4, // and y100 are relative to year 1, not year 0 bool leapYear = (y1 == 3 && (y4 != 24 || y100 == 3)); int[] days = leapYear? DaysToMonth366: DaysToMonth365; // All months have less than 32 days, so n >> 5 is a good conservative // estimate for the month int m = (n >> 5) + 1; // m = 1-based month number while (n >= days[m]) m++; // If month was requested, return it if (part == DatePartMonth) return (m); // Return 1-based day-of-month return (n - days[m - 1] + 1); } /*=================================GetAbsoluteDate========================== **Action: Gets the absolute date for the given Gregorian date. The absolute date means ** the number of days from January 1st, 1 A.D. **Returns: the absolute date **Arguments: ** year the Gregorian year ** month the Gregorian month ** day the day **Exceptions: ** ArgumentOutOfRangException if year, month, day value is valid. **Note: ** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars. ** Number of Days in Prior Years (both common and leap years) + ** Number of Days in Prior Months of Current Year + ** Number of Days in Current Month ** ============================================================================*/ internal static long GetAbsoluteDate(int year, int month, int day) { if (year >= 1 && year <= 9999 && month >= 1 && month <= 12) { int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366: DaysToMonth365; if (day >= 1 && (day <= days[month] - days[month - 1])) { int y = year - 1; int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1; return (absoluteDate); } } throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay")); } // Returns the tick count corresponding to the given year, month, and day. // Will check the if the parameters are valid. internal static long DateToTicks(int year, int month, int day) { return (GetAbsoluteDate(year, month, day)* TicksPerDay); } // Return the tick count corresponding to the given hour, minute, second. // Will check the if the parameters are valid. internal static long TimeToTicks(int hour, int minute, int second, int millisecond) { //TimeSpan.TimeToTicks is a family access function which does no error checking, so //we need to put some error checking out here. if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >=0 && second < 60) { if (millisecond < 0 || millisecond >= MillisPerSecond) { throw new ArgumentOutOfRangeException( nameof(millisecond), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, MillisPerSecond - 1)); } return (TimeSpan.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond);; } throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond")); } internal void CheckTicksRange(long ticks) { if (ticks < m_Cal.MinSupportedDateTime.Ticks || ticks > m_Cal.MaxSupportedDateTime.Ticks) { throw new ArgumentOutOfRangeException( "time", String.Format( CultureInfo.InvariantCulture, Environment.GetResourceString("ArgumentOutOfRange_CalendarRange"), m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime)); } Contract.EndContractBlock(); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( nameof(months), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), -120000, 120000)); } Contract.EndContractBlock(); CheckTicksRange(time.Ticks); int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); int d = GetDatePart(time.Ticks, DatePartDay); int i = m - 1 + months; if (i >= 0) { m = i % 12 + 1; y = y + i / 12; } else { m = 12 + (i + 1) % 12; y = y + (i - 11) / 12; } int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366: DaysToMonth365; int days = (daysArray[m] - daysArray[m - 1]); if (d > days) { d = days; } long ticks = DateToTicks(y, m, d) + (time.Ticks % TicksPerDay); Calendar.CheckAddResult(ticks, m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public DateTime AddYears(DateTime time, int years) { return (AddMonths(time, years * 12)); } // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public int GetDayOfMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartDay)); } // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public DayOfWeek GetDayOfWeek(DateTime time) { CheckTicksRange(time.Ticks); return ((DayOfWeek)((time.Ticks / TicksPerDay + 1) % 7)); } // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public int GetDayOfYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartDayOfYear)); } // Returns the number of days in the month given by the year and // month arguments. // [Pure] public int GetDaysInMonth(int year, int month, int era) { // // Convert year/era value to Gregorain year value. // year = GetGregorianYear(year, era); if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month")); } int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366: DaysToMonth365); return (days[month] - days[month - 1]); } // Returns the number of days in the year given by the year argument for the current era. // public int GetDaysInYear(int year, int era) { // // Convert year/era value to Gregorain year value. // year = GetGregorianYear(year, era); return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366:365); } // Returns the era for the specified DateTime value. public int GetEra(DateTime time) { long ticks = time.Ticks; // The assumption here is that m_EraInfo is listed in reverse order. for (int i = 0; i < m_EraInfo.Length; i++) { if (ticks >= m_EraInfo[i].ticks) { return (m_EraInfo[i].era); } } throw new ArgumentOutOfRangeException(nameof(time), Environment.GetResourceString("ArgumentOutOfRange_Era")); } public int[] Eras { get { if (m_eras == null) { m_eras = new int[m_EraInfo.Length]; for (int i = 0; i < m_EraInfo.Length; i++) { m_eras[i] = m_EraInfo[i].era; } } return ((int[])m_eras.Clone()); } } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public int GetMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartMonth)); } // Returns the number of months in the specified year and era. public int GetMonthsInYear(int year, int era) { year = GetGregorianYear(year, era); return (12); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public int GetYear(DateTime time) { long ticks = time.Ticks; int year = GetDatePart(ticks, DatePartYear); for (int i = 0; i < m_EraInfo.Length; i++) { if (ticks >= m_EraInfo[i].ticks) { return (year - m_EraInfo[i].yearOffset); } } throw new ArgumentException(Environment.GetResourceString("Argument_NoEra")); } // Returns the year that match the specified Gregorian year. The returned value is an // integer between 1 and 9999. // public int GetYear(int year, DateTime time) { long ticks = time.Ticks; for (int i = 0; i < m_EraInfo.Length; i++) { // while calculating dates with JapaneseLuniSolarCalendar, we can run into cases right after the start of the era // and still belong to the month which is started in previous era. Calculating equivalent calendar date will cause // using the new era info which will have the year offset equal to the year we are calculating year = m_EraInfo[i].yearOffset // which will end up with zero as calendar year. // We should use the previous era info instead to get the right year number. Example of such date is Feb 2nd 1989 if (ticks >= m_EraInfo[i].ticks && year > m_EraInfo[i].yearOffset) { return (year - m_EraInfo[i].yearOffset); } } throw new ArgumentException(Environment.GetResourceString("Argument_NoEra")); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public bool IsLeapDay(int year, int month, int day, int era) { // year/month/era checking is done in GetDaysInMonth() if (day < 1 || day > GetDaysInMonth(year, month, era)) { throw new ArgumentOutOfRangeException( nameof(day), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, GetDaysInMonth(year, month, era))); } Contract.EndContractBlock(); if (!IsLeapYear(year, era)) { return (false); } if (month == 2 && day == 29) { return (true); } return (false); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public int GetLeapMonth(int year, int era) { year = GetGregorianYear(year, era); return (0); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public bool IsLeapMonth(int year, int month, int era) { year = GetGregorianYear(year, era); if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException( nameof(month), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, 12)); } return (false); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public bool IsLeapYear(int year, int era) { year = GetGregorianYear(year, era); return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { year = GetGregorianYear(year, era); long ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second, millisecond); CheckTicksRange(ticks); return (new DateTime(ticks)); } public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { CheckTicksRange(time.Ticks); // Use GregorianCalendar to get around the problem that the implmentation in Calendar.GetWeekOfYear() // can call GetYear() that exceeds the supported range of the Gregorian-based calendars. return (GregorianCalendar.GetDefaultInstance().GetWeekOfYear(time, rule, firstDayOfWeek)); } public int ToFourDigitYear(int year, int twoDigitYearMax) { if (year < 0) { throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } Contract.EndContractBlock(); if (year < 100) { int y = year % 100; return ((twoDigitYearMax/100 - ( y > twoDigitYearMax % 100 ? 1 : 0))*100 + y); } if (year < m_minYear || year > m_maxYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), m_minYear, m_maxYear)); } // If the year value is above 100, just return the year value. Don't have to do // the TwoDigitYearMax comparison. return (year); } } }
// 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 Microsoft.DotNet.Cli.Build; using System; using System.IO; using System.Runtime.InteropServices; using Xunit; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.NativeHostApis { public class GivenThatICareAboutNativeHostApis : IClassFixture<GivenThatICareAboutNativeHostApis.SharedTestState> { private SharedTestState sharedTestState; public GivenThatICareAboutNativeHostApis(SharedTestState fixture) { sharedTestState = fixture; } [Fact] public void Muxer_activation_of_Publish_Output_Portable_DLL_hostfxr_get_native_search_directories_Succeeds() { var fixture = sharedTestState.PreviouslyPublishedAndRestoredPortableApiTestProjectFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var dotnetLocation = Path.Combine(dotnet.BinPath, $"dotnet{fixture.ExeExtension}"); string[] args = { "hostfxr_get_native_search_directories", dotnetLocation, appDll }; dotnet.Exec(appDll, args) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdOutContaining("hostfxr_get_native_search_directories:Success") .And .HaveStdOutContaining("hostfxr_get_native_search_directories buffer:[" + dotnet.GreatestVersionSharedFxPath); } // This test also validates that hostfxr_set_error_writer captures errors // from hostfxr itself. [Fact] public void Hostfxr_get_native_search_directories_invalid_buffer() { var fixture = sharedTestState.PreviouslyPublishedAndRestoredPortableApiTestProjectFixture.Copy(); fixture.BuiltDotnet.Exec(fixture.TestProject.AppDll, "Test_hostfxr_get_native_search_directories_invalid_buffer") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And.HaveStdOutContaining($"hostfxr reported errors:") .And.HaveStdOutContaining("hostfxr_get_native_search_directories received an invalid argument."); } // This test also validates that hostfxr_set_error_writer propagates the custom writer // to the hostpolicy.dll for the duration of those calls. [Fact] public void Muxer_hostfxr_get_native_search_directories_with_invalid_deps() { var fixture = sharedTestState.PreviouslyPublishedAndRestoredPortableApiTestProjectFixture.Copy(); var appFixture = sharedTestState.PreviouslyPublishedAndRestoredPortableAppProjectFixture.Copy(); var dotnet = fixture.BuiltDotnet; // Corrupt the .deps.json by appending } to it (malformed json) File.WriteAllText( appFixture.TestProject.DepsJson, File.ReadAllLines(appFixture.TestProject.DepsJson) + "}"); var dotnetLocation = Path.Combine(dotnet.BinPath, $"dotnet{fixture.ExeExtension}"); string[] args = { "hostfxr_get_native_search_directories", dotnetLocation, appFixture.TestProject.AppDll }; dotnet.Exec(fixture.TestProject.AppDll, args) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And.HaveStdOutContaining("hostfxr_get_native_search_directories:Fail[2147516555]") // StatusCode::ResolverInitFailure .And.HaveStdOutContaining("hostfxr reported errors:") .And.HaveStdOutContaining($"A JSON parsing exception occurred in [{appFixture.TestProject.DepsJson}]: * Line 1, Column 2 Syntax error: Malformed token") .And.HaveStdOutContaining($"Error initializing the dependency resolver: An error occurred while parsing: {appFixture.TestProject.DepsJson}"); } [Fact] public void Breadcrumb_thread_finishes_when_app_closes_normally() { var fixture = sharedTestState.PreviouslyPublishedAndRestoredPortableAppProjectFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable("CORE_BREADCRUMBS", sharedTestState.BreadcrumbLocation) .EnvironmentVariable("COREHOST_TRACE", "1") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdOutContaining("Hello World") .And .HaveStdErrContaining("Waiting for breadcrumb thread to exit..."); } [Fact] public void Breadcrumb_thread_does_not_finish_when_app_has_unhandled_exception() { var fixture = sharedTestState.PreviouslyPublishedAndRestoredPortableAppWithExceptionProjectFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable("CORE_BREADCRUMBS", sharedTestState.BreadcrumbLocation) .EnvironmentVariable("COREHOST_TRACE", "1") .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should() .Fail() .And .HaveStdErrContaining("Unhandled Exception: System.Exception: Goodbye World") .And // The breadcrumb thread does not wait since destructors are not called when an exception is thrown. // However, destructors will be called when the caller (such as a custom host) is compiled with SEH Exceptions (/EHa) and has a try\catch. // Todo: add a native host test app so we can verify this behavior. .NotHaveStdErrContaining("Waiting for breadcrumb thread to exit..."); } private class SdkResolutionFixture { private readonly TestProjectFixture _fixture; public DotNetCli Dotnet => _fixture.BuiltDotnet; public string AppDll => _fixture.TestProject.AppDll; public string ExeDir => Path.Combine(_fixture.TestProject.ProjectDirectory, "ed"); public string ProgramFiles => Path.Combine(ExeDir, "pf"); public string SelfRegistered => Path.Combine(ExeDir, "sr"); public string WorkingDir => Path.Combine(_fixture.TestProject.ProjectDirectory, "wd"); public string ProgramFilesGlobalSdkDir => Path.Combine(ProgramFiles, "dotnet", "sdk"); public string SelfRegisteredGlobalSdkDir => Path.Combine(SelfRegistered, "sdk"); public string LocalSdkDir => Path.Combine(ExeDir, "sdk"); public string GlobalJson => Path.Combine(WorkingDir, "global.json"); public string[] ProgramFilesGlobalSdks = new[] { "4.5.6", "1.2.3", "2.3.4-preview" }; public string[] SelfRegisteredGlobalSdks = new[] { "3.0.0", "15.1.4-preview", "5.6.7" }; public string[] LocalSdks = new[] { "0.1.2", "5.6.7-preview", "1.2.3" }; public SdkResolutionFixture(SharedTestState state) { _fixture = state.PreviouslyPublishedAndRestoredPortableApiTestProjectFixture.Copy(); Directory.CreateDirectory(WorkingDir); // start with an empty global.json, it will be ignored, but prevent one lying on disk // on a given machine from impacting the test. File.WriteAllText(GlobalJson, "{}"); foreach (string sdk in ProgramFilesGlobalSdks) { Directory.CreateDirectory(Path.Combine(ProgramFilesGlobalSdkDir, sdk)); } foreach (string sdk in SelfRegisteredGlobalSdks) { Directory.CreateDirectory(Path.Combine(SelfRegisteredGlobalSdkDir, sdk)); } foreach (string sdk in LocalSdks) { Directory.CreateDirectory(Path.Combine(LocalSdkDir, sdk)); } } } [Fact] public void Hostfxr_get_available_sdks_with_multilevel_lookup() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // multilevel lookup is not supported on non-Windows return; } var f = new SdkResolutionFixture(sharedTestState); // With multi-level lookup (windows onnly): get local and global sdks sorted by ascending version, // with global sdk coming before local sdk when versions are equal string expectedList = string.Join(';', new[] { Path.Combine(f.LocalSdkDir, "0.1.2"), Path.Combine(f.ProgramFilesGlobalSdkDir, "1.2.3"), Path.Combine(f.LocalSdkDir, "1.2.3"), Path.Combine(f.ProgramFilesGlobalSdkDir, "2.3.4-preview"), Path.Combine(f.SelfRegisteredGlobalSdkDir, "3.0.0"), Path.Combine(f.ProgramFilesGlobalSdkDir, "4.5.6"), Path.Combine(f.LocalSdkDir, "5.6.7-preview"), Path.Combine(f.SelfRegisteredGlobalSdkDir, "5.6.7"), Path.Combine(f.SelfRegisteredGlobalSdkDir, "15.1.4-preview"), }); f.Dotnet.Exec(f.AppDll, new[] { "hostfxr_get_available_sdks", f.ExeDir }) .EnvironmentVariable("TEST_MULTILEVEL_LOOKUP_PROGRAM_FILES", f.ProgramFiles) .EnvironmentVariable("TEST_MULTILEVEL_LOOKUP_SELF_REGISTERED", f.SelfRegistered) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdOutContaining("hostfxr_get_available_sdks:Success") .And .HaveStdOutContaining($"hostfxr_get_available_sdks sdks:[{expectedList}]"); } [Fact] public void Hostfxr_get_available_sdks_without_multilevel_lookup() { // Without multi-level lookup: get only sdks sorted by ascending version var f = new SdkResolutionFixture(sharedTestState); string expectedList = string.Join(';', new[] { Path.Combine(f.LocalSdkDir, "0.1.2"), Path.Combine(f.LocalSdkDir, "1.2.3"), Path.Combine(f.LocalSdkDir, "5.6.7-preview"), }); f.Dotnet.Exec(f.AppDll, new[] { "hostfxr_get_available_sdks", f.ExeDir }) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdOutContaining("hostfxr_get_available_sdks:Success") .And .HaveStdOutContaining($"hostfxr_get_available_sdks sdks:[{expectedList}]"); } [Fact] public void Hostfxr_resolve_sdk2_without_global_json_or_flags() { // with no global.json and no flags, pick latest SDK var f = new SdkResolutionFixture(sharedTestState); string expectedData = string.Join(';', new[] { ("resolved_sdk_dir", Path.Combine(f.LocalSdkDir, "5.6.7-preview")), }); f.Dotnet.Exec(f.AppDll, new[] { "hostfxr_resolve_sdk2", f.ExeDir, f.WorkingDir, "0" }) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdOutContaining("hostfxr_resolve_sdk2:Success") .And .HaveStdOutContaining($"hostfxr_resolve_sdk2 data:[{expectedData}]"); } [Fact] public void Hostfxr_resolve_sdk2_without_global_json_and_disallowing_previews() { // Without global.json and disallowing previews, pick latest non-preview var f = new SdkResolutionFixture(sharedTestState); string expectedData = string.Join(';', new[] { ("resolved_sdk_dir", Path.Combine(f.LocalSdkDir, "1.2.3")) }); f.Dotnet.Exec(f.AppDll, new[] { "hostfxr_resolve_sdk2", f.ExeDir, f.WorkingDir, "disallow_prerelease" }) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdOutContaining("hostfxr_resolve_sdk2:Success") .And .HaveStdOutContaining($"hostfxr_resolve_sdk2 data:[{expectedData}]"); } [Fact] public void Hostfxr_resolve_sdk2_with_global_json_and_disallowing_previews() { // With global.json specifying a preview, roll forward to preview // since flag has no impact if global.json specifies a preview. // Also check that global.json that impacted resolution is reported. var f = new SdkResolutionFixture(sharedTestState); File.WriteAllText(f.GlobalJson, "{ \"sdk\": { \"version\": \"5.6.6-preview\" } }"); string expectedData = string.Join(';', new[] { ("resolved_sdk_dir", Path.Combine(f.LocalSdkDir, "5.6.7-preview")), ("global_json_path", f.GlobalJson), }); f.Dotnet.Exec(f.AppDll, new[] { "hostfxr_resolve_sdk2", f.ExeDir, f.WorkingDir, "disallow_prerelease" }) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdOutContaining("hostfxr_resolve_sdk2:Success") .And .HaveStdOutContaining($"hostfxr_resolve_sdk2 data:[{expectedData}]"); } [Fact] public void Hostfxr_corehost_set_error_writer_test() { var fixture = sharedTestState.PreviouslyPublishedAndRestoredPortableApiTestProjectFixture.Copy(); fixture.BuiltDotnet.Exec(fixture.TestProject.AppDll, "Test_hostfxr_set_error_writer") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass(); } [Fact] public void Hostpolicy_corehost_set_error_writer_test() { var fixture = sharedTestState.PreviouslyPublishedAndRestoredPortableApiTestProjectFixture.Copy(); fixture.BuiltDotnet.Exec(fixture.TestProject.AppDll, "Test_corehost_set_error_writer") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass(); } public class SharedTestState : IDisposable { public TestProjectFixture PreviouslyPublishedAndRestoredPortableApiTestProjectFixture { get; set; } public TestProjectFixture PreviouslyPublishedAndRestoredPortableAppProjectFixture { get; set; } public TestProjectFixture PreviouslyPublishedAndRestoredPortableAppWithExceptionProjectFixture { get; set; } public RepoDirectoriesProvider RepoDirectories { get; set; } public string BreadcrumbLocation { get; set; } public SharedTestState() { RepoDirectories = new RepoDirectoriesProvider(); PreviouslyPublishedAndRestoredPortableApiTestProjectFixture = new TestProjectFixture("HostApiInvokerApp", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .BuildProject(); PreviouslyPublishedAndRestoredPortableAppProjectFixture = new TestProjectFixture("PortableApp", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .PublishProject(); PreviouslyPublishedAndRestoredPortableAppWithExceptionProjectFixture = new TestProjectFixture("PortableAppWithException", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .PublishProject(); if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { BreadcrumbLocation = Path.Combine( PreviouslyPublishedAndRestoredPortableAppWithExceptionProjectFixture.TestProject.OutputDirectory, "opt", "corebreadcrumbs"); Directory.CreateDirectory(BreadcrumbLocation); // On non-Windows, we can't just P/Invoke to already loaded hostfxr, so copy it next to the app dll. var fixture = PreviouslyPublishedAndRestoredPortableApiTestProjectFixture; var hostfxr = Path.Combine( fixture.BuiltDotnet.GreatestVersionHostFxrPath, $"{fixture.SharedLibraryPrefix}hostfxr{fixture.SharedLibraryExtension}"); File.Copy( hostfxr, Path.GetDirectoryName(fixture.TestProject.AppDll)); } } public void Dispose() { PreviouslyPublishedAndRestoredPortableApiTestProjectFixture.Dispose(); PreviouslyPublishedAndRestoredPortableAppProjectFixture.Dispose(); PreviouslyPublishedAndRestoredPortableAppWithExceptionProjectFixture.Dispose(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Numerics; using System.Security.Cryptography.Asn1; using System.Security.Cryptography.X509Certificates; namespace System.Security.Cryptography.Pkcs { internal abstract partial class CmsSignature { private static readonly Dictionary<string, CmsSignature> s_lookup = new Dictionary<string, CmsSignature>(); static CmsSignature() { PrepareRegistrationRsa(s_lookup); PrepareRegistrationDsa(s_lookup); PrepareRegistrationECDsa(s_lookup); } static partial void PrepareRegistrationRsa(Dictionary<string, CmsSignature> lookup); static partial void PrepareRegistrationDsa(Dictionary<string, CmsSignature> lookup); static partial void PrepareRegistrationECDsa(Dictionary<string, CmsSignature> lookup); protected abstract bool VerifyKeyType(AsymmetricAlgorithm key); internal abstract bool VerifySignature( #if NETCOREAPP || NETSTANDARD2_1 ReadOnlySpan<byte> valueHash, ReadOnlyMemory<byte> signature, #else byte[] valueHash, byte[] signature, #endif string digestAlgorithmOid, HashAlgorithmName digestAlgorithmName, ReadOnlyMemory<byte>? signatureParameters, X509Certificate2 certificate); protected abstract bool Sign( #if NETCOREAPP || NETSTANDARD2_1 ReadOnlySpan<byte> dataHash, #else byte[] dataHash, #endif HashAlgorithmName hashAlgorithmName, X509Certificate2 certificate, AsymmetricAlgorithm key, bool silent, out Oid signatureAlgorithm, out byte[] signatureValue); internal static CmsSignature ResolveAndVerifyKeyType(string signatureAlgorithmOid, AsymmetricAlgorithm key) { if (s_lookup.TryGetValue(signatureAlgorithmOid, out CmsSignature processor)) { if (key != null && !processor.VerifyKeyType(key)) { return null; } return processor; } return null; } internal static bool Sign( #if NETCOREAPP || NETSTANDARD2_1 ReadOnlySpan<byte> dataHash, #else byte[] dataHash, #endif HashAlgorithmName hashAlgorithmName, X509Certificate2 certificate, AsymmetricAlgorithm key, bool silent, out Oid oid, out ReadOnlyMemory<byte> signatureValue) { CmsSignature processor = ResolveAndVerifyKeyType(certificate.GetKeyAlgorithm(), key); if (processor == null) { oid = null; signatureValue = default; return false; } byte[] signature; bool signed = processor.Sign(dataHash, hashAlgorithmName, certificate, key, silent, out oid, out signature); signatureValue = signature; return signed; } private static bool DsaDerToIeee( ReadOnlyMemory<byte> derSignature, Span<byte> ieeeSignature) { int fieldSize = ieeeSignature.Length / 2; Debug.Assert( fieldSize * 2 == ieeeSignature.Length, $"ieeeSignature.Length ({ieeeSignature.Length}) must be even"); try { AsnReader reader = new AsnReader(derSignature, AsnEncodingRules.DER); AsnReader sequence = reader.ReadSequence(); if (reader.HasData) { return false; } // Fill it with zeros so that small data is correctly zero-prefixed. // this buffer isn't very large, so there's not really a reason to the // partial-fill gymnastics. ieeeSignature.Clear(); ReadOnlySpan<byte> val = sequence.ReadIntegerBytes().Span; if (val.Length > fieldSize && val[0] == 0) { val = val.Slice(1); } if (val.Length <= fieldSize) { val.CopyTo(ieeeSignature.Slice(fieldSize - val.Length, val.Length)); } val = sequence.ReadIntegerBytes().Span; if (val.Length > fieldSize && val[0] == 0) { val = val.Slice(1); } if (val.Length <= fieldSize) { val.CopyTo(ieeeSignature.Slice(fieldSize + fieldSize - val.Length, val.Length)); } return !sequence.HasData; } catch (CryptographicException) { return false; } } private static byte[] DsaIeeeToDer(ReadOnlySpan<byte> ieeeSignature) { int fieldSize = ieeeSignature.Length / 2; Debug.Assert( fieldSize * 2 == ieeeSignature.Length, $"ieeeSignature.Length ({ieeeSignature.Length}) must be even"); using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER)) { writer.PushSequence(); #if NETCOREAPP || NETSTANDARD2_1 // r BigInteger val = new BigInteger( ieeeSignature.Slice(0, fieldSize), isUnsigned: true, isBigEndian: true); writer.WriteInteger(val); // s val = new BigInteger( ieeeSignature.Slice(fieldSize, fieldSize), isUnsigned: true, isBigEndian: true); writer.WriteInteger(val); #else byte[] buf = new byte[fieldSize + 1]; Span<byte> bufWriter = new Span<byte>(buf, 1, fieldSize); ieeeSignature.Slice(0, fieldSize).CopyTo(bufWriter); Array.Reverse(buf); BigInteger val = new BigInteger(buf); writer.WriteInteger(val); buf[0] = 0; ieeeSignature.Slice(fieldSize, fieldSize).CopyTo(bufWriter); Array.Reverse(buf); val = new BigInteger(buf); writer.WriteInteger(val); #endif writer.PopSequence(); return writer.Encode(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.ComponentModel { /// <summary> /// Encapsulates zero or more components. /// </summary> public class Container : IContainer { private ISite[] _sites; private int _siteCount; private ComponentCollection _components; private ContainerFilterService _filter; private bool _checkedFilter; private readonly object _syncObj = new object(); ~Container() => Dispose(false); /// <summary> /// Adds the specified component to the <see cref='System.ComponentModel.Container'/> /// The component is unnamed. /// </summary> public virtual void Add(IComponent component) { Add(component, null); } // Adds a component to the container. /// <summary> /// Adds the specified component to the <see cref='System.ComponentModel.Container'/> and assigns /// a name to it. /// </summary> public virtual void Add(IComponent component, string name) { lock (_syncObj) { if (component == null) { return; } ISite site = component.Site; if (site != null && site.Container == this) { return; } if (_sites == null) { _sites = new ISite[4]; } else { // Validate that new components // have either a null name or a unique one. // ValidateName(component, name); if (_sites.Length == _siteCount) { ISite[] newSites = new ISite[_siteCount * 2]; Array.Copy(_sites, 0, newSites, 0, _siteCount); _sites = newSites; } } site?.Container.Remove(component); ISite newSite = CreateSite(component, name); _sites[_siteCount++] = newSite; component.Site = newSite; _components = null; } } /// <summary> /// Creates a Site <see cref='System.ComponentModel.ISite'/> for the given <see cref='System.ComponentModel.IComponent'/> /// and assigns the given name to the site. /// </summary> protected virtual ISite CreateSite(IComponent component, string name) { return new Site(component, this, name); } /// <summary> /// Disposes of the container. A call to the Dispose method indicates that /// the user of the container has no further need for it. /// /// The implementation of Dispose must: /// /// (1) Remove any references the container is holding to other components. /// This is typically accomplished by assigning null to any fields that /// contain references to other components. /// /// (2) Release any system resources that are associated with the container, /// such as file handles, window handles, or database connections. /// /// (3) Dispose of child components by calling the Dispose method of each. /// /// Ideally, a call to Dispose will revert a container to the state it was /// in immediately after it was created. However, this is not a requirement. /// Following a call to its Dispose method, a container is permitted to raise /// exceptions for operations that cannot meaningfully be performed. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { lock (_syncObj) { while (_siteCount > 0) { ISite site = _sites[--_siteCount]; site.Component.Site = null; site.Component.Dispose(); } _sites = null; _components = null; } } } protected virtual object GetService(Type service) => service == typeof(IContainer) ? this : null; /// <summary> /// Gets all the components in the <see cref='System.ComponentModel.Container'/>. /// </summary> public virtual ComponentCollection Components { get { lock (_syncObj) { if (_components == null) { IComponent[] result = new IComponent[_siteCount]; for (int i = 0; i < _siteCount; i++) { result[i] = _sites[i].Component; } _components = new ComponentCollection(result); // At each component add, if we don't yet have a filter, look for one. // Components may add filters. if (_filter == null && _checkedFilter) { _checkedFilter = false; } } if (!_checkedFilter) { _filter = GetService(typeof(ContainerFilterService)) as ContainerFilterService; _checkedFilter = true; } if (_filter != null) { ComponentCollection filteredComponents = _filter.FilterComponents(_components); if (filteredComponents != null) { _components = filteredComponents; } } return _components; } } } /// <summary> /// Removes a component from the <see cref='System.ComponentModel.Container'/>. /// </summary> public virtual void Remove(IComponent component) => Remove(component, false); private void Remove(IComponent component, bool preserveSite) { lock (_syncObj) { ISite site = component?.Site; if (site == null || site.Container != this) { return; } if (!preserveSite) { component.Site = null; } for (int i = 0; i < _siteCount; i++) { if (_sites[i] == site) { _siteCount--; Array.Copy(_sites, i + 1, _sites, i, _siteCount - i); _sites[_siteCount] = null; _components = null; break; } } } } protected void RemoveWithoutUnsiting(IComponent component) => Remove(component, true); /// <summary> /// Validates that the given name is valid for a component. The default implementation /// verifies that name is either null or unique compared to the names of other /// components in the container. /// </summary> protected virtual void ValidateName(IComponent component, string name) { if (component == null) { throw new ArgumentNullException(nameof(component)); } if (name != null) { for (int i = 0; i < Math.Min(_siteCount, _sites.Length); i++) { ISite s = _sites[i]; if (s?.Name != null && string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase) && s.Component != component) { InheritanceAttribute inheritanceAttribute = (InheritanceAttribute)TypeDescriptor.GetAttributes(s.Component)[typeof(InheritanceAttribute)]; if (inheritanceAttribute.InheritanceLevel != InheritanceLevel.InheritedReadOnly) { throw new ArgumentException(SR.Format(SR.DuplicateComponentName, name)); } } } } } private class Site : ISite { private string _name; internal Site(IComponent component, Container container, string name) { Component = component; Container = container; _name = name; } /// <summary> /// The component sited by this component site. /// </summary> public IComponent Component { get; } /// <summary> /// The container in which the component is sited. /// </summary> public IContainer Container { get; } public object GetService(Type service) { return ((service == typeof(ISite)) ? this : ((Container)Container).GetService(service)); } /// <summary> /// Indicates whether the component is in design mode. /// </summary> public bool DesignMode => false; /// <summary> /// The name of the component. /// </summary> public string Name { get { return _name; } set { if (value == null || _name == null || !value.Equals(_name)) { ((Container)Container).ValidateName(Component, value); _name = value; } } } } } }
// Amplify Shader Editor - Visual Shader Editing Tool // Copyright (c) Amplify Creations, Lda <info@amplify.pt> using System; using System.Collections.Generic; using UnityEngine; using UnityEditor; namespace AmplifyShaderEditor { public class PropertyDataCollector { public int NodeId; public int OrderIndex; public string PropertyName; public PropertyDataCollector( int nodeId, string propertyName, int orderIndex = -1 ) { NodeId = nodeId; PropertyName = propertyName; OrderIndex = orderIndex; } } public class TextureDefaultsDataColector { private List<string> m_names = new List<string>(); private List<Texture> m_values = new List<Texture>(); public void AddValue( string newName, Texture newValue ) { m_names.Add( newName ); m_values.Add( newValue ); } public void Destroy() { m_names.Clear(); m_names = null; m_values.Clear(); m_values = null; } public string[] NamesArr { get { return m_names.ToArray(); } } public Texture[] ValuesArr { get { return m_values.ToArray(); } } } public enum TextureChannelUsage { Not_Used, Used, Required } public class MasterNodeDataCollector { private bool ShowDebugMessages = false; private string m_input; private string m_customInput; private string m_properties; private string m_instancedProperties; private string m_uniforms; private string m_includes; private string m_pragmas; private string m_instructions; private string m_localVariables; private string m_vertexLocalVariables; private string m_specialLocalVariables; private string m_vertexData; private string m_customOutput; private string m_functions; private string m_grabPass; private Dictionary<string, PropertyDataCollector> m_inputDict; private Dictionary<string, PropertyDataCollector> m_customInputDict; private Dictionary<string, PropertyDataCollector> m_propertiesDict; private Dictionary<string, PropertyDataCollector> m_instancedPropertiesDict; private Dictionary<string, PropertyDataCollector> m_uniformsDict; private Dictionary<string, PropertyDataCollector> m_includesDict; private Dictionary<string, PropertyDataCollector> m_pragmasDict; private Dictionary<string, int> m_virtualCoordinatesDict; private Dictionary<string, PropertyDataCollector> m_localVariablesDict; private Dictionary<string, PropertyDataCollector> m_vertexLocalVariablesDict; private Dictionary<string, PropertyDataCollector> m_specialLocalVariablesDict; private Dictionary<string, PropertyDataCollector> m_vertexDataDict; private Dictionary<string, PropertyDataCollector> m_customOutputDict; private Dictionary<string, string> m_localFunctions; private TextureChannelUsage[] m_requireTextureProperty = { TextureChannelUsage.Not_Used, TextureChannelUsage.Not_Used, TextureChannelUsage.Not_Used, TextureChannelUsage.Not_Used }; private bool m_dirtyInputs; private bool m_dirtyCustomInputs; private bool m_dirtyFunctions; private bool m_dirtyProperties; private bool m_dirtyInstancedProperties; private bool m_dirtyUniforms; private bool m_dirtyIncludes; private bool m_dirtyPragmas; private bool m_dirtyInstructions; private bool m_dirtyLocalVariables; private bool m_dirtyVertexLocalVariables; private bool m_dirtySpecialLocalVariables; private bool m_dirtyPerVertexData; private bool m_dirtyNormal; private bool m_forceNormal; private bool m_usingInternalData; private bool m_usingTexcoord0; private bool m_usingTexcoord1; private bool m_usingTexcoord2; private bool m_usingTexcoord3; private bool m_usingWorldPosition; private bool m_usingWorldNormal; private bool m_usingWorldReflection; private bool m_usingViewDirection; private bool m_usingHigherSizeTexcoords; private bool m_usingCustomOutput; private bool m_forceNormalIsDirty; private bool m_grabPassIsDirty; private bool m_tesselationActive; private Dictionary<int, PropertyNode> m_propertyNodes; private MasterNode m_masterNode; private int m_availableUvInd = 0; private int m_availableVertexTempId = 0; private int m_availableFragTempId = 0; private MasterNodePortCategory m_portCategory; public MasterNodeDataCollector( MasterNode masterNode ) { m_masterNode = masterNode; m_input = "\t\tstruct Input\n\t\t{\n"; m_customInput = "\t\tstruct SurfaceOutput{0}\n\t\t{\n"; m_properties = IOUtils.PropertiesBegin;//"\tProperties\n\t{\n"; m_uniforms = ""; m_instructions = ""; m_includes = ""; m_pragmas = ""; m_localVariables = ""; m_specialLocalVariables = ""; m_customOutput = ""; m_inputDict = new Dictionary<string, PropertyDataCollector>(); m_customInputDict = new Dictionary<string, PropertyDataCollector>(); m_propertiesDict = new Dictionary<string, PropertyDataCollector>(); m_instancedPropertiesDict = new Dictionary<string, PropertyDataCollector>(); m_uniformsDict = new Dictionary<string, PropertyDataCollector>(); m_includesDict = new Dictionary<string, PropertyDataCollector>(); m_pragmasDict = new Dictionary<string, PropertyDataCollector>(); m_virtualCoordinatesDict = new Dictionary<string, int>(); m_localVariablesDict = new Dictionary<string, PropertyDataCollector>(); m_specialLocalVariablesDict = new Dictionary<string, PropertyDataCollector>(); m_vertexLocalVariablesDict = new Dictionary<string, PropertyDataCollector>(); m_localFunctions = new Dictionary<string, string>(); m_vertexDataDict = new Dictionary<string, PropertyDataCollector>(); m_customOutputDict = new Dictionary<string, PropertyDataCollector>(); m_dirtyInputs = false; m_dirtyCustomInputs = false; m_dirtyProperties = false; m_dirtyInstancedProperties = false; m_dirtyUniforms = false; m_dirtyInstructions = false; m_dirtyIncludes = false; m_dirtyPragmas = false; m_dirtyLocalVariables = false; m_dirtySpecialLocalVariables = false; m_grabPassIsDirty = false; m_portCategory = MasterNodePortCategory.Fragment; m_propertyNodes = new Dictionary<int, PropertyNode>(); ShowDebugMessages = ( ShowDebugMessages && DebugConsoleWindow.DeveloperMode ); } public void SetChannelUsage( int channelId, TextureChannelUsage usage ) { if ( channelId > -1 && channelId < 4 ) m_requireTextureProperty[ channelId ] = usage; } public TextureChannelUsage GetChannelUsage( int channelId ) { if ( channelId > -1 && channelId < 4 ) return m_requireTextureProperty[ channelId ]; return TextureChannelUsage.Not_Used; } public void OpenPerVertexHeader( bool includeCustomData ) { if ( m_dirtyPerVertexData ) return; m_dirtyPerVertexData = true; if ( m_tesselationActive ) { m_vertexData = "\t\tvoid " + Constants.VertexDataFunc + "( inout appdata " + Constants.VertexShaderInputStr + " )\n\t\t{\n"; } else { m_vertexData = "\t\tvoid " + Constants.VertexDataFunc + "( inout appdata_full " + Constants.VertexShaderInputStr + ( includeCustomData ? ( string.Format( ", out Input {0}", Constants.VertexShaderOutputStr ) ) : string.Empty ) + " )\n\t\t{\n"; if ( includeCustomData ) m_vertexData += string.Format( "\t\t\tUNITY_INITIALIZE_OUTPUT( Input, {0} );\n", Constants.VertexShaderOutputStr ); } } public void ClosePerVertexHeader() { if ( m_dirtyPerVertexData ) m_vertexData += "\t\t}\n\n"; } public void AddToVertexDisplacement( string value , VertexMode vertexMode ) { if ( string.IsNullOrEmpty( value ) ) return; if ( !m_dirtyPerVertexData ) { OpenPerVertexHeader( true ); } switch ( vertexMode ) { default: case VertexMode.Relative: { m_vertexData += "\t\t\t" + Constants.VertexShaderInputStr + ".vertex.xyz += " + value + ";\n"; } break; case VertexMode.Absolute: { m_vertexData += "\t\t\t" + Constants.VertexShaderInputStr + ".vertex.xyz = " + value + ";\n"; } break; } } public void AddToVertexNormal( string value ) { if ( string.IsNullOrEmpty( value ) ) return; if ( !m_dirtyPerVertexData ) { OpenPerVertexHeader( true ); } m_vertexData += "\t\t\t" + Constants.VertexShaderInputStr + ".normal = " + value + ";\n"; } public void AddVertexInstruction( string value, int nodeId, bool addDelimiters = true ) { if ( !m_dirtyPerVertexData ) { OpenPerVertexHeader( true ); } if ( !m_vertexDataDict.ContainsKey( value ) ) { m_vertexDataDict.Add( value, new PropertyDataCollector( nodeId, value ) ); m_vertexData += ( addDelimiters ? ( "\t\t\t" + value + ";\n" ) : value ); } } public bool ContainsInput( string value ) { return m_inputDict.ContainsKey( value ); } public void AddToInput( int nodeId, string value, bool addSemiColon ) { if ( string.IsNullOrEmpty( value ) ) return; if ( !m_inputDict.ContainsKey( value ) ) { m_inputDict.Add( value, new PropertyDataCollector( nodeId, value ) ); m_input += "\t\t\t" + value + ( ( addSemiColon ) ? ( ";\n" ) : "\n" ); m_dirtyInputs = true; // TODO: move this elsewhere (waste of string calculations) if ( m_input.Contains( " worldNormal;" ) ) UsingWorldNormal = true; if ( m_input.Contains( " worldRefl;" ) ) UsingWorldReflection = true; if ( m_input.Contains( " worldPos;" ) ) UsingWorldPosition = true; if ( m_input.Contains( " viewDir;" ) ) UsingViewDirection = true; if ( m_input.Contains( "INTERNAL_DATA" ) ) UsingInternalData = true; if ( m_input.Contains( "uv_texcoord;" ) ) UsingTexcoord0 = true; if ( m_input.Contains( "uv2_texcoord2;" ) ) UsingTexcoord1 = true; if ( m_input.Contains( "uv3_texcoord3;" ) ) UsingTexcoord2 = true; if ( m_input.Contains( "uv4_texcoord4;" ) ) UsingTexcoord3 = true; } } public void CloseInputs() { m_input += "\t\t};"; } public void ChangeCustomInputHeader( string value ) { m_customInput = m_customInput.Replace( "{0}", value ); } public void AddToCustomInput( int nodeId, string value, bool addSemiColon ) { if ( string.IsNullOrEmpty( value ) ) return; if ( !m_customInputDict.ContainsKey( value ) ) { m_customInputDict.Add( value, new PropertyDataCollector( nodeId, value ) ); m_customInput += "\t\t\t" + value + ( ( addSemiColon ) ? ( ";\n" ) : "\n" ); m_dirtyCustomInputs = true; } } public void CloseCustomInputs() { m_customInput += "\t\t};"; } // Instanced properties public void SetupInstancePropertiesBlock( string blockName ) { if ( m_dirtyInstancedProperties ) { m_instancedProperties = string.Format( IOUtils.InstancedPropertiesBegin, blockName ) + m_instancedProperties + IOUtils.InstancedPropertiesEnd; } } public void AddToInstancedProperties( int nodeId, string value, int orderIndex ) { if ( string.IsNullOrEmpty( value ) ) return; if ( !m_instancedPropertiesDict.ContainsKey( value ) ) { m_instancedPropertiesDict.Add( value, new PropertyDataCollector( nodeId, value, orderIndex ) ); m_instancedProperties += value; m_dirtyInstancedProperties = true; } } public void CloseInstancedProperties() { if ( m_dirtyInstancedProperties ) { m_instancedProperties += IOUtils.InstancedPropertiesEnd; } } // Properties public void AddToProperties( int nodeId, string value, int orderIndex ) { if ( string.IsNullOrEmpty( value ) ) return; if ( !m_propertiesDict.ContainsKey( value ) ) { m_propertiesDict.Add( value, new PropertyDataCollector( nodeId, value, orderIndex ) ); m_properties += string.Format( IOUtils.PropertiesElement, value ); m_dirtyProperties = true; } } public string BuildPropertiesString() { List<PropertyDataCollector> list = new List<PropertyDataCollector>( m_propertiesDict.Values ); list.Sort( ( x, y ) => { return x.OrderIndex.CompareTo( y.OrderIndex ); } ); m_properties = IOUtils.PropertiesBegin; for ( int i = 0; i < list.Count; i++ ) { m_properties += string.Format( IOUtils.PropertiesElement, list[ i ].PropertyName ); } m_properties += IOUtils.PropertiesEnd; return m_properties; } public void CloseProperties() { if ( m_dirtyProperties ) { m_properties += IOUtils.PropertiesEnd; } } public void AddGrabPass( string value ) { m_grabPassIsDirty = true; if ( string.IsNullOrEmpty( value ) ) { m_grabPass = IOUtils.GrabPassEmpty; } else { m_grabPass = IOUtils.GrabPassBegin + value + IOUtils.GrabPassEnd; } } public void AddToUniforms( int nodeId, string dataType, string dataName ) { if ( string.IsNullOrEmpty( dataName ) || string.IsNullOrEmpty( dataType ) ) return; if ( !m_uniformsDict.ContainsKey( dataName ) ) { string value = UIUtils.GenerateUniformName( dataType, dataName ); m_uniforms += "\t\t" + value + '\n'; m_uniformsDict.Add( dataName, new PropertyDataCollector( nodeId, value ) ); m_dirtyUniforms = true; } else if ( m_uniformsDict[ dataName ].NodeId != nodeId ) { if ( ShowDebugMessages ) UIUtils.ShowMessage( "AddToUniforms:Attempting to add duplicate " + dataName, MessageSeverity.Warning ); } } public void AddToUniforms( int nodeId, string value ) { if ( string.IsNullOrEmpty( value ) ) return; if ( !m_uniformsDict.ContainsKey( value ) ) { m_uniforms += "\t\t" + value + '\n'; m_uniformsDict.Add( value, new PropertyDataCollector( nodeId, value ) ); m_dirtyUniforms = true; } else if ( m_uniformsDict[ value ].NodeId != nodeId ) { if ( ShowDebugMessages ) UIUtils.ShowMessage( "AddToUniforms:Attempting to add duplicate " + value, MessageSeverity.Warning ); } } public void AddToIncludes( int nodeId, string value ) { if ( string.IsNullOrEmpty( value ) ) return; if ( !m_includesDict.ContainsKey( value ) ) { m_includesDict.Add( value, new PropertyDataCollector( nodeId, value ) ); m_includes += "\t\t#include \"" + value + "\"\n"; m_dirtyIncludes = true; } else { if ( ShowDebugMessages ) UIUtils.ShowMessage( "AddToIncludes:Attempting to add duplicate " + value, MessageSeverity.Warning ); } } public void AddToPragmas( int nodeId, string value ) { if ( string.IsNullOrEmpty( value ) ) return; if ( !m_pragmasDict.ContainsKey( value ) ) { m_pragmasDict.Add( value, new PropertyDataCollector( nodeId, value ) ); m_pragmas += "\t\t#pragma " + value + "\n"; m_dirtyPragmas = true; } else { if ( ShowDebugMessages ) UIUtils.ShowMessage( "AddToPragmas:Attempting to add duplicate " + value, MessageSeverity.Warning ); } } public int GetVirtualCoordinatesId( int nodeId, string coord, string lodBias ) { if ( !m_virtualCoordinatesDict.ContainsKey( coord ) ) { m_virtualCoordinatesDict.Add( coord, nodeId ); AddToLocalVariables(nodeId, "VirtualCoord " + Constants.VirtualCoordNameStr + nodeId + " = VTComputeVirtualCoord" + lodBias + "(" + coord + ");" ); return nodeId; } else { int fetchedId = 0; m_virtualCoordinatesDict.TryGetValue( coord, out fetchedId ); return fetchedId; } } public bool AddToLocalVariables( MasterNodePortCategory category, int nodeId, PrecisionType precisionType, WirePortDataType type, string varName, string varValue ) { if ( string.IsNullOrEmpty( varName ) || string.IsNullOrEmpty( varValue ) ) return false; string value = UIUtils.PrecisionWirePortToCgType( precisionType, type ) + " " + varName + " = " + varValue + ";"; return AddToLocalVariables( category, nodeId, value ); } public bool AddToLocalVariables( int nodeId, PrecisionType precisionType, WirePortDataType type, string varName, string varValue ) { if ( string.IsNullOrEmpty( varName ) || string.IsNullOrEmpty( varValue ) ) return false; string value = UIUtils.PrecisionWirePortToCgType( precisionType, type ) + " " + varName + " = " + varValue + ";"; return AddToLocalVariables( nodeId, value ); } public bool AddToLocalVariables( MasterNodePortCategory category, int nodeId, string value, bool ignoreDuplicates = false ) { if ( string.IsNullOrEmpty( value ) ) return false; switch ( category ) { case MasterNodePortCategory.Vertex: case MasterNodePortCategory.Tessellation: { return AddToVertexLocalVariables( nodeId, value, ignoreDuplicates ); } case MasterNodePortCategory.Fragment: case MasterNodePortCategory.Debug: { return AddToLocalVariables( nodeId, value, ignoreDuplicates ); } } return false; } public bool AddLocalVariable( int nodeId, string value, bool ignoreDuplicates = false ) { if ( string.IsNullOrEmpty( value ) ) return false; switch ( m_portCategory ) { case MasterNodePortCategory.Vertex: case MasterNodePortCategory.Tessellation: { return AddToVertexLocalVariables( nodeId, value, ignoreDuplicates ); } case MasterNodePortCategory.Fragment: case MasterNodePortCategory.Debug: { return AddToLocalVariables( nodeId, value, ignoreDuplicates ); } } return false; } public void AddCodeComments( bool forceForwardSlash, params string[] comments ) { if ( m_portCategory == MasterNodePortCategory.Tessellation || m_portCategory == MasterNodePortCategory.Vertex ) { AddToVertexLocalVariables( 0, IOUtils.CreateCodeComments( forceForwardSlash, comments ) ); } else { AddToLocalVariables( 0, IOUtils.CreateCodeComments( forceForwardSlash, comments ) ); } } public bool AddToLocalVariables( int nodeId, string value, bool ignoreDuplicates = false ) { if ( string.IsNullOrEmpty( value ) ) return false; if ( m_usingCustomOutput ) { if ( !m_customOutputDict.ContainsKey( value ) || ignoreDuplicates ) { if ( !m_customOutputDict.ContainsKey( value ) ) m_customOutputDict.Add( value, new PropertyDataCollector( nodeId, value ) ); m_customOutput += "\t\t\t" + value + '\n'; return true; } else { if ( ShowDebugMessages ) UIUtils.ShowMessage( "AddToLocalVariables:Attempting to add duplicate " + value, MessageSeverity.Warning ); } } else { if ( !m_localVariablesDict.ContainsKey( value ) || ignoreDuplicates ) { if ( !m_localVariablesDict.ContainsKey( value ) ) m_localVariablesDict.Add( value, new PropertyDataCollector( nodeId, value ) ); AddToSpecialLocalVariables( nodeId, value, ignoreDuplicates ); return true; } else { if ( ShowDebugMessages ) UIUtils.ShowMessage( "AddToLocalVariables:Attempting to add duplicate " + value, MessageSeverity.Warning ); } } return false; } public void AddToSpecialLocalVariables( int nodeId, string value, bool ignoreDuplicates = false ) { if ( string.IsNullOrEmpty( value ) ) return; if ( !m_specialLocalVariablesDict.ContainsKey( value ) || ignoreDuplicates ) { if ( !m_specialLocalVariablesDict.ContainsKey( value ) ) m_specialLocalVariablesDict.Add( value, new PropertyDataCollector( nodeId, value ) ); m_specialLocalVariables += "\t\t\t" + value + '\n'; m_dirtySpecialLocalVariables = true; } else { if ( ShowDebugMessages ) UIUtils.ShowMessage( "AddToSpecialLocalVariables:Attempting to add duplicate " + value, MessageSeverity.Warning ); } } public void ClearSpecialLocalVariables() { //m_specialLocalVariablesDict.Clear(); m_specialLocalVariables = string.Empty; m_dirtySpecialLocalVariables = false; } public bool AddToVertexLocalVariables( int nodeId, string value, bool ignoreDuplicates = false ) { if ( string.IsNullOrEmpty( value ) ) return false; if ( !m_vertexLocalVariablesDict.ContainsKey( value ) || ignoreDuplicates ) { if ( !m_vertexLocalVariablesDict.ContainsKey( value ) ) m_vertexLocalVariablesDict.Add( value, new PropertyDataCollector( nodeId, value ) ); m_vertexLocalVariables += "\t\t\t" + value + '\n'; m_dirtyVertexLocalVariables = true; return true; } else { if ( ShowDebugMessages ) UIUtils.ShowMessage( "AddToVertexLocalVariables:Attempting to add duplicate " + value, MessageSeverity.Warning ); } return false; } public void ClearVertexLocalVariables() { //m_vertexLocalVariablesDict.Clear(); m_vertexLocalVariables = string.Empty; m_dirtyVertexLocalVariables = false; } public bool CheckFunction( string header ) { return m_localFunctions.ContainsKey( header ); } public string AddFunctions( string header, string body, params object[] inParams ) { if ( !m_localFunctions.ContainsKey( header ) ) { m_localFunctions.Add( header, body ); m_functions += "\n" + body + "\n"; m_dirtyFunctions = true; } return String.Format( header, inParams ); } public void AddFunction( string functionId, string body ) { if ( !m_localFunctions.ContainsKey( functionId ) ) { m_localFunctions.Add( functionId, body ); m_functions += "\n" + body + "\n"; m_dirtyFunctions = true; } } public void AddInstructions( string value, bool addTabs = false, bool addLineEnding = false ) { m_instructions += addTabs ? "\t\t\t" + value : value; if ( addLineEnding ) { m_instructions += '\n'; } m_dirtyInstructions = true; } public void AddInstructions( bool addLineEnding, bool addTabs, params string[] values ) { for ( int i = 0; i < values.Length; i++ ) { m_instructions += addTabs ? "\t\t\t" + values[ i ] : values[ i ]; if ( addLineEnding ) { m_instructions += '\n'; } } m_dirtyInstructions = true; } public void AddToStartInstructions( string value ) { if ( string.IsNullOrEmpty( value ) ) return; m_instructions = value + m_instructions; m_dirtyInstructions = true; } public void AddPropertyNode( PropertyNode node ) { if ( !m_propertyNodes.ContainsKey( node.UniqueId ) ) { m_propertyNodes.Add( node.UniqueId, node ); } } public void UpdateMaterialOnPropertyNodes( Material material ) { m_masterNode.UpdateMaterial( material ); foreach ( KeyValuePair<int, PropertyNode> kvp in m_propertyNodes ) { kvp.Value.UpdateMaterial( material ); } } public void UpdateShaderOnPropertyNodes( ref Shader shader ) { if ( m_propertyNodes.Count == 0 ) return; try { bool hasContents = false; //string metaNewcontents = IOUtils.LINE_TERMINATOR.ToString(); TextureDefaultsDataColector defaultCol = new TextureDefaultsDataColector(); foreach ( KeyValuePair<int, PropertyNode> kvp in m_propertyNodes ) { hasContents = kvp.Value.UpdateShaderDefaults( ref shader, ref defaultCol ) || hasContents; } if ( hasContents ) { ShaderImporter importer = ( ShaderImporter ) ShaderImporter.GetAtPath( AssetDatabase.GetAssetPath( shader ) ); importer.SetDefaultTextures( defaultCol.NamesArr, defaultCol.ValuesArr ); importer.SaveAndReimport(); defaultCol.Destroy(); defaultCol = null; //string metaFilepath = AssetDatabase.GetTextMetaFilePathFromAssetPath( AssetDatabase.GetAssetPath( shader ) ); //string metaContents = IOUtils.LoadTextFileFromDisk( metaFilepath ); //int startIndex = metaContents.IndexOf( IOUtils.MetaBegin ); //int endIndex = metaContents.IndexOf( IOUtils.MetaEnd ); //if ( startIndex > 0 && endIndex > 0 ) //{ // startIndex += IOUtils.MetaBegin.Length; // string replace = metaContents.Substring( startIndex, ( endIndex - startIndex ) ); // if ( hasContents ) // { // metaContents = metaContents.Replace( replace, metaNewcontents ); // } //} //IOUtils.SaveTextfileToDisk( metaContents, metaFilepath, false ); } } catch ( Exception e ) { Debug.LogException( e ); } } public void Destroy() { m_masterNode = null; m_propertyNodes.Clear(); m_propertyNodes = null; m_inputDict.Clear(); m_inputDict = null; m_customInputDict.Clear(); m_customInputDict = null; m_propertiesDict.Clear(); m_propertiesDict = null; m_instancedPropertiesDict.Clear(); m_instancedPropertiesDict = null; m_uniformsDict.Clear(); m_uniformsDict = null; m_includesDict.Clear(); m_includesDict = null; m_pragmasDict.Clear(); m_pragmasDict = null; m_virtualCoordinatesDict.Clear(); m_virtualCoordinatesDict = null; m_localVariablesDict.Clear(); m_localVariablesDict = null; m_specialLocalVariablesDict.Clear(); m_specialLocalVariablesDict = null; m_vertexLocalVariablesDict.Clear(); m_vertexLocalVariablesDict = null; m_localFunctions.Clear(); m_localFunctions = null; m_vertexDataDict.Clear(); m_vertexDataDict = null; m_customOutputDict.Clear(); m_customOutputDict = null; } public string Inputs { get { return m_input; } } public string CustomInput { get { return m_customInput; } } public string Properties { get { return m_properties; } } public string InstancedProperties { get { return m_instancedProperties; } } public string Uniforms { get { return m_uniforms; } } public string Instructions { get { return m_instructions; } } public string Includes { get { return m_includes; } } public string Pragmas { get { return m_pragmas; } } public string LocalVariables { get { return m_localVariables; } } public string SpecialLocalVariables { get { return m_specialLocalVariables; } } public string VertexLocalVariables { get { return m_vertexLocalVariables; } } public string VertexData { get { return m_vertexData; } } public string CustomOutput { get { return m_customOutput; } } public string Functions { get { return m_functions; } } public string GrabPass { get { return m_grabPass; } } public bool DirtyInstructions { get { return m_dirtyInstructions; } } public bool DirtyUniforms { get { return m_dirtyUniforms; } } public bool DirtyProperties { get { return m_dirtyProperties; } } public bool DirtyInstancedProperties { get { return m_dirtyInstancedProperties; } } public bool DirtyInputs { get { return m_dirtyInputs; } } public bool DirtyCustomInput { get { return m_dirtyCustomInputs; } } public bool DirtyIncludes { get { return m_dirtyIncludes; } } public bool DirtyPragmas { get { return m_dirtyPragmas; } } public bool DirtyLocalVariables { get { return m_dirtyLocalVariables; } } public bool DirtyVertexVariables { get { return m_dirtyVertexLocalVariables; } } public bool DirtySpecialLocalVariables { get { return m_dirtySpecialLocalVariables; } } public bool DirtyPerVertexData { get { return m_dirtyPerVertexData; } } public bool DirtyFunctions { get { return m_dirtyFunctions; } } public bool DirtyGrabPass { get { return m_grabPassIsDirty; } } public int LocalVariablesAmount { get { return m_localVariablesDict.Count; } } public int SpecialLocalVariablesAmount { get { return m_specialLocalVariablesDict.Count; } } public int VertexLocalVariablesAmount { get { return m_vertexLocalVariablesDict.Count; } } public int AvailableUvIndex { get { return m_availableUvInd++; } } public bool TesselationActive { set { m_tesselationActive = value; } get { return m_tesselationActive; } } public int AvailableVertexTempId { get { return m_availableVertexTempId++; } } public int AvailableFragTempId { get { return m_availableFragTempId++; } } /// <summary> /// Returns true if Normal output is being written by something else /// </summary> public bool DirtyNormal { get { return m_dirtyNormal; } set { m_dirtyNormal = value; } } public MasterNodePortCategory PortCategory { get { return m_portCategory; } set { m_portCategory = value; } } /// <summary> /// Forces write to Normal output when the output is not connected /// </summary> public bool ForceNormal { get { return m_forceNormal; } set { if ( value ) { if ( !m_forceNormalIsDirty ) { m_forceNormal = value; m_forceNormalIsDirty = value; } } else { m_forceNormal = value; } } } public bool UsingInternalData { get { return m_usingInternalData; } set { m_usingInternalData = value; } } public bool UsingWorldNormal { get { return m_usingWorldNormal; } set { m_usingWorldNormal = value; } } public bool UsingWorldReflection { get { return m_usingWorldReflection; } set { m_usingWorldReflection = value; } } public bool UsingWorldPosition { get { return m_usingWorldPosition; } set { m_usingWorldPosition = value; } } public bool UsingViewDirection { get { return m_usingViewDirection; } set { m_usingViewDirection = value; } } public bool UsingTexcoord0 { get { return m_usingTexcoord0; } set { m_usingTexcoord0 = value; } } public bool UsingTexcoord1 { get { return m_usingTexcoord1; } set { m_usingTexcoord1 = value; } } public bool UsingTexcoord2 { get { return m_usingTexcoord2; } set { m_usingTexcoord2 = value; } } public bool UsingTexcoord3 { get { return m_usingTexcoord3; } set { m_usingTexcoord3 = value; } } public bool UsingCustomOutput { get { return m_usingCustomOutput; } set { m_usingCustomOutput = value; } } public bool UsingHigherSizeTexcoords { get { return m_usingHigherSizeTexcoords; } set { m_usingHigherSizeTexcoords = value; } } } }
/* * DISCLAIMER * * Copyright 2016 ArangoDB GmbH, Cologne, Germany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright holder is ArangoDB GmbH, Cologne, Germany */ namespace ArangoDB.Internal { using global::ArangoDB.Entity; using global::ArangoDB.Internal.VelocyStream; using global::ArangoDB.Model; using global::ArangoDB.Velocypack; using global::ArangoDB.Velocypack.Exceptions; using global::ArangoDB.Velocystream; /// <author>Mark - mark at arangodb.com</author> public class InternalArangoGraph<E, R, C> : ArangoExecuteable <E, R, C> where E : ArangoExecutor<R, C> where C : Connection { private readonly string db; private readonly string name; public InternalArangoGraph(E executor, string db, string name) : base(executor) { this.db = db; this.name = name; } public virtual string db() { return db; } public virtual string name() { return name; } protected internal virtual Request dropRequest() { return new Request(db, RequestType .DELETE, this.executor.createPath(ArangoDBConstants.PATH_API_GHARIAL , name)); } protected internal virtual Request getInfoRequest() { return new Request(db, RequestType .GET, this.executor.createPath(ArangoDBConstants.PATH_API_GHARIAL , name)); } protected internal virtual com.arangodb.@internal.ArangoExecutor.ResponseDeserializer <GraphEntity> getInfoResponseDeserializer() { return this.addVertexCollectionResponseDeserializer(); } protected internal virtual Request getVertexCollectionsRequest () { return new Request(db, RequestType .GET, this.executor.createPath(ArangoDBConstants.PATH_API_GHARIAL , name, ArangoDBConstants.VERTEX)); } protected internal virtual com.arangodb.@internal.ArangoExecutor.ResponseDeserializer <System.Collections.Generic.ICollection<string>> getVertexCollectionsResponseDeserializer () { return new _ResponseDeserializer_79(this); } private sealed class _ResponseDeserializer_79 : com.arangodb.@internal.ArangoExecutor.ResponseDeserializer <System.Collections.Generic.ICollection<string>> { public _ResponseDeserializer_79(InternalArangoGraph<E, R, C> _enclosing) { this._enclosing = _enclosing; } /// <exception cref="VPackException"/> public System.Collections.Generic.ICollection<string> deserialize(Response response) { return this._enclosing.executor.Deserialize(response.getBody().get(ArangoDBConstants .COLLECTIONS), new _Type_83().getType()); } private sealed class _Type_83 : Type<System.Collections.Generic.ICollection <string>> { public _Type_83() { } } private readonly InternalArangoGraph<E, R, C> _enclosing; } protected internal virtual Request addVertexCollectionRequest (string name) { Request request = new Request (db, RequestType.POST, this.executor.createPath(ArangoDBConstants .PATH_API_GHARIAL, name(), ArangoDBConstants.VERTEX)); request.setBody(this.executor.Serialize(OptionsBuilder.build(new VertexCollectionCreateOptions (), name))); return request; } protected internal virtual com.arangodb.@internal.ArangoExecutor.ResponseDeserializer <GraphEntity> addVertexCollectionResponseDeserializer() { return this.addEdgeDefinitionResponseDeserializer(); } protected internal virtual Request getEdgeDefinitionsRequest () { return new Request(db, RequestType .GET, this.executor.createPath(ArangoDBConstants.PATH_API_GHARIAL , name, ArangoDBConstants.EDGE)); } protected internal virtual com.arangodb.@internal.ArangoExecutor.ResponseDeserializer <System.Collections.Generic.ICollection<string>> getEdgeDefinitionsDeserializer( ) { return new _ResponseDeserializer_106(this); } private sealed class _ResponseDeserializer_106 : com.arangodb.@internal.ArangoExecutor.ResponseDeserializer <System.Collections.Generic.ICollection<string>> { public _ResponseDeserializer_106(InternalArangoGraph<E, R, C> _enclosing) { this._enclosing = _enclosing; } /// <exception cref="VPackException"/> public System.Collections.Generic.ICollection<string> deserialize(Response response) { return this._enclosing.executor.Deserialize(response.getBody().get(ArangoDBConstants .COLLECTIONS), new _Type_110().getType()); } private sealed class _Type_110 : Type<System.Collections.Generic.ICollection <string>> { public _Type_110() { } } private readonly InternalArangoGraph<E, R, C> _enclosing; } protected internal virtual Request addEdgeDefinitionRequest (EdgeDefinition definition) { Request request = new Request (db, RequestType.POST, this.executor.createPath(ArangoDBConstants .PATH_API_GHARIAL, name, ArangoDBConstants.EDGE)); request.setBody(this.executor.Serialize(definition)); return request; } protected internal virtual com.arangodb.@internal.ArangoExecutor.ResponseDeserializer <GraphEntity> addEdgeDefinitionResponseDeserializer() { return new _ResponseDeserializer_124(this); } private sealed class _ResponseDeserializer_124 : com.arangodb.@internal.ArangoExecutor.ResponseDeserializer <GraphEntity> { public _ResponseDeserializer_124(InternalArangoGraph<E, R, C> _enclosing) { this._enclosing = _enclosing; } /// <exception cref="VPackException"/> public GraphEntity deserialize(Response response) { return this._enclosing.executor.Deserialize(response.getBody().get(ArangoDBConstants .GRAPH), typeof(GraphEntity )); } private readonly InternalArangoGraph<E, R, C> _enclosing; } protected internal virtual Request replaceEdgeDefinitionRequest (EdgeDefinition definition) { Request request = new Request (db, RequestType.PUT, this.executor.createPath(ArangoDBConstants .PATH_API_GHARIAL, name, ArangoDBConstants.EDGE, definition .getCollection())); request.setBody(this.executor.Serialize(definition)); return request; } protected internal virtual com.arangodb.@internal.ArangoExecutor.ResponseDeserializer <GraphEntity> replaceEdgeDefinitionResponseDeserializer() { return new _ResponseDeserializer_140(this); } private sealed class _ResponseDeserializer_140 : com.arangodb.@internal.ArangoExecutor.ResponseDeserializer <GraphEntity> { public _ResponseDeserializer_140(InternalArangoGraph<E, R, C> _enclosing) { this._enclosing = _enclosing; } /// <exception cref="VPackException"/> public GraphEntity deserialize(Response response) { return this._enclosing.executor.Deserialize(response.getBody().get(ArangoDBConstants .GRAPH), typeof(GraphEntity )); } private readonly InternalArangoGraph<E, R, C> _enclosing; } protected internal virtual Request removeEdgeDefinitionRequest (string definitionName) { return new Request(db, RequestType .DELETE, this.executor.createPath(ArangoDBConstants.PATH_API_GHARIAL , name, ArangoDBConstants.EDGE, definitionName)); } protected internal virtual com.arangodb.@internal.ArangoExecutor.ResponseDeserializer <GraphEntity> removeEdgeDefinitionResponseDeserializer() { return new _ResponseDeserializer_154(this); } private sealed class _ResponseDeserializer_154 : com.arangodb.@internal.ArangoExecutor.ResponseDeserializer <GraphEntity> { public _ResponseDeserializer_154(InternalArangoGraph<E, R, C> _enclosing) { this._enclosing = _enclosing; } /// <exception cref="VPackException"/> public GraphEntity deserialize(Response response) { return this._enclosing.executor.Deserialize(response.getBody().get(ArangoDBConstants .GRAPH), typeof(GraphEntity )); } private readonly InternalArangoGraph<E, R, C> _enclosing; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.Remoting.Lifetime; using OpenSim.Region.ScriptEngine.Shared; using OpenSim.Region.ScriptEngine.Shared.ScriptBase; using log4net; namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase { public class Executor { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Contains the script to execute functions in. /// </summary> protected IScript m_Script; protected Dictionary<string, scriptEvents> m_eventFlagsMap = new Dictionary<string, scriptEvents>(); [Flags] public enum scriptEvents : int { None = 0, attach = 1, collision = 16, collision_end = 32, collision_start = 64, control = 128, dataserver = 256, email = 512, http_response = 1024, land_collision = 2048, land_collision_end = 4096, land_collision_start = 8192, at_target = 16384, at_rot_target = 16777216, listen = 32768, money = 65536, moving_end = 131072, moving_start = 262144, not_at_rot_target = 524288, not_at_target = 1048576, remote_data = 8388608, run_time_permissions = 268435456, state_entry = 1073741824, state_exit = 2, timer = 4, touch = 8, touch_end = 536870912, touch_start = 2097152, transaction_result = 33554432, object_rez = 4194304 } // Cache functions by keeping a reference to them in a dictionary private Dictionary<string, MethodInfo> Events = new Dictionary<string, MethodInfo>(); private Dictionary<string, scriptEvents> m_stateEvents = new Dictionary<string, scriptEvents>(); public Executor(IScript script) { m_Script = script; initEventFlags(); } public scriptEvents GetStateEventFlags(string state) { //m_log.Debug("Get event flags for " + state); // Check to see if we've already computed the flags for this state scriptEvents eventFlags = scriptEvents.None; if (m_stateEvents.ContainsKey(state)) { m_stateEvents.TryGetValue(state, out eventFlags); return eventFlags; } Type type=m_Script.GetType(); // Fill in the events for this state, cache the results in the map foreach (KeyValuePair<string, scriptEvents> kvp in m_eventFlagsMap) { string evname = state + "_event_" + kvp.Key; //m_log.Debug("Trying event "+evname); try { MethodInfo mi = type.GetMethod(evname); if (mi != null) { //m_log.Debug("Found handler for " + kvp.Key); eventFlags |= kvp.Value; } } catch(Exception) { //m_log.Debug("Exeption in GetMethod:\n"+e.ToString()); } } // Save the flags we just computed and return the result if (eventFlags != 0) m_stateEvents.Add(state, eventFlags); //m_log.Debug("Returning {0:x}", eventFlags); return (eventFlags); } public void ExecuteEvent(string state, string FunctionName, object[] args) { // IMPORTANT: Types and MemberInfo-derived objects require a LOT of memory. // Instead use RuntimeTypeHandle, RuntimeFieldHandle and RunTimeHandle (IntPtr) instead! string EventName = state + "_event_" + FunctionName; //#if DEBUG //m_log.Debug("ScriptEngine: Script event function name: " + EventName); //#endif if (Events.ContainsKey(EventName) == false) { // Not found, create Type type = m_Script.GetType(); try { MethodInfo mi = type.GetMethod(EventName); Events.Add(EventName, mi); } catch { // m_log.Error("Event "+EventName+" not found."); // Event name not found, cache it as not found Events.Add(EventName, null); } } // Get event MethodInfo ev = null; Events.TryGetValue(EventName, out ev); if (ev == null) // No event by that name! { //m_log.Debug("ScriptEngine Can not find any event named: \String.Empty + EventName + "\String.Empty); return; } //cfk 2-7-08 dont need this right now and the default Linux build has DEBUG defined #if DEBUG //m_log.Debug("ScriptEngine: Executing function name: " + EventName); #endif // Found try { ev.Invoke(m_Script, args); } catch (TargetInvocationException tie) { // Grab the inner exception and rethrow it, unless the inner // exception is an EventAbortException as this indicates event // invocation termination due to a state change. // DO NOT THROW JUST THE INNER EXCEPTION! // FriendlyErrors depends on getting the whole exception! // if (!(tie.InnerException is EventAbortException)) { throw; } } } protected void initEventFlags() { // Initialize the table if it hasn't already been done if (m_eventFlagsMap.Count > 0) { return; } m_eventFlagsMap.Add("attach", scriptEvents.attach); m_eventFlagsMap.Add("at_rot_target", scriptEvents.at_rot_target); m_eventFlagsMap.Add("at_target", scriptEvents.at_target); // m_eventFlagsMap.Add("changed",(long)scriptEvents.changed); m_eventFlagsMap.Add("collision", scriptEvents.collision); m_eventFlagsMap.Add("collision_end", scriptEvents.collision_end); m_eventFlagsMap.Add("collision_start", scriptEvents.collision_start); m_eventFlagsMap.Add("control", scriptEvents.control); m_eventFlagsMap.Add("dataserver", scriptEvents.dataserver); m_eventFlagsMap.Add("email", scriptEvents.email); m_eventFlagsMap.Add("http_response", scriptEvents.http_response); m_eventFlagsMap.Add("land_collision", scriptEvents.land_collision); m_eventFlagsMap.Add("land_collision_end", scriptEvents.land_collision_end); m_eventFlagsMap.Add("land_collision_start", scriptEvents.land_collision_start); // m_eventFlagsMap.Add("link_message",scriptEvents.link_message); m_eventFlagsMap.Add("listen", scriptEvents.listen); m_eventFlagsMap.Add("money", scriptEvents.money); m_eventFlagsMap.Add("moving_end", scriptEvents.moving_end); m_eventFlagsMap.Add("moving_start", scriptEvents.moving_start); m_eventFlagsMap.Add("not_at_rot_target", scriptEvents.not_at_rot_target); m_eventFlagsMap.Add("not_at_target", scriptEvents.not_at_target); // m_eventFlagsMap.Add("no_sensor",(long)scriptEvents.no_sensor); // m_eventFlagsMap.Add("on_rez",(long)scriptEvents.on_rez); m_eventFlagsMap.Add("remote_data", scriptEvents.remote_data); m_eventFlagsMap.Add("run_time_permissions", scriptEvents.run_time_permissions); // m_eventFlagsMap.Add("sensor",(long)scriptEvents.sensor); m_eventFlagsMap.Add("state_entry", scriptEvents.state_entry); m_eventFlagsMap.Add("state_exit", scriptEvents.state_exit); m_eventFlagsMap.Add("timer", scriptEvents.timer); m_eventFlagsMap.Add("touch", scriptEvents.touch); m_eventFlagsMap.Add("touch_end", scriptEvents.touch_end); m_eventFlagsMap.Add("touch_start", scriptEvents.touch_start); m_eventFlagsMap.Add("transaction_result", scriptEvents.transaction_result); m_eventFlagsMap.Add("object_rez", scriptEvents.object_rez); } } }
/* Copyright(c) 2009, Stefan Simek Copyright(c) 2016, Vladyslav Taranov MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Text; #if FEAT_IKVM using IKVM.Reflection; using IKVM.Reflection.Emit; using Type = IKVM.Reflection.Type; using MissingMethodException = System.MissingMethodException; using MissingMemberException = System.MissingMemberException; using DefaultMemberAttribute = System.Reflection.DefaultMemberAttribute; using Attribute = IKVM.Reflection.CustomAttributeData; using BindingFlags = IKVM.Reflection.BindingFlags; #else using System.Reflection; using System.Reflection.Emit; #endif namespace TriAxis.RunSharp.Operands { class OverloadableOperation : Operand { readonly Operator _op; readonly Operand[] _operands; ApplicableFunction _af; Operand _afInterceptor; Type _returnType; protected override void ResetLeakedStateRecursively() { base.ResetLeakedStateRecursively(); OperandExtensions.SetLeakedState(_operands, false); } public OverloadableOperation(Operator op, params Operand[] operands) { _op = op; _operands = operands; } internal void SetOperand(Operand newOp) { _operands[0] = newOp; } readonly List<LocalCache>_caches=new List<LocalCache>(); void PrepareAf(ITypeMapper typeMapper) { if (_af != null || !ReferenceEquals(_afInterceptor, null)) return; Operand[] operandsValueOrDefault = new Operand[2]; Operand[] operandsHasValue = new Operand[2]; Operand[] operandsValue = new Operand[2]; int nullables = 0; int nulls = 0; int lastNullableIndex = -1; for (int i = 0; i < _operands.Length; i++) { var op = _operands[i]; if (ReferenceEquals(op, null)) { nulls++; continue; } Type vt = op.GetReturnType(typeMapper); if (vt.IsValueType && (Helpers.GetNullableUnderlyingType(vt) != null)) { if (!op.TrivialAccess) { var cache = new LocalCache(op); _caches.Add(cache); op = cache; } operandsValueOrDefault[i] = op.Invoke("GetValueOrDefault", typeMapper).SetNotLeaked(); operandsValue[i] = op.Property("Value", typeMapper).SetNotLeaked(); operandsHasValue[i] = op.Property("HasValue", typeMapper).SetNotLeaked(); nullables++; lastNullableIndex = i; } else { operandsValueOrDefault[i] = op; operandsValue[i] = op; } } if (nullables > 0 && nulls == 0) { if (_operands.Length == 2) { var nonNullableOperation = new OverloadableOperation(_op, operandsValueOrDefault[0], operandsValueOrDefault[1]); Type returnType = nonNullableOperation.GetReturnType(typeMapper); // when no value // for comparsion we return false, // for +-, etc we return nullable null Type nullableReturnType = typeMapper.MapType(typeof(Nullable<>)).MakeGenericType(returnType); // bool? || bool? - not allowed // bool? || bool - not allowed // but bool? | bool - allowed but not logical! // the difference between logical == != vs normal: for we should always return true or false // expression "(int?) == 5" is not nullable but "int? + 5" is! if (_op.IsLogical) { // true or false required _returnType = typeMapper.MapType(typeof(bool)); if (_op.BranchOp == BranchInstruction.Ne) { if (nullables == 1) { Operand notHasValue = !operandsHasValue[lastNullableIndex]; _afInterceptor = new Conditional(nonNullableOperation, true, notHasValue); } else { // ((nullable.GetValueOrDefault() != nullable2.GetValueOrDefault()) ? true : (nullable.HasValue != nullable2.HasValue)) Operand hasValueNotEqual = operandsHasValue[0] != operandsHasValue[1]; _afInterceptor = new Conditional(nonNullableOperation, true, hasValueNotEqual); } } else { // ((nullable.GetValueOrDefault() == nullable2.GetValueOrDefault()) ? (nullable.HasValue == nullable2.HasValue) : false) Operand hasValueEqualCheck = nullables == 2 ? operandsHasValue[0] == operandsHasValue[1] : operandsHasValue[lastNullableIndex]; _afInterceptor = new Conditional(nonNullableOperation, hasValueEqualCheck, false); } } else { // nullable return: // long? = int? + long? // long? = (a.HasValue && b.HasValue) ? new long?(a.Value + b.Value) : (long?)null _returnType = nullableReturnType; nonNullableOperation = new OverloadableOperation(_op, operandsValue[0], operandsValue[1]); var ctorArgs = new Operand[] { nonNullableOperation }; var ctor = typeMapper.TypeInfo.FindConstructor(nullableReturnType, ctorArgs); Operand bothWithValueCondition = nullables == 2 ? operandsHasValue[0] && operandsHasValue[1] : operandsHasValue[lastNullableIndex]; _afInterceptor = new Conditional(bothWithValueCondition, new NewObject(ctor, ctorArgs), new DefaultValue(nullableReturnType)); } return; } else if (_operands.Length == 1) { // convert increment/decrement to binary operators if (_op.OpCode == OpCodes.Add) { _afInterceptor = _operands[0] + 1; _returnType = _afInterceptor.GetReturnType(typeMapper); return; } if (_op.OpCode == OpCodes.Sub) { _afInterceptor = _operands[0] - 1; _returnType = _afInterceptor.GetReturnType(typeMapper); return; } } } PrepareAfNormally(typeMapper, _operands); if (_af == null) throw new AmbiguousMatchException(Properties.Messages.ErrAmbiguousBinding); _returnType = _af.Method.ReturnType; } void PrepareAfNormally(ITypeMapper typeMapper, Operand[] afOperands) { List<ApplicableFunction> candidates = null; foreach (Operand operand in afOperands) { if ((object)operand != null && !operand.GetReturnType(typeMapper).IsPrimitive) { // try overloads candidates = _op.FindUserCandidates(typeMapper, afOperands); break; } } if (candidates == null) candidates = OverloadResolver.FindApplicable(_op.GetStandardCandidates(typeMapper, afOperands), typeMapper, afOperands); if (candidates == null) throw new InvalidOperationException( string.Format( null, Properties.Messages.ErrInvalidOperation, _op.MethodName, string.Join(", ", ConvertAll<Operand, string>(afOperands, op => op.GetReturnType(typeMapper).FullName)))); _af = OverloadResolver.FindBest(candidates, typeMapper); } static TOut[] ConvertAll<TIn, TOut>(TIn[] array, Converter<TIn, TOut> converter) { TOut[] newArray = new TOut[array.Length]; for (int i = 0; i < array.Length; i++) { newArray[i] = converter(array[i]); } return newArray; } protected internal override void EmitGet(CodeGen g) { OperandExtensions.SetLeakedState(this, false); foreach (LocalCache lc in _caches) { lc.Clear(); } // value type handling if (_operands.Length == 2) { var valueOperand = _operands[0] ?? _operands[1]; Type returnType = valueOperand?.GetReturnType(g.TypeMapper); if ((ReferenceEquals(_operands[0], null) || ReferenceEquals(_operands[1], null)) && (returnType?.IsValueType ?? false)) { bool isNullable = Helpers.GetNullableUnderlyingType(returnType) != null; if (_op.BranchOp == BranchInstruction.Ne) { if (isNullable) { valueOperand.Property("HasValue", g.TypeMapper).EmitGet(g); } else { g.EmitI4Helper(1); } return; } else if (_op.BranchOp == BranchInstruction.Eq) { if (isNullable) { valueOperand.Property("HasValue", g.TypeMapper).LogicalNot().EmitGet(g); } else { g.EmitI4Helper(0); } return; } else if (_op.IsLogical) // 5? > null, 5 <= null, ... { g.EmitI4Helper(0); return; } } } PrepareAf(g.TypeMapper); if (!ReferenceEquals(_afInterceptor, null)) { _afInterceptor.EmitGet(g); return; } _af.EmitArgs(g, _operands); IStandardOperation sop = _af.Method as IStandardOperation; if (sop != null) sop.Emit(g, _op); else g.IL.Emit(OpCodes.Call, (MethodInfo)_af.Method.Member); } protected internal override void EmitBranch(CodeGen g, OptionalLabel labelTrue, OptionalLabel labelFalse) { OperandExtensions.SetLeakedState(this, false); foreach (LocalCache lc in _caches) { lc.Clear(); } bool argsEmitted = false; var branchSet = BranchSet.Normal; // value type handling if (_operands.Length == 2) { var valueOperand = _operands[0] ?? _operands[1]; Type returnType = valueOperand?.GetReturnType(g.TypeMapper); if (returnType?.IsValueType ?? false) { if (ReferenceEquals(_operands[0], null) || ReferenceEquals(_operands[1], null)) { bool isNullable = Helpers.GetNullableUnderlyingType(returnType) != null; var op = branchSet.Get(_op.BranchOp, true); if (op == OpCodes.Bne_Un || op == OpCodes.Bne_Un_S) { if (isNullable) { valueOperand.Property("HasValue", g.TypeMapper).EmitBranch(g, labelTrue, labelFalse); } else { // ValueType != null, should return true if (labelTrue != null && labelTrue.IsLabelExist) // otherwise default path g.IL.Emit(OpCodes.Br, labelTrue.Value); } return; } else if (op == OpCodes.Beq || op == OpCodes.Beq_S) { if (isNullable) { valueOperand.Property("HasValue", g.TypeMapper).EmitBranch(g, labelFalse, labelTrue); } else { // ValueType == null, should return false if (labelFalse != null && labelFalse.IsLabelExist) // otherwise default path g.IL.Emit(OpCodes.Br, labelFalse.Value); } return; } else if (_op.IsLogical) // 5? > null, 5 <= null, ... { if (labelFalse != null && labelFalse.IsLabelExist) // otherwise default path g.IL.Emit(OpCodes.Br, labelFalse.Value); } } } } PrepareAf(g.TypeMapper); if (!ReferenceEquals(_afInterceptor, null)) { _afInterceptor.EmitBranch(g, labelTrue, labelFalse); return; } IStandardOperation stdOp = _af.Method as IStandardOperation; if (_op.BranchOp == 0 || stdOp == null) { base.EmitBranch(g, labelTrue, labelFalse); return; } if (!argsEmitted) _af.EmitArgs(g, _operands); bool inverted = false; if (labelTrue == null || !labelTrue.IsLabelExist) { if (labelFalse == null) throw new InvalidOperationException("No labels passed"); if (!labelFalse.IsLabelExist) throw new InvalidOperationException("No existing labels were passed"); labelTrue = labelFalse; branchSet = branchSet.GetInverted(); inverted = true; } g.IL.Emit(branchSet.Get(_op.BranchOp, stdOp.IsUnsigned), labelTrue.Value); if (!inverted && labelFalse != null && labelFalse.IsLabelExist) g.IL.Emit(OpCodes.Br, labelFalse.Value); } public override Type GetReturnType(ITypeMapper typeMapper) { PrepareAf(typeMapper); return _returnType; } } }
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 SAEON.Observations.Data{ /// <summary> /// Strongly-typed collection for the VStationOrganisation class. /// </summary> [Serializable] public partial class VStationOrganisationCollection : ReadOnlyList<VStationOrganisation, VStationOrganisationCollection> { public VStationOrganisationCollection() {} } /// <summary> /// This is Read-only wrapper class for the vStationOrganisation view. /// </summary> [Serializable] public partial class VStationOrganisation : ReadOnlyRecord<VStationOrganisation>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor 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("vStationOrganisation", TableType.View, DataService.GetInstance("ObservationsDB")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema); colvarId.ColumnName = "ID"; colvarId.DataType = DbType.Guid; colvarId.MaxLength = 0; colvarId.AutoIncrement = false; colvarId.IsNullable = false; colvarId.IsPrimaryKey = false; colvarId.IsForeignKey = false; colvarId.IsReadOnly = false; schema.Columns.Add(colvarId); TableSchema.TableColumn colvarOrganisationID = new TableSchema.TableColumn(schema); colvarOrganisationID.ColumnName = "OrganisationID"; colvarOrganisationID.DataType = DbType.Guid; colvarOrganisationID.MaxLength = 0; colvarOrganisationID.AutoIncrement = false; colvarOrganisationID.IsNullable = false; colvarOrganisationID.IsPrimaryKey = false; colvarOrganisationID.IsForeignKey = false; colvarOrganisationID.IsReadOnly = false; schema.Columns.Add(colvarOrganisationID); TableSchema.TableColumn colvarOrganisationCode = new TableSchema.TableColumn(schema); colvarOrganisationCode.ColumnName = "OrganisationCode"; colvarOrganisationCode.DataType = DbType.AnsiString; colvarOrganisationCode.MaxLength = 50; colvarOrganisationCode.AutoIncrement = false; colvarOrganisationCode.IsNullable = false; colvarOrganisationCode.IsPrimaryKey = false; colvarOrganisationCode.IsForeignKey = false; colvarOrganisationCode.IsReadOnly = false; schema.Columns.Add(colvarOrganisationCode); TableSchema.TableColumn colvarOrganisationName = new TableSchema.TableColumn(schema); colvarOrganisationName.ColumnName = "OrganisationName"; colvarOrganisationName.DataType = DbType.AnsiString; colvarOrganisationName.MaxLength = 150; colvarOrganisationName.AutoIncrement = false; colvarOrganisationName.IsNullable = false; colvarOrganisationName.IsPrimaryKey = false; colvarOrganisationName.IsForeignKey = false; colvarOrganisationName.IsReadOnly = false; schema.Columns.Add(colvarOrganisationName); TableSchema.TableColumn colvarStationID = new TableSchema.TableColumn(schema); colvarStationID.ColumnName = "StationID"; colvarStationID.DataType = DbType.Guid; colvarStationID.MaxLength = 0; colvarStationID.AutoIncrement = false; colvarStationID.IsNullable = false; colvarStationID.IsPrimaryKey = false; colvarStationID.IsForeignKey = false; colvarStationID.IsReadOnly = false; schema.Columns.Add(colvarStationID); TableSchema.TableColumn colvarStationCode = new TableSchema.TableColumn(schema); colvarStationCode.ColumnName = "StationCode"; colvarStationCode.DataType = DbType.AnsiString; colvarStationCode.MaxLength = 50; colvarStationCode.AutoIncrement = false; colvarStationCode.IsNullable = false; colvarStationCode.IsPrimaryKey = false; colvarStationCode.IsForeignKey = false; colvarStationCode.IsReadOnly = false; schema.Columns.Add(colvarStationCode); TableSchema.TableColumn colvarStationName = new TableSchema.TableColumn(schema); colvarStationName.ColumnName = "StationName"; colvarStationName.DataType = DbType.AnsiString; colvarStationName.MaxLength = 150; colvarStationName.AutoIncrement = false; colvarStationName.IsNullable = false; colvarStationName.IsPrimaryKey = false; colvarStationName.IsForeignKey = false; colvarStationName.IsReadOnly = false; schema.Columns.Add(colvarStationName); TableSchema.TableColumn colvarOrganisationRoleID = new TableSchema.TableColumn(schema); colvarOrganisationRoleID.ColumnName = "OrganisationRoleID"; colvarOrganisationRoleID.DataType = DbType.Guid; colvarOrganisationRoleID.MaxLength = 0; colvarOrganisationRoleID.AutoIncrement = false; colvarOrganisationRoleID.IsNullable = false; colvarOrganisationRoleID.IsPrimaryKey = false; colvarOrganisationRoleID.IsForeignKey = false; colvarOrganisationRoleID.IsReadOnly = false; schema.Columns.Add(colvarOrganisationRoleID); TableSchema.TableColumn colvarOrganisationRoleCode = new TableSchema.TableColumn(schema); colvarOrganisationRoleCode.ColumnName = "OrganisationRoleCode"; colvarOrganisationRoleCode.DataType = DbType.AnsiString; colvarOrganisationRoleCode.MaxLength = 50; colvarOrganisationRoleCode.AutoIncrement = false; colvarOrganisationRoleCode.IsNullable = false; colvarOrganisationRoleCode.IsPrimaryKey = false; colvarOrganisationRoleCode.IsForeignKey = false; colvarOrganisationRoleCode.IsReadOnly = false; schema.Columns.Add(colvarOrganisationRoleCode); TableSchema.TableColumn colvarOrganisationRoleName = new TableSchema.TableColumn(schema); colvarOrganisationRoleName.ColumnName = "OrganisationRoleName"; colvarOrganisationRoleName.DataType = DbType.AnsiString; colvarOrganisationRoleName.MaxLength = 150; colvarOrganisationRoleName.AutoIncrement = false; colvarOrganisationRoleName.IsNullable = false; colvarOrganisationRoleName.IsPrimaryKey = false; colvarOrganisationRoleName.IsForeignKey = false; colvarOrganisationRoleName.IsReadOnly = false; schema.Columns.Add(colvarOrganisationRoleName); TableSchema.TableColumn colvarStartDate = new TableSchema.TableColumn(schema); colvarStartDate.ColumnName = "StartDate"; colvarStartDate.DataType = DbType.Date; colvarStartDate.MaxLength = 0; colvarStartDate.AutoIncrement = false; colvarStartDate.IsNullable = true; colvarStartDate.IsPrimaryKey = false; colvarStartDate.IsForeignKey = false; colvarStartDate.IsReadOnly = false; schema.Columns.Add(colvarStartDate); TableSchema.TableColumn colvarEndDate = new TableSchema.TableColumn(schema); colvarEndDate.ColumnName = "EndDate"; colvarEndDate.DataType = DbType.Date; colvarEndDate.MaxLength = 0; colvarEndDate.AutoIncrement = false; colvarEndDate.IsNullable = true; colvarEndDate.IsPrimaryKey = false; colvarEndDate.IsForeignKey = false; colvarEndDate.IsReadOnly = false; schema.Columns.Add(colvarEndDate); TableSchema.TableColumn colvarLevel = new TableSchema.TableColumn(schema); colvarLevel.ColumnName = "Level"; colvarLevel.DataType = DbType.AnsiString; colvarLevel.MaxLength = 10; colvarLevel.AutoIncrement = false; colvarLevel.IsNullable = false; colvarLevel.IsPrimaryKey = false; colvarLevel.IsForeignKey = false; colvarLevel.IsReadOnly = false; schema.Columns.Add(colvarLevel); TableSchema.TableColumn colvarLevelCode = new TableSchema.TableColumn(schema); colvarLevelCode.ColumnName = "LevelCode"; colvarLevelCode.DataType = DbType.AnsiString; colvarLevelCode.MaxLength = 50; colvarLevelCode.AutoIncrement = false; colvarLevelCode.IsNullable = false; colvarLevelCode.IsPrimaryKey = false; colvarLevelCode.IsForeignKey = false; colvarLevelCode.IsReadOnly = false; schema.Columns.Add(colvarLevelCode); TableSchema.TableColumn colvarLevelName = new TableSchema.TableColumn(schema); colvarLevelName.ColumnName = "LevelName"; colvarLevelName.DataType = DbType.AnsiString; colvarLevelName.MaxLength = 150; colvarLevelName.AutoIncrement = false; colvarLevelName.IsNullable = false; colvarLevelName.IsPrimaryKey = false; colvarLevelName.IsForeignKey = false; colvarLevelName.IsReadOnly = false; schema.Columns.Add(colvarLevelName); TableSchema.TableColumn colvarWeight = new TableSchema.TableColumn(schema); colvarWeight.ColumnName = "Weight"; colvarWeight.DataType = DbType.Int32; colvarWeight.MaxLength = 0; colvarWeight.AutoIncrement = false; colvarWeight.IsNullable = false; colvarWeight.IsPrimaryKey = false; colvarWeight.IsForeignKey = false; colvarWeight.IsReadOnly = false; schema.Columns.Add(colvarWeight); TableSchema.TableColumn colvarIsReadOnly = new TableSchema.TableColumn(schema); colvarIsReadOnly.ColumnName = "IsReadOnly"; colvarIsReadOnly.DataType = DbType.Boolean; colvarIsReadOnly.MaxLength = 0; colvarIsReadOnly.AutoIncrement = false; colvarIsReadOnly.IsNullable = true; colvarIsReadOnly.IsPrimaryKey = false; colvarIsReadOnly.IsForeignKey = false; colvarIsReadOnly.IsReadOnly = false; schema.Columns.Add(colvarIsReadOnly); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["ObservationsDB"].AddSchema("vStationOrganisation",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public VStationOrganisation() { SetSQLProps(); SetDefaults(); MarkNew(); } public VStationOrganisation(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public VStationOrganisation(object keyID) { SetSQLProps(); LoadByKey(keyID); } public VStationOrganisation(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("Id")] [Bindable(true)] public Guid Id { get { return GetColumnValue<Guid>("ID"); } set { SetColumnValue("ID", value); } } [XmlAttribute("OrganisationID")] [Bindable(true)] public Guid OrganisationID { get { return GetColumnValue<Guid>("OrganisationID"); } set { SetColumnValue("OrganisationID", value); } } [XmlAttribute("OrganisationCode")] [Bindable(true)] public string OrganisationCode { get { return GetColumnValue<string>("OrganisationCode"); } set { SetColumnValue("OrganisationCode", value); } } [XmlAttribute("OrganisationName")] [Bindable(true)] public string OrganisationName { get { return GetColumnValue<string>("OrganisationName"); } set { SetColumnValue("OrganisationName", value); } } [XmlAttribute("StationID")] [Bindable(true)] public Guid StationID { get { return GetColumnValue<Guid>("StationID"); } set { SetColumnValue("StationID", value); } } [XmlAttribute("StationCode")] [Bindable(true)] public string StationCode { get { return GetColumnValue<string>("StationCode"); } set { SetColumnValue("StationCode", value); } } [XmlAttribute("StationName")] [Bindable(true)] public string StationName { get { return GetColumnValue<string>("StationName"); } set { SetColumnValue("StationName", value); } } [XmlAttribute("OrganisationRoleID")] [Bindable(true)] public Guid OrganisationRoleID { get { return GetColumnValue<Guid>("OrganisationRoleID"); } set { SetColumnValue("OrganisationRoleID", value); } } [XmlAttribute("OrganisationRoleCode")] [Bindable(true)] public string OrganisationRoleCode { get { return GetColumnValue<string>("OrganisationRoleCode"); } set { SetColumnValue("OrganisationRoleCode", value); } } [XmlAttribute("OrganisationRoleName")] [Bindable(true)] public string OrganisationRoleName { get { return GetColumnValue<string>("OrganisationRoleName"); } set { SetColumnValue("OrganisationRoleName", value); } } [XmlAttribute("StartDate")] [Bindable(true)] public DateTime? StartDate { get { return GetColumnValue<DateTime?>("StartDate"); } set { SetColumnValue("StartDate", value); } } [XmlAttribute("EndDate")] [Bindable(true)] public DateTime? EndDate { get { return GetColumnValue<DateTime?>("EndDate"); } set { SetColumnValue("EndDate", value); } } [XmlAttribute("Level")] [Bindable(true)] public string Level { get { return GetColumnValue<string>("Level"); } set { SetColumnValue("Level", value); } } [XmlAttribute("LevelCode")] [Bindable(true)] public string LevelCode { get { return GetColumnValue<string>("LevelCode"); } set { SetColumnValue("LevelCode", value); } } [XmlAttribute("LevelName")] [Bindable(true)] public string LevelName { get { return GetColumnValue<string>("LevelName"); } set { SetColumnValue("LevelName", value); } } [XmlAttribute("Weight")] [Bindable(true)] public int Weight { get { return GetColumnValue<int>("Weight"); } set { SetColumnValue("Weight", value); } } [XmlAttribute("IsReadOnly")] [Bindable(true)] public bool? IsReadOnly { get { return GetColumnValue<bool?>("IsReadOnly"); } set { SetColumnValue("IsReadOnly", value); } } #endregion #region Columns Struct public struct Columns { public static string Id = @"ID"; public static string OrganisationID = @"OrganisationID"; public static string OrganisationCode = @"OrganisationCode"; public static string OrganisationName = @"OrganisationName"; public static string StationID = @"StationID"; public static string StationCode = @"StationCode"; public static string StationName = @"StationName"; public static string OrganisationRoleID = @"OrganisationRoleID"; public static string OrganisationRoleCode = @"OrganisationRoleCode"; public static string OrganisationRoleName = @"OrganisationRoleName"; public static string StartDate = @"StartDate"; public static string EndDate = @"EndDate"; public static string Level = @"Level"; public static string LevelCode = @"LevelCode"; public static string LevelName = @"LevelName"; public static string Weight = @"Weight"; public static string IsReadOnly = @"IsReadOnly"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using Cassandra.Requests; using Cassandra.Serialization; namespace Cassandra { /// <summary> /// A simple <see cref="IStatement"/> implementation built directly from a query string. /// </summary> public class SimpleStatement : RegularStatement { private static readonly Logger Logger = new Logger(typeof(SimpleStatement)); private string _query; private volatile RoutingKey _routingKey; private object[] _routingValues; private string _keyspace; /// <summary> /// Gets the query string. /// </summary> public override string QueryString { get { return _query; } } /// <summary> /// Gets the routing key for the query. /// <para> /// Routing key can be provided using the <see cref="SetRoutingValues"/> method. /// </para> /// </summary> public override RoutingKey RoutingKey { get { if (_routingKey != null) { return _routingKey; } if (_routingValues == null) { return null; } var serializer = Serializer; if (serializer == null) { serializer = Serialization.SerializerManager.Default.GetCurrentSerializer(); Logger.Warning("Calculating routing key before executing is not supported for SimpleStatement " + "instances, using default serializer."); } // Calculate the routing key return RoutingKey.Compose( _routingValues .Select(value => new RoutingKey(serializer.Serialize(value))) .ToArray()); } } /// <summary> /// Returns the keyspace this query operates on, as set using <see cref="SetKeyspace(string)"/> /// <para> /// The keyspace returned is used as a hint for token-aware routing. /// </para> /// </summary> /// <remarks> /// Consider using a <see cref="ISession"/> connected to single keyspace using /// <see cref="ICluster.Connect(string)"/>. /// </remarks> public override string Keyspace { get { return _keyspace; } } /// <summary> /// Creates a new instance of <see cref="SimpleStatement"/> without any query string or parameters. /// </summary> public SimpleStatement() { } /// <summary> /// Creates a new instance of <see cref="SimpleStatement"/> with the provided CQL query. /// </summary> /// <param name="query">The cql query string.</param> public SimpleStatement(string query) { _query = query; } /// <summary> /// Creates a new instance of <see cref="SimpleStatement"/> with the provided CQL query and values provided. /// </summary> /// <param name="query">The cql query string.</param> /// <param name="values">Parameter values required for the execution of <c>query</c>.</param> /// <example> /// Using positional parameters: /// <code> /// const string query = "INSERT INTO users (id, name, email) VALUES (?, ?, ?)"; /// var statement = new SimpleStatement(query, id, name, email); /// </code> /// Using named parameters (using anonymous objects): /// <code> /// const string query = "INSERT INTO users (id, name, email) VALUES (:id, :name, :email)"; /// var statement = new SimpleStatement(query, new { id, name, email } ); /// </code> /// </example> public SimpleStatement(string query, params object[] values) : this(query) { // ReSharper disable once DoNotCallOverridableMethodsInConstructor SetValues(values, Serializer); } /// <summary> /// Creates a new instance of <see cref="SimpleStatement"/> using a dictionary of parameters and a query with /// named parameters. /// </summary> /// <param name="valuesDictionary"> /// A dictionary containing the query parameters values using the parameter name as keys. /// </param> /// <param name="query">The cql query string.</param> /// <remarks> /// This constructor is valid for dynamically-sized named parameters, consider using anonymous types for /// fixed-size named parameters. /// </remarks> /// <example> /// <code> /// const string query = "INSERT INTO users (id, name, email) VALUES (:id, :name, :email)"; /// var parameters = new Dictionary&lt;string, object&gt; /// { /// { "id", id }, /// { "name", name }, /// { "email", email }, /// }; /// var statement = new SimpleStatement(parameters, query); /// </code> /// </example> /// <seealso cref="SimpleStatement(string, object[])"/> public SimpleStatement(IDictionary<string, object> valuesDictionary, string query) { if (valuesDictionary == null) { throw new ArgumentNullException("valuesDictionary"); } _query = query ?? throw new ArgumentNullException("query"); //The order of the keys and values is unspecified, but is guaranteed to be both in the same order. SetParameterNames(valuesDictionary.Keys); base.SetValues(valuesDictionary.Values.ToArray(), Serializer); } /// <summary> /// Set the routing key for this query. <p> This method allows to manually /// provide a routing key for this query. It is thus optional since the routing /// key is only an hint for token aware load balancing policy but is never /// mandatory. </p><p> If the partition key for the query is composite, use the /// <link>#setRoutingKey(ByteBuffer...)</link> method instead to build the /// routing key.</p> /// </summary> /// <param name="routingKeyComponents"> the raw (binary) values to compose to /// obtain the routing key. /// </param> /// <returns>this <c>SimpleStatement</c> object. <see>Query#getRoutingKey</see></returns> public SimpleStatement SetRoutingKey(params RoutingKey[] routingKeyComponents) { _routingKey = RoutingKey.Compose(routingKeyComponents); return this; } /// <summary> /// Sets the partition key values in order to route the query to the correct replicas. /// <para>For simple partition keys, set the partition key value.</para> /// <para>For composite partition keys, set the multiple the partition key values in correct order.</para> /// </summary> public SimpleStatement SetRoutingValues(params object[] keys) { _routingValues = keys; return this; } public SimpleStatement SetQueryString(string queryString) { _query = queryString; return this; } /// <summary> /// Sets the parameter values for the query. /// <para> /// The same amount of values must be provided as parameter markers in the query. /// </para> /// <para> /// Specify the parameter values by the position of the markers in the query or by name, /// using a single instance of an anonymous type, with property names as parameter names. /// </para> /// </summary> [Obsolete("The method Bind() is deprecated, use SimpleStatement constructor parameters to provide query values")] public SimpleStatement Bind(params object[] values) { SetValues(values, Serializer); return this; } [Obsolete("The method BindObject() is deprecated, use SimpleStatement constructor parameters to provide query values")] public SimpleStatement BindObjects(object[] values) { return Bind(values); } /// <summary> /// Sets the keyspace this Statement operates on. The keyspace should only be set when the /// <see cref="IStatement"/> applies to a different keyspace to the logged keyspace of the /// <see cref="ISession"/>. /// </summary> /// <param name="name">The keyspace name.</param> public SimpleStatement SetKeyspace(string name) { _keyspace = name; return this; } internal override IQueryRequest CreateBatchRequest(ISerializer serializer) { // Use the default query options as the individual options of the query will be ignored var options = QueryProtocolOptions.CreateForBatchItem(this); return new QueryRequest(serializer, QueryString, options, IsTracing, null); } internal override void SetValues(object[] values, ISerializer serializer) { if (values != null && values.Length == 1 && Utils.IsAnonymousType(values[0])) { var keyValues = Utils.GetValues(values[0]); SetParameterNames(keyValues.Keys); values = keyValues.Values.ToArray(); } base.SetValues(values, serializer); } private void SetParameterNames(IEnumerable<string> names) { //Force named values to lowercase as identifiers are lowercased in Cassandra QueryValueNames = names.Select(k => k.ToLowerInvariant()).ToList(); } } }
using System; using System.Collections.Generic; /// <summary> /// System.Collections.Generic.ICollection<T>.Clear() /// </summary> public class ICollectionClear { private int c_MINI_STRING_LENGTH = 8; private int c_MAX_STRING_LENGTH = 256; public static int Main(string[] args) { ICollectionClear testObj = new ICollectionClear(); TestLibrary.TestFramework.BeginTestCase("Testing for Methord: System.Collections.Generic.ICollection<T>.Clear())"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("[Netativ]"); retVal = NegTest1() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; const string c_TEST_DESC = "PosTest1: Using List<T> which implemented the Clear method in ICollection<T> and Type is Byte..."; const string c_TEST_ID = "P001"; Byte[] byteValue = new Byte[10]; TestLibrary.Generator.GetBytes(-55, byteValue); List<Byte> list = new List<Byte>(byteValue); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((ICollection<Byte>)list).Clear(); if (list.Count != 0) { string errorDesc = "ICollection.Count is not " + list.Count.ToString() + " as expected: Actual(0)"; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_DESC = "PosTest2: Using List<T> which implemented the Clear method in ICollection<T> and Type is a reference type..."; const string c_TEST_ID = "P002"; String[] strValue = new String[10]; for (int i = 0; i < 10; i++) { strValue[i] = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); } List<String> list = new List<String>(strValue); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((ICollection<String>)list).Clear(); if (list.Count != 0) { string errorDesc = "ICollection.Count is not 0 as expected: Actual(" + list.Count.ToString() + ")"; TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_DESC = "PosTest3: Using List<T> which implemented the Clear method in ICollection<T> and Type is a user-defined type..."; const string c_TEST_ID = "P003"; MyClass[] mcValue = new MyClass[10]; for (int i = 0; i < 10; i++) { mcValue[i] = new MyClass(); } List<MyClass> list = new List<MyClass>(mcValue); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((ICollection<MyClass>)list).Clear(); if (list.Count != 0) { string errorDesc = "ICollection.Count is not 0 as expected: Actual(" + list.Count.ToString() + ")"; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; const string c_TEST_DESC = "PosTest4: Using customer class which implemented the Clear method in ICollection<T> and Type is int..."; const string c_TEST_ID = "P004"; MyCollection<int> myC = new MyCollection<int>(); for (int i = 0; i < 10; i++) { myC.Add(TestLibrary.Generator.GetInt32(-55)); } TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((ICollection<int>)myC).Clear(); if (myC.Count != 0) { string errorDesc = "ICollection.Count is not 0 as expected: Actual(" + myC.Count.ToString() + ")"; TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: Using user-defined type which is readonly"); MyCollection<int> myC = new MyCollection<int>(); myC.isReadOnly = true; try { ((ICollection<int>)myC).Clear(); TestLibrary.TestFramework.LogError("009", "The NotSupportedException was not thrown as expected"); retVal = false; } catch (NotSupportedException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Help Class public class MyCollection<T> : ICollection<T> { public T[] _items; protected int length; public bool isReadOnly = false; public MyCollection() { _items = new T[10]; length = 0; } public T this[int index] { get { // Fllowing trick can reduce the range check by one if ((uint)index >= (uint)length) { throw new ArgumentOutOfRangeException(); } return _items[index]; } } #region ICollection<T> Members public void Add(T item) { if (isReadOnly) { throw new NotSupportedException(); } else { _items[length] = item; length++; } } public void Clear() { if (isReadOnly) { throw new NotSupportedException(); } else { Array.Clear(_items, 0, length); length = 0; } } public bool Contains(T item) { throw new Exception("The method or operation is not implemented."); } public void CopyTo(T[] array, int arrayIndex) { throw new Exception("The method or operation is not implemented."); } public int Count { get { return length; } } public bool IsReadOnly { get { return isReadOnly; } } public bool Remove(T item) { throw new Exception("The method or operation is not implemented."); } #endregion #region IEnumerable<T> Members public IEnumerator<T> GetEnumerator() { throw new Exception("The method or operation is not implemented."); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new Exception("The method or operation is not implemented."); } #endregion } public class MyClass {} #endregion }
using System; using Org.BouncyCastle.Crypto.Parameters; namespace Org.BouncyCastle.Crypto.Engines { /** * The specification for RC5 came from the <code>RC5 Encryption Algorithm</code> * publication in RSA CryptoBytes, Spring of 1995. * <em>http://www.rsasecurity.com/rsalabs/cryptobytes</em>. * <p> * This implementation has a word size of 32 bits.</p> */ public class RC532Engine : IBlockCipher { /* * the number of rounds to perform */ private int _noRounds; /* * the expanded key array of size 2*(rounds + 1) */ private int [] _S; /* * our "magic constants" for 32 32 * * Pw = Odd((e-2) * 2^wordsize) * Qw = Odd((o-2) * 2^wordsize) * * where e is the base of natural logarithms (2.718281828...) * and o is the golden ratio (1.61803398...) */ private static readonly int P32 = unchecked((int) 0xb7e15163); private static readonly int Q32 = unchecked((int) 0x9e3779b9); private bool forEncryption; /** * Create an instance of the RC5 encryption algorithm * and set some defaults */ public RC532Engine() { _noRounds = 12; // the default // _S = null; } public virtual string AlgorithmName { get { return "RC5-32"; } } public virtual bool IsPartialBlockOkay { get { return false; } } public virtual int GetBlockSize() { return 2 * 4; } /** * initialise a RC5-32 cipher. * * @param forEncryption whether or not we are for encryption. * @param parameters the parameters required to set up the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public virtual void Init( bool forEncryption, ICipherParameters parameters) { if (typeof(RC5Parameters).IsInstanceOfType(parameters)) { RC5Parameters p = (RC5Parameters)parameters; _noRounds = p.Rounds; SetKey(p.GetKey()); } else if (typeof(KeyParameter).IsInstanceOfType(parameters)) { KeyParameter p = (KeyParameter)parameters; SetKey(p.GetKey()); } else { throw new ArgumentException("invalid parameter passed to RC532 init - " + parameters.GetType().ToString()); } this.forEncryption = forEncryption; } public virtual int ProcessBlock( byte[] input, int inOff, byte[] output, int outOff) { return (forEncryption) ? EncryptBlock(input, inOff, output, outOff) : DecryptBlock(input, inOff, output, outOff); } public virtual void Reset() { } /** * Re-key the cipher. * * @param key the key to be used */ private void SetKey( byte[] key) { // // KEY EXPANSION: // // There are 3 phases to the key expansion. // // Phase 1: // Copy the secret key K[0...b-1] into an array L[0..c-1] of // c = ceil(b/u), where u = 32/8 in little-endian order. // In other words, we fill up L using u consecutive key bytes // of K. Any unfilled byte positions in L are zeroed. In the // case that b = c = 0, set c = 1 and L[0] = 0. // int[] L = new int[(key.Length + (4 - 1)) / 4]; for (int i = 0; i != key.Length; i++) { L[i / 4] += (key[i] & 0xff) << (8 * (i % 4)); } // // Phase 2: // Initialize S to a particular fixed pseudo-random bit pattern // using an arithmetic progression modulo 2^wordsize determined // by the magic numbers, Pw & Qw. // _S = new int[2*(_noRounds + 1)]; _S[0] = P32; for (int i=1; i < _S.Length; i++) { _S[i] = (_S[i-1] + Q32); } // // Phase 3: // Mix in the user's secret key in 3 passes over the arrays S & L. // The max of the arrays sizes is used as the loop control // int iter; if (L.Length > _S.Length) { iter = 3 * L.Length; } else { iter = 3 * _S.Length; } int A = 0, B = 0; int ii = 0, jj = 0; for (int k = 0; k < iter; k++) { A = _S[ii] = RotateLeft(_S[ii] + A + B, 3); B = L[jj] = RotateLeft( L[jj] + A + B, A+B); ii = (ii+1) % _S.Length; jj = (jj+1) % L.Length; } } /** * Encrypt the given block starting at the given offset and place * the result in the provided buffer starting at the given offset. * * @param in in byte buffer containing data to encrypt * @param inOff offset into src buffer * @param out out buffer where encrypted data is written * @param outOff offset into out buffer */ private int EncryptBlock( byte[] input, int inOff, byte[] outBytes, int outOff) { int A = BytesToWord(input, inOff) + _S[0]; int B = BytesToWord(input, inOff + 4) + _S[1]; for (int i = 1; i <= _noRounds; i++) { A = RotateLeft(A ^ B, B) + _S[2*i]; B = RotateLeft(B ^ A, A) + _S[2*i+1]; } WordToBytes(A, outBytes, outOff); WordToBytes(B, outBytes, outOff + 4); return 2 * 4; } private int DecryptBlock( byte[] input, int inOff, byte[] outBytes, int outOff) { int A = BytesToWord(input, inOff); int B = BytesToWord(input, inOff + 4); for (int i = _noRounds; i >= 1; i--) { B = RotateRight(B - _S[2*i+1], A) ^ A; A = RotateRight(A - _S[2*i], B) ^ B; } WordToBytes(A - _S[0], outBytes, outOff); WordToBytes(B - _S[1], outBytes, outOff + 4); return 2 * 4; } ////////////////////////////////////////////////////////////// // // PRIVATE Helper Methods // ////////////////////////////////////////////////////////////// /** * Perform a left "spin" of the word. The rotation of the given * word <em>x</em> is rotated left by <em>y</em> bits. * Only the <em>lg(32)</em> low-order bits of <em>y</em> * are used to determine the rotation amount. Here it is * assumed that the wordsize used is a power of 2. * * @param x word to rotate * @param y number of bits to rotate % 32 */ private int RotateLeft(int x, int y) { return ((int) ( (uint) (x << (y & (32-1))) | ((uint) x >> (32 - (y & (32-1)))) ) ); } /** * Perform a right "spin" of the word. The rotation of the given * word <em>x</em> is rotated left by <em>y</em> bits. * Only the <em>lg(32)</em> low-order bits of <em>y</em> * are used to determine the rotation amount. Here it is * assumed that the wordsize used is a power of 2. * * @param x word to rotate * @param y number of bits to rotate % 32 */ private int RotateRight(int x, int y) { return ((int) ( ((uint) x >> (y & (32-1))) | (uint) (x << (32 - (y & (32-1)))) ) ); } private int BytesToWord( byte[] src, int srcOff) { return (src[srcOff] & 0xff) | ((src[srcOff + 1] & 0xff) << 8) | ((src[srcOff + 2] & 0xff) << 16) | ((src[srcOff + 3] & 0xff) << 24); } private void WordToBytes( int word, byte[] dst, int dstOff) { dst[dstOff] = (byte)word; dst[dstOff + 1] = (byte)(word >> 8); dst[dstOff + 2] = (byte)(word >> 16); dst[dstOff + 3] = (byte)(word >> 24); } } }
// <copyright file="EdgeOptions.cs" company="Microsoft"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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. // </copyright> using System; using System.Collections.Generic; using System.Globalization; using OpenQA.Selenium.Chromium; namespace OpenQA.Selenium.Edge { /// <summary> /// Class to manage options specific to <see cref="EdgeDriver"/> /// </summary> /// <example> /// <code> /// EdgeOptions options = new EdgeOptions(); /// </code> /// <para></para> /// <para>For use with EdgeDriver:</para> /// <para></para> /// <code> /// EdgeDriver driver = new EdgeDriver(options); /// </code> /// <para></para> /// <para>For use with RemoteWebDriver:</para> /// <para></para> /// <code> /// RemoteWebDriver driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), options.ToCapabilities()); /// </code> /// </example> public class EdgeOptions : ChromiumOptions { private const string BrowserNameValue = "MicrosoftEdge"; private const string UseInPrivateBrowsingCapability = "ms:inPrivate"; private const string ExtensionPathsCapability = "ms:extensionPaths"; private const string StartPageCapability = "ms:startPage"; private static readonly string[] ChromiumCapabilityNames = { "goog:chromeOptions", "se:forceAlwaysMatch", "args", "binary", "extensions", "localState", "prefs", "detach", "debuggerAddress", "excludeSwitches", "minidumpPath", "mobileEmulation", "perfLoggingPrefs", "windowTypes", "w3c"}; private bool useInPrivateBrowsing; private string startPage; private List<string> extensionPaths = new List<string>(); private bool isLegacy; /// <summary> /// Initializes a new instance of the <see cref="EdgeOptions"/> class. /// </summary> public EdgeOptions() : this(true) { } /// <summary> /// Create an EdgeOption for ChromiumEdge /// </summary> /// <param name="isLegacy">Whether to use Legacy Mode. If so, remove all Chromium Capabilities</param> public EdgeOptions(bool isLegacy) : base(BrowserNameValue) { this.isLegacy = isLegacy; if (this.isLegacy) { foreach (string capabilityName in ChromiumCapabilityNames) { this.RemoveKnownCapabilityName(capabilityName); } this.AddKnownCapabilityName(UseInPrivateBrowsingCapability, "UseInPrivateBrowsing property"); this.AddKnownCapabilityName(StartPageCapability, "StartPage property"); this.AddKnownCapabilityName(ExtensionPathsCapability, "AddExtensionPaths method"); } } /// <summary> /// Gets or sets the location of the Edge browser's binary executable file. /// </summary> public new string BinaryLocation { get { if (this.isLegacy) { throw new ArgumentException("BinaryLocation does not exist in Legacy Edge"); } return base.BinaryLocation; } set { if (this.isLegacy) { throw new ArgumentException("BinaryLocation does not exist in Legacy Edge"); } base.BinaryLocation = value; } } /// <summary> /// Gets or sets a value indicating whether the browser should be launched using /// InPrivate browsing. /// </summary> public bool UseInPrivateBrowsing { get { if (!this.isLegacy) { throw new ArgumentException("UseInPrivateBrowsing property does not exist in Chromium Edge"); } return this.useInPrivateBrowsing; } set { if (!this.isLegacy) { throw new ArgumentException("UseInPrivateBrowsing property does not exist in Chromium Edge"); } this.useInPrivateBrowsing = value; } } /// <summary> /// Gets or sets the URL of the page with which the browser will be navigated to on launch. /// </summary> public string StartPage { get { if (!this.isLegacy) { throw new ArgumentException("StartPage property does not exist in Chromium Edge"); } return this.startPage; } set { if (!this.isLegacy) { throw new ArgumentException("StartPage property does not exist in Chromium Edge"); } this.startPage = value; } } /// <summary> /// Adds a path to an extension that is to be used with the Edge driver. /// </summary> /// <param name="extensionPath">The full path and file name of the extension.</param> public void AddExtensionPath(string extensionPath) { if (!this.isLegacy) { throw new ArgumentException("Property does not exist in Chromium Edge", "extensionPath"); } if (string.IsNullOrEmpty(extensionPath)) { throw new ArgumentException("extensionPath must not be null or empty", "extensionPath"); } this.AddExtensionPaths(extensionPath); } /// <summary> /// Adds a list of paths to an extensions that are to be used with the Edge driver. /// </summary> /// <param name="extensionPathsToAdd">An array of full paths with file names of extensions to add.</param> public void AddExtensionPaths(params string[] extensionPathsToAdd) { if (!this.isLegacy) { throw new ArgumentException("Property does not exist in Chromium Edge", "extensionPathsToAdd"); } this.AddExtensionPaths(new List<string>(extensionPathsToAdd)); } /// <summary> /// Adds a list of paths to an extensions that are to be used with the Edge driver. /// </summary> /// <param name="extensionPathsToAdd">An <see cref="IEnumerable{T}"/> of full paths with file names of extensions to add.</param> public void AddExtensionPaths(IEnumerable<string> extensionPathsToAdd) { if (!this.isLegacy) { throw new ArgumentException("Property does not exist in Chromium Edge", "extensionPathsToAdd"); } if (extensionPathsToAdd == null) { throw new ArgumentNullException("extensionPathsToAdd", "extensionPathsToAdd must not be null"); } this.extensionPaths.AddRange(extensionPathsToAdd); } /// <summary> /// Returns DesiredCapabilities for Edge with these options included as /// capabilities. This copies the options. Further changes will not be /// reflected in the returned capabilities. /// </summary> /// <returns>The DesiredCapabilities for Edge with these options.</returns> public override ICapabilities ToCapabilities() { if (!this.isLegacy) { return base.ToCapabilities(); } IWritableCapabilities capabilities = this.GenerateDesiredCapabilities(true); if (this.useInPrivateBrowsing) { capabilities.SetCapability(UseInPrivateBrowsingCapability, true); } if (!string.IsNullOrEmpty(this.startPage)) { capabilities.SetCapability(StartPageCapability, this.startPage); } if (this.extensionPaths.Count > 0) { capabilities.SetCapability(ExtensionPathsCapability, this.extensionPaths); } return capabilities.AsReadOnly(); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="RuntimeIocContainer.cs" company="Rare Crowds Inc"> // Copyright 2012-2013 Rare Crowds, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Globalization; using System.Linq; using Activities; using ActivityProcessor; using AzureUtilities.Storage; using ConcreteDataStore; using ConfigManager; using DataAccessLayer; using DefaultMailTemplates; using DeliveryNetworkUtilities; using Diagnostics; using DynamicAllocation; using Microsoft.Practices.Unity; using PaymentProcessor; using Queuing; using Queuing.Azure; using ScheduledWorkItems; using SqlUtilities.Storage; using Utilities.Diagnostics; using Utilities.Net.Mail; using Utilities.Runtime; using Utilities.Storage; using WorkItems; namespace RuntimeIoc.WorkerRole { /// <summary> /// A singleton implementation for the default UnityContainer. /// This container should not be extensively referenced - usually only from /// service startup code where the root classes are constructed. Subsequent /// construction of the dependency chain should happen silently by Unity. /// </summary> public static class RuntimeIocContainer { /// <summary>singleton lock object.</summary> private static readonly object LockObj = new object(); /// <summary>The one and only UnityContainer object.</summary> private static UnityContainer container; /// <summary>singleton initialization flag.</summary> private static bool initialized = false; /// <summary>Gets or initializes a singleton UnityContainer instance.</summary> /// <value>The unity container.</value> public static IUnityContainer Instance { get { if (!initialized) { lock (LockObj) { if (!initialized) { container = new UnityContainer(); InitializeContainerMappings(container); // Make sure flag initialization isn't reordered by the compiler. System.Threading.Thread.MemoryBarrier(); initialized = true; } } } return container; } } /// <summary> /// Gets a value indicating whether the mail alert logger should be used /// </summary> private static bool MailAlertLogging { get { try { return Config.GetBoolValue("Logging.MailAlerts"); } catch (ArgumentException) { return false; } } } /// <summary>Do runtime intitialization of the UnityContainer.</summary> /// <param name="unityContainer">The unity container.</param> private static void InitializeContainerMappings(UnityContainer unityContainer) { // Default ILoggers unityContainer.RegisterType<ILogger, QuotaLogger>("QuotaLogger"); unityContainer.RegisterType<ILogger, TraceLogger>("TraceLogger"); if (MailAlertLogging) { unityContainer.RegisterType<ILogger, MailAlertLogger>("MailAlertLogger"); } // Default IIndexStoreFactory // TODO: change to AzureSql when available string indexStoreConnectionString = Config.GetValue("Index.ConnectionString"); unityContainer.RegisterType<IIndexStoreFactory, SqlIndexStoreFactory>(new InjectionConstructor(indexStoreConnectionString)); // Default IEntityStoreFactory string entityStoreConnectionString = Config.GetValue("Entity.ConnectionString"); unityContainer.RegisterType<IEntityStoreFactory, AzureEntityStoreFactory>(new InjectionConstructor(entityStoreConnectionString)); // Default IBlobStoreFactory unityContainer.RegisterType<IBlobStoreFactory, AzureBlobStoreFactory>(new InjectionConstructor(entityStoreConnectionString)); // Default IKeyRuleFactory unityContainer.RegisterType<IKeyRuleFactory, KeyRuleFactory>(); // Default IStorageKeyFactory unityContainer.RegisterType<IStorageKeyFactory, AzureStorageKeyFactory>(); // Default IEntityRepository unityContainer.RegisterType<IEntityRepository, ConcreteEntityRepository>(); // Default IUserAccessStoreFactory unityContainer.RegisterType<IUserAccessStoreFactory, SqlUserAccessStoreFactory>(new InjectionConstructor(indexStoreConnectionString)); // Default IUserAccessRepository unityContainer.RegisterType<IUserAccessRepository, ConcreteUserAccessRepository>(); // Default ICategorizedQueue unityContainer.RegisterType<ICategorizedQueue, CategorizedAzureQueue>(); // Default IPersistentDictionary Factories unityContainer.RegisterType<IPersistentDictionaryFactory, MemoryPersistentDictionaryFactory>("MemoryDictionaryFactory"); var persistentDictionaryBlobConnectionString = Config.GetValue("Dictionary.Blob.ConnectionString"); unityContainer.RegisterType<IPersistentDictionaryFactory, CloudBlobDictionaryFactory>("CloudBlobDictionaryFactory", new InjectionConstructor(persistentDictionaryBlobConnectionString)); var persistentDictionarySqlConnectionString = Config.GetValue("Dictionary.Sql.ConnectionString"); unityContainer.RegisterType<IPersistentDictionaryFactory, SqlDictionaryFactory>("SqlDictionaryFactory", new InjectionConstructor(persistentDictionarySqlConnectionString)); // Default IQueuer unityContainer.RegisterType<IQueuer, Queue>(); // Default IDequeuer unityContainer.RegisterType<IDequeuer, Queue>(); // Default IWorkItemProcessor unityContainer.RegisterType<IWorkItemProcessor, ActivityWorkItemProcessor>(); // Mail Configuration Provider unityContainer.RegisterType<IMailTemplateProvider, EmbeddedMailTemplateProvider>(); // Billing Payment Processor var paymentProcessorSecretKey = TryGetValue("PaymentProcessor.ApiSecretKey", "nonfunctionaldefaultkey"); unityContainer.RegisterType<IPaymentProcessor, StripePaymentProcessor>(new InjectionConstructor(paymentProcessorSecretKey)); // Activity Providers unityContainer.RegisterType<IActivityProvider, EntityActivities.ActivityProvider>("EntityActivities"); unityContainer.RegisterType<IActivityProvider, DynamicAllocationActivities.ActivityProvider>("DynamicAllocationActivities"); unityContainer.RegisterType<IActivityProvider, AppNexusActivities.ActivityProvider>("AppNexusActivities"); unityContainer.RegisterType<IActivityProvider, GoogleDfpActivities.ActivityProvider>("GoogleDfpActivities"); unityContainer.RegisterType<IActivityProvider, ReportingActivities.ActivityProvider>("ReportingActivities"); unityContainer.RegisterType<IActivityProvider, BillingActivities.ActivityProvider>("BillingActivities"); // Scheduled Activity Request Source Providers unityContainer.RegisterType<IScheduledWorkItemSourceProvider, DynamicAllocationActivityDispatchers.ScheduledActivitySourceProvider>("DynamicAllocationActivityDispatchers"); unityContainer.RegisterType<IScheduledWorkItemSourceProvider, DeliveryNetworkActivityDispatchers.ScheduledActivitySourceProvider>("DeliveryNetworkActivityDispatchers"); // Default WorkItemSubmitter unityContainer.RegisterType<IRunner, WorkItemSubmitter>("WorkItemSubmitter"); // Delivery Network Client Factories unityContainer.RegisterType<IDeliveryNetworkClientFactory, GenericDeliveryNetworkClientFactory<AppNexusClient.IAppNexusApiClient, AppNexusClient.AppNexusApiClient>>("AppNexusApiClient"); unityContainer.RegisterType<IDeliveryNetworkClientFactory, GenericDeliveryNetworkClientFactory<GoogleDfpClient.IGoogleDfpClient, GoogleDfpClient.GoogleDfpWrapper>>("GoogleDfpClient"); // Measure Source Providers unityContainer.RegisterType<IMeasureSourceProvider, AppNexusActivities.Measures.AppNexusLegacyMeasureSourceProvider>("AppNexusLegacyMeasures"); unityContainer.RegisterType<IMeasureSourceProvider, AppNexusActivities.Measures.AppNexusMeasureSourceProvider>("AppNexusMeasures"); unityContainer.RegisterType<IMeasureSourceProvider, GoogleDfpActivities.Measures.DfpMeasureSourceProvider>("GoogleDfpMeasures"); // QueueProcessors var activityRuntimeCategories = (Enum.GetValues(typeof(ActivityRuntimeCategory)) as ActivityRuntimeCategory[]) .Select(c => c.ToString()) .ToArray(); var queueCategories = Config.GetValue("QueueProcessor.Categories"); var queues = queueCategories.Split(new[] { '|' }); foreach (var queue in queues) { var categories = queue.Split(new[] { ',' }) .Select(c => int.Parse(c.Trim(), CultureInfo.InvariantCulture)) .Select(i => activityRuntimeCategories[i]) .ToArray(); var queueName = "QueueProcessor-" + Guid.NewGuid().ToString("N"); unityContainer.RegisterType<IRunner, QueueProcessor>(queueName, new InjectionProperty("Categories", categories)); } } /// <summary>Get a string value from config. Return default if not found.</summary> /// <param name="configKey">The config key.</param> /// <param name="defaultValue">The default value if not found.</param> /// <returns>The config value.</returns> private static string TryGetValue(string configKey, string defaultValue) { try { return Config.GetValue(configKey); } catch (ArgumentException) { return defaultValue; } } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Handlers { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public class OperatorHandlers_HighLevel { [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(ObjectAllocationOperator) )] private static void Handle_ObjectAllocationOperator( PhaseExecution.NotificationContext nc ) { ObjectAllocationOperator op = (ObjectAllocationOperator)nc.CurrentOperator; TypeSystemForCodeTransformation ts = nc.TypeSystem; WellKnownMethods wkm = ts.WellKnownMethods; MethodRepresentation mdAllocateObject = wkm.TypeSystemManager_AllocateObject; MethodRepresentation md = op.Method; TypeRepresentation td = op.Type; CallOperator call; Expression[] rhs; Expression exStringLen = null; // // Is this a special object? // for(var td2 = td; td2 != null; td2 = td2.Extends) { if(ts.GarbageCollectionExtensions.ContainsKey( td2 )) { mdAllocateObject = wkm.TypeSystemManager_AllocateObjectWithExtensions; break; } } if(md != null) { if(md == wkm.StringImpl_ctor_char_int) { exStringLen = op.SecondArgument; } else if(md == wkm.StringImpl_ctor_charArray) { TemporaryVariableExpression tmp = nc.CurrentCFG.AllocateTemporary( ts.WellKnownTypes.System_Int32, null ); op.AddOperatorBefore( ArrayLengthOperator.New( op.DebugInfo, tmp, op.FirstArgument ) ); exStringLen = tmp; } else if(md == wkm.StringImpl_ctor_charArray_int_int) { exStringLen = op.ThirdArgument; } } // // Special case to allocate strings built out of characters. // if(exStringLen != null) { if(ts.IsReferenceCountingType( ts.WellKnownTypes.System_String ) && !ts.ShouldExcludeMethodFromReferenceCounting( nc.CurrentMethod )) { mdAllocateObject = wkm.StringImpl_FastAllocateReferenceCountingString; } else { mdAllocateObject = wkm.StringImpl_FastAllocateString; } rhs = ts.AddTypePointerToArgumentsOfStaticMethod( mdAllocateObject, exStringLen ); call = StaticCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, mdAllocateObject, op.Results, rhs ); op.SubstituteWithOperator( call, Operator.SubstitutionFlags.CopyAnnotations ); call.AddAnnotation( NotNullAnnotation.Create( ts ) ); } else { if( ts.IsReferenceCountingGarbageCollectionEnabled && md != wkm.TypeSystemManager_AllocateObjectWithExtensions && ts.IsReferenceCountingType( td ) && !ts.ShouldExcludeMethodFromReferenceCounting( nc.CurrentMethod )) { mdAllocateObject = wkm.TypeSystemManager_AllocateReferenceCountingObject; } TemporaryVariableExpression typeSystemManagerEx = FetchTypeSystemManager( nc, op ); rhs = new Expression[] { typeSystemManagerEx, ts.GetVTable( op.Type ) }; call = InstanceCallOperator.New( op.DebugInfo, CallOperator.CallKind.Virtual, mdAllocateObject, op.Results, rhs, true ); op.SubstituteWithOperator( call, Operator.SubstitutionFlags.CopyAnnotations ); call.AddAnnotation( NotNullAnnotation.Create( ts ) ); var mdFinalizer = td.FindDestructor(); if(mdFinalizer != null && mdFinalizer.OwnerType != ts.WellKnownTypes.System_Object) { var mdHelper = wkm.Finalizer_Allocate; var rhsHelper = ts.AddTypePointerToArgumentsOfStaticMethod( mdHelper, call.FirstResult ); var callHelper = StaticCallOperator.New( call.DebugInfo, CallOperator.CallKind.Direct, mdHelper, rhsHelper ); call.AddOperatorAfter( callHelper ); } } nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(ArrayAllocationOperator) )] private static void Handle_ArrayAllocationOperator( PhaseExecution.NotificationContext nc ) { ArrayAllocationOperator op = (ArrayAllocationOperator)nc.CurrentOperator; TypeSystemForCodeTransformation ts = nc.TypeSystem; TemporaryVariableExpression typeSystemManagerEx = FetchTypeSystemManager( nc, op ); MethodRepresentation mdAllocateArray = ts.WellKnownMethods.TypeSystemManager_AllocateArray; CallOperator call; Expression[] rhs; Expression exLen = op.FirstArgument; if( ts.IsReferenceCountingGarbageCollectionEnabled && ts.IsReferenceCountingType( ts.WellKnownTypes.System_Array ) && !ts.ShouldExcludeMethodFromReferenceCounting( nc.CurrentMethod )) { mdAllocateArray = ts.WellKnownMethods.TypeSystemManager_AllocateReferenceCountingArray; } rhs = new Expression[] { typeSystemManagerEx, ts.GetVTable( op.Type ), exLen }; call = InstanceCallOperator.New( op.DebugInfo, CallOperator.CallKind.Virtual, mdAllocateArray, op.Results, rhs, true ); op.SubstituteWithOperator( call, Operator.SubstitutionFlags.CopyAnnotations ); call.AddAnnotation( NotNullAnnotation.Create( ts ) ); ConstantExpression exLenConst = exLen as ConstantExpression; if(exLenConst != null && exLenConst.IsValueInteger) { ulong val; exLenConst.GetAsRawUlong( out val ); call.AddAnnotation( FixedLengthArrayAnnotation.Create( ts, (int)val ) ); } nc.MarkAsModified(); } [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(ArrayLengthOperator) )] private static void Handle_ArrayLengthOperator( PhaseExecution.NotificationContext nc ) { ArrayLengthOperator op = (ArrayLengthOperator)nc.CurrentOperator; TypeSystemForCodeTransformation typeSystem = nc.TypeSystem; InstanceCallOperator opNew = InstanceCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, typeSystem.WellKnownMethods.ArrayImpl_get_Length, op.Results, new Expression[] { op.FirstArgument }, true ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(ThrowControlOperator) )] private static void Handle_ThrowControlOperator( PhaseExecution.NotificationContext nc ) { ThrowControlOperator op = (ThrowControlOperator)nc.CurrentOperator; TypeSystemForCodeTransformation typeSystem = nc.TypeSystem; TemporaryVariableExpression typeSystemManagerEx = FetchTypeSystemManager( nc, op ); MethodRepresentation mdThrow = typeSystem.WellKnownMethods.TypeSystemManager_Throw; Debugging.DebugInfo debugInfo = op.DebugInfo; CallOperator call; Expression[] rhs; rhs = new Expression[] { typeSystemManagerEx, op.FirstArgument }; call = InstanceCallOperator.New( debugInfo, CallOperator.CallKind.Virtual, mdThrow, rhs, true ); call.CopyAnnotations( op ); op.AddOperatorBefore( call ); op.SubstituteWithOperator( DeadControlOperator.New( debugInfo ), Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(RethrowControlOperator) )] private static void Handle_RethrowControlOperator( PhaseExecution.NotificationContext nc ) { RethrowControlOperator op = (RethrowControlOperator)nc.CurrentOperator; TypeSystemForCodeTransformation typeSystem = nc.TypeSystem; TemporaryVariableExpression typeSystemManagerEx = FetchTypeSystemManager( nc, op ); MethodRepresentation mdRethrow = typeSystem.WellKnownMethods.TypeSystemManager_Rethrow; Debugging.DebugInfo debugInfo = op.DebugInfo; CallOperator call; Expression[] rhs; rhs = new Expression[] { typeSystemManagerEx }; call = InstanceCallOperator.New( debugInfo, CallOperator.CallKind.Virtual, mdRethrow, rhs, true ); call.CopyAnnotations( op ); op.AddOperatorBefore( call ); op.SubstituteWithOperator( DeadControlOperator.New( debugInfo ), Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(FetchExceptionOperator) )] private static void Handle_FetchExceptionOperator( PhaseExecution.NotificationContext nc ) { FetchExceptionOperator op = (FetchExceptionOperator)nc.CurrentOperator; TypeSystemForCodeTransformation typeSystem = nc.TypeSystem; MethodRepresentation md = typeSystem.WellKnownMethods.ThreadImpl_GetCurrentException; CallOperator call; Expression[] rhs; rhs = typeSystem.AddTypePointerToArgumentsOfStaticMethod( md ); call = StaticCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, md, op.Results, rhs ); op.SubstituteWithOperator( call, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(CastOperator) )] private static void Handle_CastOperator( PhaseExecution.NotificationContext nc ) { WellKnownMethods wkm = nc.TypeSystem.WellKnownMethods; CastOperator op = (CastOperator)nc.CurrentOperator; Handle_GenericCastOperator( nc, op.Type, wkm.TypeSystemManager_CastToSealedType, wkm.TypeSystemManager_CastToType, wkm.TypeSystemManager_CastToInterface ); } [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(IsInstanceOperator) )] private static void Handle_IsInstanceOperator( PhaseExecution.NotificationContext nc ) { WellKnownMethods wkm = nc.TypeSystem.WellKnownMethods; IsInstanceOperator op = (IsInstanceOperator)nc.CurrentOperator; Handle_GenericCastOperator( nc, op.Type, wkm.TypeSystemManager_CastToSealedTypeNoThrow, wkm.TypeSystemManager_CastToTypeNoThrow, wkm.TypeSystemManager_CastToInterfaceNoThrow ); } private static void Handle_GenericCastOperator( PhaseExecution.NotificationContext nc , TypeRepresentation target , MethodRepresentation mdSealedType , MethodRepresentation mdType , MethodRepresentation mdInterface ) { TypeSystemForCodeTransformation typeSystem = nc.TypeSystem; Operator op = nc.CurrentOperator; Expression src = op.FirstArgument; if(target.CanBeAssignedFrom( src.Type, null )) { var opNew = SingleAssignmentOperator.New( op.DebugInfo, op.FirstResult, src ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); } else { MethodRepresentation md; Expression[] rhs; CallOperator call; if(target is InterfaceTypeRepresentation) { md = mdInterface; } else if(target is ArrayReferenceTypeRepresentation) { md = mdType; } else { TypeRepresentation targetSealed; if(typeSystem.IsSealedType( target, out targetSealed )) { target = targetSealed; md = mdSealedType; } else { md = mdType; } } rhs = typeSystem.AddTypePointerToArgumentsOfStaticMethod( md, src, typeSystem.GetVTable( target ) ); call = StaticCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, md, op.Results, rhs ); op.SubstituteWithOperator( call, Operator.SubstitutionFlags.Default ); } nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(LoadStaticFieldAddressOperator) )] private static void Handle_LoadStaticFieldAddressOperator( PhaseExecution.NotificationContext nc ) { LoadStaticFieldAddressOperator op = (LoadStaticFieldAddressOperator)nc.CurrentOperator; TypeSystemForCodeTransformation ts = nc.TypeSystem; Expression exRoot = ts.GenerateRootAccessor( op ); InstanceFieldRepresentation fd = ts.AddStaticFieldToGlobalRoot( (StaticFieldRepresentation)op.Field ); // // 'exRoot' will never be null, so we don't need to add null checks. // LoadInstanceFieldAddressOperator opNew = LoadInstanceFieldAddressOperator.New( op.DebugInfo, fd, op.FirstResult, exRoot, false ); opNew.AddAnnotation( NotNullAnnotation.Create( ts ) ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(LoadStaticFieldOperator) )] private static void Handle_LoadStaticFieldOperator( PhaseExecution.NotificationContext nc ) { LoadStaticFieldOperator op = (LoadStaticFieldOperator)nc.CurrentOperator; TypeSystemForCodeTransformation typeSystem = nc.TypeSystem; Expression exRoot = typeSystem.GenerateRootAccessor( op ); InstanceFieldRepresentation fd = typeSystem.AddStaticFieldToGlobalRoot( (StaticFieldRepresentation)op.Field ); // // 'exRoot' will never be null, so we don't need to check for it. // LoadInstanceFieldOperator opNew = LoadInstanceFieldOperator.New( op.DebugInfo, fd, op.FirstResult, exRoot, false ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(StoreStaticFieldOperator) )] private static void Handle_StoreStaticFieldOperator( PhaseExecution.NotificationContext nc ) { StoreStaticFieldOperator op = (StoreStaticFieldOperator)nc.CurrentOperator; TypeSystemForCodeTransformation typeSystem = nc.TypeSystem; Expression exRoot = typeSystem.GenerateRootAccessor( op ); InstanceFieldRepresentation fd = typeSystem.AddStaticFieldToGlobalRoot( (StaticFieldRepresentation)op.Field ); // // 'exRoot' will never be null, so we don't need to check for it. // StoreInstanceFieldOperator opNew = StoreInstanceFieldOperator.New( op.DebugInfo, fd, exRoot, op.FirstArgument, false ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(MkRefAnyOperator) )] private static void Handle_MkRefAnyOperator( PhaseExecution.NotificationContext nc ) { MkRefAnyOperator op = (MkRefAnyOperator)nc.CurrentOperator; VariableExpression lhs = op.FirstResult; TypeRepresentation target = lhs.Type; FieldRepresentation fdValue = target.FindField( "Value" ); FieldRepresentation fdType = target.FindField( "Type" ); op.AddOperatorBefore ( StoreInstanceFieldOperator.New( op.DebugInfo, fdValue, lhs, op.FirstArgument , true ) ); op.SubstituteWithOperator( StoreInstanceFieldOperator.New( op.DebugInfo, fdType , lhs, nc.TypeSystem.GetVTable( op.Type ), true ), Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(RefAnyValOperator) )] private static void Handle_RefAnyValOperator( PhaseExecution.NotificationContext nc ) { RefAnyValOperator op = (RefAnyValOperator)nc.CurrentOperator; TypeRepresentation target = op.FirstArgument.Type; FieldRepresentation fdValue = target.FindField( "Value" ); // // TODO: Check that target.Type and op.Type are the same. // LoadInstanceFieldOperator opNew = LoadInstanceFieldOperator.New( op.DebugInfo, fdValue, op.FirstResult, op.FirstArgument, true ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(RefAnyTypeOperator) )] private static void Handle_RefAnyTypeOperator( PhaseExecution.NotificationContext nc ) { RefAnyTypeOperator op = (RefAnyTypeOperator)nc.CurrentOperator; TypeRepresentation target = op.FirstArgument.Type; FieldRepresentation fdType = target.FindField( "Type" ); LoadInstanceFieldOperator opNew = LoadInstanceFieldOperator.New( op.DebugInfo, fdType, op.FirstResult, op.FirstArgument, true ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(BoxOperator) )] private static void Handle_BoxOperator( PhaseExecution.NotificationContext nc ) { BoxOperator op = (BoxOperator)nc.CurrentOperator; var lhs = op.FirstResult; // // Try to detect the pattern of many methods in generic types: // // private int FindEntry( TKey key ) // { // if(key == null) // { // // 'null' is always a reference and if TKey is a value type, the compiler has to generate a boxing operation. // But boxed values are also non-null, so we can delete the boxing and substitute a constant for the outcome of the compare. // { var cfg = nc.CurrentCFG; var use = cfg.FindSingleUse( lhs ); if(use != null) { bool fNullOnRight; if(use.IsBinaryOperationAgainstZeroValue( out fNullOnRight ) == lhs) { if(use is CompareAndSetOperator) { var use2 = (CompareAndSetOperator)use; bool fSubstitute = false; int val = 0; switch(use2.Condition) { case CompareAndSetOperator.ActionCondition.EQ: fSubstitute = true; val = 0; break; case CompareAndSetOperator.ActionCondition.NE: fSubstitute = true; val = 1; break; } if(fSubstitute) { op.Delete(); use2.SubstituteWithOperator( SingleAssignmentOperator.New( use2.DebugInfo, use2.FirstResult, cfg.TypeSystem.CreateConstant( val ) ), Operator.SubstitutionFlags.Default ); nc.StopScan(); return; } } if(use is CompareConditionalControlOperator) { var use2 = (CompareConditionalControlOperator)use; bool fSubstitute = false; BasicBlock target = null; switch(use2.Condition) { case CompareAndSetOperator.ActionCondition.EQ: fSubstitute = true; target = use2.TargetBranchNotTaken; break; case CompareAndSetOperator.ActionCondition.NE: fSubstitute = true; target = use2.TargetBranchTaken; break; } if(fSubstitute) { op.Delete(); use2.SubstituteWithOperator( UnconditionalControlOperator.New( use2.DebugInfo, target ), Operator.SubstitutionFlags.Default ); nc.StopScan(); return; } } } } } op.AddOperatorBefore(ObjectAllocationOperator.New(op.DebugInfo, op.Type.UnderlyingType, lhs)); // Store requires a boxed type, but this argument may have been retyped. Retype it if necessary. VariableExpression boxedValue = lhs; if (boxedValue.Type != op.Type) { boxedValue = nc.AllocateTemporary(op.Type); op.AddOperatorBefore(SingleAssignmentOperator.New(op.DebugInfo, boxedValue, lhs)); } var storeOp = StoreInstanceFieldOperator.New(op.DebugInfo, op.Type.Fields[0], boxedValue, op.FirstArgument, false); op.SubstituteWithOperator(storeOp, Operator.SubstitutionFlags.Default); nc.MarkAsModified(); } [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(UnboxOperator) )] private static void Handle_UnboxOperator( PhaseExecution.NotificationContext nc ) { UnboxOperator op = (UnboxOperator)nc.CurrentOperator; // Load requires a boxed type, but this argument may have been retyped. Retype it if necessary. Expression boxedValue = op.FirstArgument; if (boxedValue.Type != op.Type) { VariableExpression newValue = nc.AllocateTemporary(op.Type); op.AddOperatorBefore(SingleAssignmentOperator.New(op.DebugInfo, newValue, op.FirstArgument)); boxedValue = newValue; } var loadOp = LoadInstanceFieldAddressOperator.New( op.DebugInfo, op.Type.Fields[0], op.FirstResult, boxedValue, fNullCheck: true); op.SubstituteWithOperator(loadOp, Operator.SubstitutionFlags.Default); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(BinaryOperator) )] private static void Handle_RemoveTypeConversions( PhaseExecution.NotificationContext nc ) { BinaryOperator op = (BinaryOperator)nc.CurrentOperator; ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; VariableExpression exLhs = op.FirstResult; ConstantExpression exConstLeft = op.FirstArgument as ConstantExpression; ConstantExpression exConstRight = op.SecondArgument as ConstantExpression; ConversionOperator use = IsArgumentAsTypeConversion( cfg, exLhs , false ); ConversionOperator defLeft = IsArgumentAsTypeConversion( cfg, op.FirstArgument , true ); ConversionOperator defRight = IsArgumentAsTypeConversion( cfg, op.SecondArgument, true ); if(defLeft != null && defRight != null) { Expression leftPre = defLeft .FirstArgument; Expression leftPost = defLeft .FirstResult; Expression rightPre = defRight.FirstArgument; Expression rightPost = defRight.FirstResult; uint leftPreSize = leftPre .Type.UnderlyingType.Size; uint leftPostSize = leftPost .Type.UnderlyingType.Size; uint rightPreSize = rightPre .Type.UnderlyingType.Size; uint rightPostSize = rightPost.Type.UnderlyingType.Size; if(leftPreSize == leftPostSize && defLeft .SignificantSize == leftPostSize && rightPreSize == rightPostSize && defRight.SignificantSize == rightPostSize ) { // // The extend ops are no-ops, most likely due to the requirement of loading an int/long into the evaluation stack. // // Shortcut the binary operator to use the pre-extension values. // ShortcutBinaryOperation( nc, op, op.Signed, exLhs, leftPre, rightPre ); return; } if(leftPreSize == 4 && leftPostSize == 8 && rightPreSize == 4 && rightPostSize == 8 ) { // // This is a 32 -> 64 bit extension. Can we remove the 64 bit operation? // if(use != null && use.SignificantSize == 4) { // // It's a 32->64->32 sequence of operations. // if(op.CheckOverflow == false) { switch(op.Alu) { case BinaryOperator.ALU.ADD: case BinaryOperator.ALU.SUB: case BinaryOperator.ALU.MUL: case BinaryOperator.ALU.AND: case BinaryOperator.ALU.OR : ShortcutBinaryOperation( nc, op, use.FirstResult.Type.IsSigned, use.FirstResult, leftPre, rightPre ); use.Delete(); nc.StopScan(); return; } } } else { // // It's a 32x32->64 sequence of operations. // if(op.CheckOverflow == false) { switch(op.Alu) { case BinaryOperator.ALU.MUL: ShortcutBinaryOperation( nc, op, exLhs.Type.IsSigned, exLhs, leftPre, rightPre ); return; } } } } } if(defLeft != null && exConstRight != null) { Expression leftPre = defLeft.FirstArgument; Expression leftPost = defLeft.FirstResult; uint leftPreSize = leftPre .Type.UnderlyingType.Size; uint leftPostSize = leftPost .Type.UnderlyingType.Size; uint rightSize = exConstRight.Type.UnderlyingType.Size; if(leftPreSize == leftPostSize && defLeft.SignificantSize == leftPostSize) { // // The extend ops are no-ops, most likely due to the requirement of loading an int/long into the evaluation stack. // // Shortcut the binary operator to use the pre-extension values. // ShortcutBinaryOperation( nc, op, op.Signed, exLhs, leftPre, exConstRight ); return; } if(leftPreSize == 4 && leftPostSize == 8 && rightSize == 8) { ulong val; if(exConstRight.GetAsRawUlong( out val )) { ConstantExpression exConstRightShort = nc.TypeSystem.CreateConstant( leftPre.Type, ConstantExpression.ConvertToType( leftPre.Type, val ) ); // // This is a 32 -> 64 bit extension. Can we remove the 64 bit operation? // if(use != null && use.SignificantSize == 4) { // // It's a 32->64->32 sequence of operations. // if(op.CheckOverflow == false) { switch(op.Alu) { case BinaryOperator.ALU.ADD: case BinaryOperator.ALU.SUB: case BinaryOperator.ALU.MUL: case BinaryOperator.ALU.AND: case BinaryOperator.ALU.OR : ShortcutBinaryOperation( nc, op, use.FirstResult.Type.IsSigned, use.FirstResult, leftPre, exConstRightShort ); use.Delete(); nc.StopScan(); return; } } } else { ulong valPost; exConstRightShort.GetAsRawUlong( out valPost ); if(valPost == val) { // // It's a 32x32->64 sequence of operations. // if(op.CheckOverflow == false) { switch(op.Alu) { case BinaryOperator.ALU.MUL: ShortcutBinaryOperation( nc, op, exLhs.Type.IsSigned, exLhs, leftPre, exConstRightShort ); return; } } } } } } } if(exConstLeft != null && defRight != null) { Expression rightPre = defRight.FirstArgument; Expression rightPost = defRight.FirstResult; uint rightPreSize = rightPre .Type.UnderlyingType.Size; uint rightPostSize = rightPost .Type.UnderlyingType.Size; uint leftSize = exConstLeft.Type.UnderlyingType.Size; if(rightPreSize == rightPostSize && defRight.SignificantSize == rightPostSize) { // // The extend ops are no-ops, most likely due to the requirement of loading an int/long into the evaluation stack. // // Shortcut the binary operator to use the pre-extension values. // ShortcutBinaryOperation( nc, op, op.Signed, exLhs, exConstLeft, rightPre ); return; } if(rightPreSize == 4 && rightPostSize == 8 && leftSize == 8) { ulong val; if(exConstRight.GetAsRawUlong( out val )) { ConstantExpression exConstLeftShort = nc.TypeSystem.CreateConstant( rightPre.Type, ConstantExpression.ConvertToType( rightPre.Type, val ) ); // // This is a 32 -> 64 bit extension. Can we remove the 64 bit operation? // if(use != null && use.SignificantSize == 4) { // // It's a 32->64->32 sequence of operations. // if(op.CheckOverflow == false) { switch(op.Alu) { case BinaryOperator.ALU.ADD: case BinaryOperator.ALU.SUB: case BinaryOperator.ALU.MUL: case BinaryOperator.ALU.AND: case BinaryOperator.ALU.OR : ShortcutBinaryOperation( nc, op, use.FirstResult.Type.IsSigned, use.FirstResult, exConstLeftShort, rightPre ); use.Delete(); nc.StopScan(); return; } } } else { ulong valPost; exConstLeftShort.GetAsRawUlong( out valPost ); if(valPost == val) { // // It's a 32x32->64 sequence of operations. // if(op.CheckOverflow == false) { switch(op.Alu) { case BinaryOperator.ALU.MUL: ShortcutBinaryOperation( nc, op, exLhs.Type.IsSigned, exLhs, exConstLeftShort, rightPre ); return; } } } } } } } } private static ConversionOperator IsArgumentAsTypeConversion( ControlFlowGraphStateForCodeTransformation cfg , Expression ex , bool fGetDefinition ) { if(ex is VariableExpression) { Operator[][] useChains = cfg.DataFlow_UseChains; Operator[][] defChains = cfg.DataFlow_DefinitionChains; int idx = ex.SpanningTreeIndex; Operator[] uses = useChains[idx]; Operator[] defs = defChains[idx]; if(uses.Length == 1 && defs.Length == 1 ) { Operator res = fGetDefinition ? defs[0] : uses[0]; return res as ConversionOperator; } } return null; } private static void ShortcutBinaryOperation( PhaseExecution.NotificationContext nc , BinaryOperator op , bool fSigned , VariableExpression lhs , Expression left , Expression right ) { BinaryOperator opNew = BinaryOperator.New( op.DebugInfo, op.Alu, fSigned, op.CheckOverflow, lhs, left, right ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// private static TemporaryVariableExpression FetchTypeSystemManager( PhaseExecution.NotificationContext nc , Operator op ) { TypeSystemForCodeTransformation typeSystem = nc.TypeSystem; MethodRepresentation mdTypeSystemManager = typeSystem.WellKnownMethods.TypeSystemManager_get_Instance; TemporaryVariableExpression typeSystemManagerEx = nc.AllocateTemporary( mdTypeSystemManager.ReturnType ); CallOperator call; Expression[] rhs; rhs = typeSystem.AddTypePointerToArgumentsOfStaticMethod( mdTypeSystemManager ); call = StaticCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, mdTypeSystemManager, VariableExpression.ToArray( typeSystemManagerEx ), rhs ); op.AddOperatorBefore( call ); nc.MarkAsModified(); return typeSystemManagerEx; } } }
/* * 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 OpenSim.Region.ScriptEngine.Yengine; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Reflection.Emit; namespace OpenSim.Region.ScriptEngine.Yengine { public delegate void ScriptEventHandler(XMRInstAbstract instance); /* * This object represents the output of the compilation. * Once the compilation is complete, its contents should be * considered 'read-only', so it can be shared among multiple * instances of the script. * * It gets created by ScriptCodeGen. * It gets used by XMRInstance to create script instances. */ public class ScriptObjCode { public string sourceHash; // source text hash code public XMRInstArSizes glblSizes = new XMRInstArSizes(); // number of global variables of various types public string[] stateNames; // convert state number to corresponding string public ScriptEventHandler[,] scriptEventHandlerTable; // entrypoints to all event handler functions // 1st subscript = state code number (0=default) // 2nd subscript = event code number // null entry means no handler defined for that state,event public Dictionary<string, TokenDeclSDType> sdObjTypesName; // all script-defined types by name public TokenDeclSDType[] sdObjTypesIndx; // all script-defined types by sdTypeIndex public Dictionary<Type, string> sdDelTypes; // all script-defined delegates (including anonymous) public Dictionary<string, DynamicMethod> dynamicMethods; // all dyanmic methods public Dictionary<string, KeyValuePair<int, ScriptSrcLoc>[]> scriptSrcLocss; // method,iloffset -> source file,line,posn public int refCount; // used by engine to keep track of number of // instances that are using this object code public Dictionary<string, Dictionary<int, string>> globalVarNames = new Dictionary<string, Dictionary<int, string>>(); /** * @brief Fill in ScriptObjCode from an YEngine object file. * 'objFileReader' is a serialized form of the CIL code we generated * 'asmFileWriter' is where we write the disassembly to (or null if not wanted) * 'srcFileWriter' is where we write the decompilation to (or null if not wanted) * Throws an exception if there is any error (theoretically). */ public ScriptObjCode(BinaryReader objFileReader, TextWriter asmFileWriter, TextWriter srcFileWriter) { // Check version number to make sure we know how to process file contents. char[] ocm = objFileReader.ReadChars(ScriptCodeGen.OBJECT_CODE_MAGIC.Length); if(new String(ocm) != ScriptCodeGen.OBJECT_CODE_MAGIC) throw new CVVMismatchException("Not an Yengine object file (bad magic)"); int cvv = objFileReader.ReadInt32(); if(cvv != ScriptCodeGen.COMPILED_VERSION_VALUE) throw new CVVMismatchException( "Object version is " + cvv.ToString() + " but accept only " + ScriptCodeGen.COMPILED_VERSION_VALUE.ToString()); // Fill in simple parts of scriptObjCode object. sourceHash = objFileReader.ReadString(); glblSizes.ReadFromFile(objFileReader); int nStates = objFileReader.ReadInt32(); stateNames = new string[nStates]; for(int i = 0; i < nStates; i++) { stateNames[i] = objFileReader.ReadString(); if(asmFileWriter != null) asmFileWriter.WriteLine(" state[{0}] = {1}", i, stateNames[i]); } if(asmFileWriter != null) glblSizes.WriteAsmFile(asmFileWriter, "numGbl"); string gblName; while((gblName = objFileReader.ReadString()) != "") { string gblType = objFileReader.ReadString(); int gblIndex = objFileReader.ReadInt32(); Dictionary<int, string> names; if(!globalVarNames.TryGetValue(gblType, out names)) { names = new Dictionary<int, string>(); globalVarNames.Add(gblType, names); } names.Add(gblIndex, gblName); if(asmFileWriter != null) asmFileWriter.WriteLine(" {0} = {1}[{2}]", gblName, gblType, gblIndex); } // Read in script-defined types. sdObjTypesName = new Dictionary<string, TokenDeclSDType>(); sdDelTypes = new Dictionary<Type, string>(); int maxIndex = -1; while((gblName = objFileReader.ReadString()) != "") { TokenDeclSDType sdt = TokenDeclSDType.ReadFromFile(sdObjTypesName, gblName, objFileReader, asmFileWriter); sdObjTypesName.Add(gblName, sdt); if(maxIndex < sdt.sdTypeIndex) maxIndex = sdt.sdTypeIndex; if(sdt is TokenDeclSDTypeDelegate) sdDelTypes.Add(sdt.GetSysType(), gblName); } sdObjTypesIndx = new TokenDeclSDType[maxIndex + 1]; foreach(TokenDeclSDType sdt in sdObjTypesName.Values) sdObjTypesIndx[sdt.sdTypeIndex] = sdt; // Now fill in the methods (the hard part). scriptEventHandlerTable = new ScriptEventHandler[nStates, (int)ScriptEventCode.Size]; dynamicMethods = new Dictionary<string, DynamicMethod>(); scriptSrcLocss = new Dictionary<string, KeyValuePair<int, ScriptSrcLoc>[]>(); ObjectTokens objectTokens = null; if(asmFileWriter != null) objectTokens = new OTDisassemble(this, asmFileWriter); else if(srcFileWriter != null) objectTokens = new OTDecompile(this, srcFileWriter); try { ScriptObjWriter.CreateObjCode(sdObjTypesName, objFileReader, this, objectTokens); } finally { if(objectTokens != null) objectTokens.Close(); } // We enter all script event handler methods in the ScriptEventHandler table. // They are named: <statename> <eventname> foreach(KeyValuePair<string, DynamicMethod> kvp in dynamicMethods) { string methName = kvp.Key; int i = methName.IndexOf(' '); if(i < 0) continue; string stateName = methName.Substring(0, i); string eventName = methName.Substring(++i); int stateCode; for(stateCode = stateNames.Length; --stateCode >= 0;) if(stateNames[stateCode] == stateName) break; int eventCode = (int)Enum.Parse(typeof(ScriptEventCode), eventName); scriptEventHandlerTable[stateCode, eventCode] = (ScriptEventHandler)kvp.Value.CreateDelegate(typeof(ScriptEventHandler)); } // Fill in all script-defined class vtables. foreach(TokenDeclSDType sdt in sdObjTypesIndx) { if((sdt != null) && (sdt is TokenDeclSDTypeClass)) { TokenDeclSDTypeClass sdtc = (TokenDeclSDTypeClass)sdt; sdtc.FillVTables(this); } } } /** * @brief Called once for every method found in objFileReader file. * It enters the method in the ScriptObjCode object table so it can be called. */ public void EndMethod(DynamicMethod method, Dictionary<int, ScriptSrcLoc> srcLocs) { // Save method object code pointer. dynamicMethods.Add(method.Name, method); // Build and sort iloffset -> source code location array. int n = srcLocs.Count; KeyValuePair<int, ScriptSrcLoc>[] srcLocArray = new KeyValuePair<int, ScriptSrcLoc>[n]; n = 0; foreach(KeyValuePair<int, ScriptSrcLoc> kvp in srcLocs) srcLocArray[n++] = kvp; Array.Sort(srcLocArray, endMethodWrapper); // Save sorted array. scriptSrcLocss.Add(method.Name, srcLocArray); } /** * @brief Called once for every method found in objFileReader file. * It enters the method in the ScriptObjCode object table so it can be called. */ private static EndMethodWrapper endMethodWrapper = new EndMethodWrapper(); private class EndMethodWrapper: System.Collections.IComparer { public int Compare(object x, object y) { KeyValuePair<int, ScriptSrcLoc> kvpx = (KeyValuePair<int, ScriptSrcLoc>)x; KeyValuePair<int, ScriptSrcLoc> kvpy = (KeyValuePair<int, ScriptSrcLoc>)y; return kvpx.Key - kvpy.Key; } } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel.Dispatcher { using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Diagnostics; using System.Threading; using System.Transactions; using System.ServiceModel.Diagnostics.Application; using System.Runtime.Diagnostics; using System.Security; class ImmutableDispatchRuntime { readonly AuthenticationBehavior authenticationBehavior; readonly AuthorizationBehavior authorizationBehavior; readonly int correlationCount; readonly ConcurrencyBehavior concurrency; readonly IDemuxer demuxer; readonly ErrorBehavior error; readonly bool enableFaults; readonly bool ignoreTransactionFlow; readonly bool impersonateOnSerializingReply; readonly IInputSessionShutdown[] inputSessionShutdownHandlers; readonly InstanceBehavior instance; readonly bool isOnServer; readonly bool manualAddressing; readonly IDispatchMessageInspector[] messageInspectors; readonly int parameterInspectorCorrelationOffset; readonly IRequestReplyCorrelator requestReplyCorrelator; readonly SecurityImpersonationBehavior securityImpersonation; readonly TerminatingOperationBehavior terminate; readonly ThreadBehavior thread; readonly TransactionBehavior transaction; readonly bool validateMustUnderstand; readonly bool receiveContextEnabledChannel; readonly bool sendAsynchronously; readonly bool requireClaimsPrincipalOnOperationContext; readonly MessageRpcProcessor processMessage1; readonly MessageRpcProcessor processMessage11; readonly MessageRpcProcessor processMessage2; readonly MessageRpcProcessor processMessage3; readonly MessageRpcProcessor processMessage31; readonly MessageRpcProcessor processMessage4; readonly MessageRpcProcessor processMessage41; readonly MessageRpcProcessor processMessage5; readonly MessageRpcProcessor processMessage6; readonly MessageRpcProcessor processMessage7; readonly MessageRpcProcessor processMessage8; readonly MessageRpcProcessor processMessage9; readonly MessageRpcProcessor processMessageCleanup; readonly MessageRpcProcessor processMessageCleanupError; static AsyncCallback onFinalizeCorrelationCompleted = Fx.ThunkCallback(new AsyncCallback(OnFinalizeCorrelationCompletedCallback)); static AsyncCallback onReplyCompleted = Fx.ThunkCallback(new AsyncCallback(OnReplyCompletedCallback)); bool didTraceProcessMessage1 = false; bool didTraceProcessMessage2 = false; bool didTraceProcessMessage3 = false; bool didTraceProcessMessage31 = false; bool didTraceProcessMessage4 = false; bool didTraceProcessMessage41 = false; internal ImmutableDispatchRuntime(DispatchRuntime dispatch) { this.authenticationBehavior = AuthenticationBehavior.TryCreate(dispatch); this.authorizationBehavior = AuthorizationBehavior.TryCreate(dispatch); this.concurrency = new ConcurrencyBehavior(dispatch); this.error = new ErrorBehavior(dispatch.ChannelDispatcher); this.enableFaults = dispatch.EnableFaults; this.inputSessionShutdownHandlers = EmptyArray<IInputSessionShutdown>.ToArray(dispatch.InputSessionShutdownHandlers); this.instance = new InstanceBehavior(dispatch, this); this.isOnServer = dispatch.IsOnServer; this.manualAddressing = dispatch.ManualAddressing; this.messageInspectors = EmptyArray<IDispatchMessageInspector>.ToArray(dispatch.MessageInspectors); this.requestReplyCorrelator = new RequestReplyCorrelator(); this.securityImpersonation = SecurityImpersonationBehavior.CreateIfNecessary(dispatch); this.requireClaimsPrincipalOnOperationContext = dispatch.RequireClaimsPrincipalOnOperationContext; this.impersonateOnSerializingReply = dispatch.ImpersonateOnSerializingReply; this.terminate = TerminatingOperationBehavior.CreateIfNecessary(dispatch); this.thread = new ThreadBehavior(dispatch); this.validateMustUnderstand = dispatch.ValidateMustUnderstand; this.ignoreTransactionFlow = dispatch.IgnoreTransactionMessageProperty; this.transaction = TransactionBehavior.CreateIfNeeded(dispatch); this.receiveContextEnabledChannel = dispatch.ChannelDispatcher.ReceiveContextEnabled; this.sendAsynchronously = dispatch.ChannelDispatcher.SendAsynchronously; this.parameterInspectorCorrelationOffset = (dispatch.MessageInspectors.Count + dispatch.MaxCallContextInitializers); this.correlationCount = this.parameterInspectorCorrelationOffset + dispatch.MaxParameterInspectors; DispatchOperationRuntime unhandled = new DispatchOperationRuntime(dispatch.UnhandledDispatchOperation, this); if (dispatch.OperationSelector == null) { ActionDemuxer demuxer = new ActionDemuxer(); for (int i = 0; i < dispatch.Operations.Count; i++) { DispatchOperation operation = dispatch.Operations[i]; DispatchOperationRuntime operationRuntime = new DispatchOperationRuntime(operation, this); demuxer.Add(operation.Action, operationRuntime); } demuxer.SetUnhandled(unhandled); this.demuxer = demuxer; } else { CustomDemuxer demuxer = new CustomDemuxer(dispatch.OperationSelector); for (int i = 0; i < dispatch.Operations.Count; i++) { DispatchOperation operation = dispatch.Operations[i]; DispatchOperationRuntime operationRuntime = new DispatchOperationRuntime(operation, this); demuxer.Add(operation.Name, operationRuntime); } demuxer.SetUnhandled(unhandled); this.demuxer = demuxer; } this.processMessage1 = new MessageRpcProcessor(this.ProcessMessage1); this.processMessage11 = new MessageRpcProcessor(this.ProcessMessage11); this.processMessage2 = new MessageRpcProcessor(this.ProcessMessage2); this.processMessage3 = new MessageRpcProcessor(this.ProcessMessage3); this.processMessage31 = new MessageRpcProcessor(this.ProcessMessage31); this.processMessage4 = new MessageRpcProcessor(this.ProcessMessage4); this.processMessage41 = new MessageRpcProcessor(this.ProcessMessage41); this.processMessage5 = new MessageRpcProcessor(this.ProcessMessage5); this.processMessage6 = new MessageRpcProcessor(this.ProcessMessage6); this.processMessage7 = new MessageRpcProcessor(this.ProcessMessage7); this.processMessage8 = new MessageRpcProcessor(this.ProcessMessage8); this.processMessage9 = new MessageRpcProcessor(this.ProcessMessage9); this.processMessageCleanup = new MessageRpcProcessor(this.ProcessMessageCleanup); this.processMessageCleanupError = new MessageRpcProcessor(this.ProcessMessageCleanupError); } internal int CallContextCorrelationOffset { get { return this.messageInspectors.Length; } } internal int CorrelationCount { get { return this.correlationCount; } } internal bool EnableFaults { get { return this.enableFaults; } } internal InstanceBehavior InstanceBehavior { get { return this.instance; } } internal bool IsImpersonationEnabledOnSerializingReply { get { return this.impersonateOnSerializingReply; } } internal bool RequireClaimsPrincipalOnOperationContext { get { return this.requireClaimsPrincipalOnOperationContext; } } internal bool ManualAddressing { get { return this.manualAddressing; } } internal int MessageInspectorCorrelationOffset { get { return 0; } } internal int ParameterInspectorCorrelationOffset { get { return this.parameterInspectorCorrelationOffset; } } internal IRequestReplyCorrelator RequestReplyCorrelator { get { return this.requestReplyCorrelator; } } internal SecurityImpersonationBehavior SecurityImpersonation { get { return this.securityImpersonation; } } internal bool ValidateMustUnderstand { get { return validateMustUnderstand; } } internal ErrorBehavior ErrorBehavior { get { return this.error; } } bool AcquireDynamicInstanceContext(ref MessageRpc rpc) { if (rpc.InstanceContext.QuotaThrottle != null) { return AcquireDynamicInstanceContextCore(ref rpc); } else { return true; } } bool AcquireDynamicInstanceContextCore(ref MessageRpc rpc) { bool success = rpc.InstanceContext.QuotaThrottle.Acquire(rpc.Pause()); if (success) { rpc.UnPause(); } return success; } internal void AfterReceiveRequest(ref MessageRpc rpc) { if (this.messageInspectors.Length > 0) { AfterReceiveRequestCore(ref rpc); } } internal void AfterReceiveRequestCore(ref MessageRpc rpc) { int offset = this.MessageInspectorCorrelationOffset; try { for (int i = 0; i < this.messageInspectors.Length; i++) { rpc.Correlation[offset + i] = this.messageInspectors[i].AfterReceiveRequest(ref rpc.Request, (IClientChannel)rpc.Channel.Proxy, rpc.InstanceContext); if (TD.MessageInspectorAfterReceiveInvokedIsEnabled()) { TD.MessageInspectorAfterReceiveInvoked(rpc.EventTraceActivity, this.messageInspectors[i].GetType().FullName); } } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (ErrorBehavior.ShouldRethrowExceptionAsIs(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } } void BeforeSendReply(ref MessageRpc rpc, ref Exception exception, ref bool thereIsAnUnhandledException) { if (this.messageInspectors.Length > 0) { BeforeSendReplyCore(ref rpc, ref exception, ref thereIsAnUnhandledException); } } internal void BeforeSendReplyCore(ref MessageRpc rpc, ref Exception exception, ref bool thereIsAnUnhandledException) { int offset = this.MessageInspectorCorrelationOffset; for (int i = 0; i < this.messageInspectors.Length; i++) { try { Message originalReply = rpc.Reply; Message reply = originalReply; this.messageInspectors[i].BeforeSendReply(ref reply, rpc.Correlation[offset + i]); if (TD.MessageInspectorBeforeSendInvokedIsEnabled()) { TD.MessageInspectorBeforeSendInvoked(rpc.EventTraceActivity, this.messageInspectors[i].GetType().FullName); } if ((reply == null) && (originalReply != null)) { string message = SR.GetString(SR.SFxNullReplyFromExtension2, this.messageInspectors[i].GetType().ToString(), (rpc.Operation.Name ?? "")); ErrorBehavior.ThrowAndCatch(new InvalidOperationException(message)); } rpc.Reply = reply; } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (!ErrorBehavior.ShouldRethrowExceptionAsIs(e)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } if (exception == null) { exception = e; } thereIsAnUnhandledException = (!this.error.HandleError(e)) || thereIsAnUnhandledException; } } } void FinalizeCorrelation(ref MessageRpc rpc) { Message reply = rpc.Reply; if (reply != null && rpc.Error == null) { if (rpc.transaction != null && rpc.transaction.Current != null && rpc.transaction.Current.TransactionInformation.Status != TransactionStatus.Active) { return; } CorrelationCallbackMessageProperty callback; if (CorrelationCallbackMessageProperty.TryGet(reply, out callback)) { if (callback.IsFullyDefined) { try { rpc.RequestContextThrewOnReply = true; rpc.CorrelationCallback = callback; rpc.Reply = rpc.CorrelationCallback.FinalizeCorrelation(reply, rpc.ReplyTimeoutHelper.RemainingTime()); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (!this.error.HandleError(e)) { rpc.CorrelationCallback = null; rpc.CanSendReply = false; } } } else { rpc.CorrelationCallback = new RpcCorrelationCallbackMessageProperty(callback, this, ref rpc); reply.Properties[CorrelationCallbackMessageProperty.Name] = rpc.CorrelationCallback; } } } } void BeginFinalizeCorrelation(ref MessageRpc rpc) { Message reply = rpc.Reply; if (reply != null && rpc.Error == null) { if (rpc.transaction != null && rpc.transaction.Current != null && rpc.transaction.Current.TransactionInformation.Status != TransactionStatus.Active) { return; } CorrelationCallbackMessageProperty callback; if (CorrelationCallbackMessageProperty.TryGet(reply, out callback)) { if (callback.IsFullyDefined) { bool success = false; try { rpc.RequestContextThrewOnReply = true; rpc.CorrelationCallback = callback; IResumeMessageRpc resume = rpc.Pause(); rpc.AsyncResult = rpc.CorrelationCallback.BeginFinalizeCorrelation(reply, rpc.ReplyTimeoutHelper.RemainingTime(), onFinalizeCorrelationCompleted, resume); success = true; if (rpc.AsyncResult.CompletedSynchronously) { rpc.UnPause(); } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (!this.error.HandleError(e)) { rpc.CorrelationCallback = null; rpc.CanSendReply = false; } } finally { if (!success) { rpc.UnPause(); } } } else { rpc.CorrelationCallback = new RpcCorrelationCallbackMessageProperty(callback, this, ref rpc); reply.Properties[CorrelationCallbackMessageProperty.Name] = rpc.CorrelationCallback; } } } } void Reply(ref MessageRpc rpc) { rpc.RequestContextThrewOnReply = true; rpc.SuccessfullySendReply = false; try { rpc.RequestContext.Reply(rpc.Reply, rpc.ReplyTimeoutHelper.RemainingTime()); rpc.RequestContextThrewOnReply = false; rpc.SuccessfullySendReply = true; if (TD.DispatchMessageStopIsEnabled()) { TD.DispatchMessageStop(rpc.EventTraceActivity); } } catch (CommunicationException e) { this.error.HandleError(e); } catch (TimeoutException e) { this.error.HandleError(e); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (DiagnosticUtility.ShouldTraceError) { TraceUtility.TraceEvent(TraceEventType.Error, TraceCode.ServiceOperationExceptionOnReply, SR.GetString(SR.TraceCodeServiceOperationExceptionOnReply), this, e); } if (!this.error.HandleError(e)) { rpc.RequestContextThrewOnReply = true; rpc.CanSendReply = false; } } } void BeginReply(ref MessageRpc rpc) { bool success = false; try { IResumeMessageRpc resume = rpc.Pause(); rpc.AsyncResult = rpc.RequestContext.BeginReply(rpc.Reply, rpc.ReplyTimeoutHelper.RemainingTime(), onReplyCompleted, resume); success = true; if (rpc.AsyncResult.CompletedSynchronously) { rpc.UnPause(); } } catch (CommunicationException e) { this.error.HandleError(e); } catch (TimeoutException e) { this.error.HandleError(e); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (DiagnosticUtility.ShouldTraceError) { TraceUtility.TraceEvent(System.Diagnostics.TraceEventType.Error, TraceCode.ServiceOperationExceptionOnReply, SR.GetString(SR.TraceCodeServiceOperationExceptionOnReply), this, e); } if (!this.error.HandleError(e)) { rpc.RequestContextThrewOnReply = true; rpc.CanSendReply = false; } } finally { if (!success) { rpc.UnPause(); } } } internal bool Dispatch(ref MessageRpc rpc, bool isOperationContextSet) { rpc.ErrorProcessor = this.processMessage8; rpc.NextProcessor = this.processMessage1; return rpc.Process(isOperationContextSet); } void EndFinalizeCorrelation(ref MessageRpc rpc) { try { rpc.Reply = rpc.CorrelationCallback.EndFinalizeCorrelation(rpc.AsyncResult); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (!this.error.HandleError(e)) { rpc.CanSendReply = false; } } } bool EndReply(ref MessageRpc rpc) { bool success = false; try { rpc.RequestContext.EndReply(rpc.AsyncResult); rpc.RequestContextThrewOnReply = false; success = true; if (TD.DispatchMessageStopIsEnabled()) { TD.DispatchMessageStop(rpc.EventTraceActivity); } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.error.HandleError(e); } return success; } internal void InputSessionDoneReceiving(ServiceChannel channel) { if (this.inputSessionShutdownHandlers.Length > 0) { this.InputSessionDoneReceivingCore(channel); } } void InputSessionDoneReceivingCore(ServiceChannel channel) { IDuplexContextChannel proxy = channel.Proxy as IDuplexContextChannel; if (proxy != null) { IInputSessionShutdown[] handlers = this.inputSessionShutdownHandlers; try { for (int i = 0; i < handlers.Length; i++) { handlers[i].DoneReceiving(proxy); } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (!this.error.HandleError(e)) { proxy.Abort(); } } } } internal bool IsConcurrent(ref MessageRpc rpc) { return this.concurrency.IsConcurrent(ref rpc); } internal void InputSessionFaulted(ServiceChannel channel) { if (this.inputSessionShutdownHandlers.Length > 0) { this.InputSessionFaultedCore(channel); } } void InputSessionFaultedCore(ServiceChannel channel) { IDuplexContextChannel proxy = channel.Proxy as IDuplexContextChannel; if (proxy != null) { IInputSessionShutdown[] handlers = this.inputSessionShutdownHandlers; try { for (int i = 0; i < handlers.Length; i++) { handlers[i].ChannelFaulted(proxy); } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (!this.error.HandleError(e)) { proxy.Abort(); } } } } static internal void GotDynamicInstanceContext(object state) { bool alreadyResumedNoLock; ((IResumeMessageRpc)state).Resume(out alreadyResumedNoLock); if (alreadyResumedNoLock) { Fx.Assert("GotDynamicInstanceContext more than once for same call."); } } void AddMessageProperties(Message message, OperationContext context, ServiceChannel replyChannel) { if (context.InternalServiceChannel == replyChannel) { if (context.HasOutgoingMessageHeaders) { message.Headers.CopyHeadersFrom(context.OutgoingMessageHeaders); } if (context.HasOutgoingMessageProperties) { message.Properties.MergeProperties(context.OutgoingMessageProperties); } } } static void OnFinalizeCorrelationCompletedCallback(IAsyncResult result) { if (result.CompletedSynchronously) { return; } IResumeMessageRpc resume = result.AsyncState as IResumeMessageRpc; if (resume == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SFxInvalidAsyncResultState0)); } resume.Resume(result); } static void OnReplyCompletedCallback(IAsyncResult result) { if (result.CompletedSynchronously) { return; } IResumeMessageRpc resume = result.AsyncState as IResumeMessageRpc; if (resume == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SFxInvalidAsyncResultState0)); } resume.Resume(result); } void PrepareReply(ref MessageRpc rpc) { RequestContext context = rpc.OperationContext.RequestContext; Exception exception = null; bool thereIsAnUnhandledException = false; if (!rpc.Operation.IsOneWay) { if (DiagnosticUtility.ShouldTraceWarning) { // If a service both returns null and sets RequestContext null, that // means they handled it (either by calling Close or Reply manually). // These traces catch accidents, where you accidentally return null, // or you accidentally close the context so we can't return your message. if ((rpc.Reply == null) && (context != null)) { TraceUtility.TraceEvent(System.Diagnostics.TraceEventType.Warning, TraceCode.ServiceOperationMissingReply, SR.GetString(SR.TraceCodeServiceOperationMissingReply, rpc.Operation.Name ?? String.Empty), null, null); } else if ((context == null) && (rpc.Reply != null)) { TraceUtility.TraceEvent(System.Diagnostics.TraceEventType.Warning, TraceCode.ServiceOperationMissingReplyContext, SR.GetString(SR.TraceCodeServiceOperationMissingReplyContext, rpc.Operation.Name ?? String.Empty), null, null); } } if ((context != null) && (rpc.Reply != null)) { try { rpc.CanSendReply = PrepareAndAddressReply(ref rpc); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } thereIsAnUnhandledException = (!this.error.HandleError(e)) || thereIsAnUnhandledException; exception = e; } } } this.BeforeSendReply(ref rpc, ref exception, ref thereIsAnUnhandledException); if (rpc.Operation.IsOneWay) { rpc.CanSendReply = false; } if (!rpc.Operation.IsOneWay && (context != null) && (rpc.Reply != null)) { if (exception != null) { // We don't call ProvideFault again, since we have already passed the // point where SFx addresses the reply, and it is reasonable for // ProvideFault to expect that SFx will address the reply. Instead // we always just do 'internal server error' processing. rpc.Error = exception; this.error.ProvideOnlyFaultOfLastResort(ref rpc); try { rpc.CanSendReply = PrepareAndAddressReply(ref rpc); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.error.HandleError(e); } } } else if ((exception != null) && thereIsAnUnhandledException) { rpc.Abort(); } } bool PrepareAndAddressReply(ref MessageRpc rpc) { bool canSendReply = true; if (!this.manualAddressing) { if (!object.ReferenceEquals(rpc.RequestID, null)) { System.ServiceModel.Channels.RequestReplyCorrelator.PrepareReply(rpc.Reply, rpc.RequestID); } if (!rpc.Channel.HasSession) { canSendReply = System.ServiceModel.Channels.RequestReplyCorrelator.AddressReply(rpc.Reply, rpc.ReplyToInfo); } } AddMessageProperties(rpc.Reply, rpc.OperationContext, rpc.Channel); if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled && rpc.EventTraceActivity != null) { rpc.Reply.Properties[EventTraceActivity.Name] = rpc.EventTraceActivity; } return canSendReply; } internal DispatchOperationRuntime GetOperation(ref Message message) { return this.demuxer.GetOperation(ref message); } internal void ProcessMessage1(ref MessageRpc rpc) { rpc.NextProcessor = this.processMessage11; if (this.receiveContextEnabledChannel) { ReceiveContextRPCFacet.CreateIfRequired(this, ref rpc); } if (!rpc.IsPaused) { this.ProcessMessage11(ref rpc); } else if (this.isOnServer && DiagnosticUtility.ShouldTraceInformation && !this.didTraceProcessMessage1) { this.didTraceProcessMessage1 = true; TraceUtility.TraceEvent( TraceEventType.Information, TraceCode.MessageProcessingPaused, SR.GetString(SR.TraceCodeProcessMessage31Paused, rpc.Channel.DispatchRuntime.EndpointDispatcher.ContractName, rpc.Channel.DispatchRuntime.EndpointDispatcher.EndpointAddress)); } } internal void ProcessMessage11(ref MessageRpc rpc) { rpc.NextProcessor = this.processMessage2; if (rpc.Operation.IsOneWay) { rpc.RequestContext.Reply(null); rpc.OperationContext.RequestContext = null; } else { if (!rpc.Channel.IsReplyChannel && ((object)rpc.RequestID == null) && (rpc.Operation.Action != MessageHeaders.WildcardAction)) { CommunicationException error = new CommunicationException(SR.GetString(SR.SFxOneWayMessageToTwoWayMethod0)); throw TraceUtility.ThrowHelperError(error, rpc.Request); } if (!this.manualAddressing) { EndpointAddress replyTo = rpc.ReplyToInfo.ReplyTo; if (replyTo != null && replyTo.IsNone && rpc.Channel.IsReplyChannel) { CommunicationException error = new CommunicationException(SR.GetString(SR.SFxRequestReplyNone)); throw TraceUtility.ThrowHelperError(error, rpc.Request); } if (this.isOnServer) { EndpointAddress remoteAddress = rpc.Channel.RemoteAddress; if ((remoteAddress != null) && !remoteAddress.IsAnonymous) { MessageHeaders headers = rpc.Request.Headers; Uri remoteUri = remoteAddress.Uri; if ((replyTo != null) && !replyTo.IsAnonymous && (remoteUri != replyTo.Uri)) { string text = SR.GetString(SR.SFxRequestHasInvalidReplyToOnServer, replyTo.Uri, remoteUri); Exception error = new InvalidOperationException(text); throw TraceUtility.ThrowHelperError(error, rpc.Request); } EndpointAddress faultTo = headers.FaultTo; if ((faultTo != null) && !faultTo.IsAnonymous && (remoteUri != faultTo.Uri)) { string text = SR.GetString(SR.SFxRequestHasInvalidFaultToOnServer, faultTo.Uri, remoteUri); Exception error = new InvalidOperationException(text); throw TraceUtility.ThrowHelperError(error, rpc.Request); } if (rpc.RequestVersion.Addressing == AddressingVersion.WSAddressingAugust2004) { EndpointAddress from = headers.From; if ((from != null) && !from.IsAnonymous && (remoteUri != from.Uri)) { string text = SR.GetString(SR.SFxRequestHasInvalidFromOnServer, from.Uri, remoteUri); Exception error = new InvalidOperationException(text); throw TraceUtility.ThrowHelperError(error, rpc.Request); } } } } } } if (this.concurrency.IsConcurrent(ref rpc)) { rpc.Channel.IncrementActivity(); rpc.SuccessfullyIncrementedActivity = true; } if (this.authenticationBehavior != null) { this.authenticationBehavior.Authenticate(ref rpc); } if (this.authorizationBehavior != null) { this.authorizationBehavior.Authorize(ref rpc); } this.instance.EnsureInstanceContext(ref rpc); this.TransferChannelFromPendingList(ref rpc); this.AcquireDynamicInstanceContext(ref rpc); if (!rpc.IsPaused) { this.ProcessMessage2(ref rpc); } } void ProcessMessage2(ref MessageRpc rpc) { rpc.NextProcessor = this.processMessage3; this.AfterReceiveRequest(ref rpc); if (!this.ignoreTransactionFlow) { // Transactions need to have the context in the message rpc.TransactionMessageProperty = TransactionMessageProperty.TryGet(rpc.Request); } this.concurrency.LockInstance(ref rpc); if (!rpc.IsPaused) { this.ProcessMessage3(ref rpc); } else if (this.isOnServer && DiagnosticUtility.ShouldTraceInformation && !this.didTraceProcessMessage2) { this.didTraceProcessMessage2 = true; TraceUtility.TraceEvent( TraceEventType.Information, TraceCode.MessageProcessingPaused, SR.GetString(SR.TraceCodeProcessMessage2Paused, rpc.Channel.DispatchRuntime.EndpointDispatcher.ContractName, rpc.Channel.DispatchRuntime.EndpointDispatcher.EndpointAddress)); } } void ProcessMessage3(ref MessageRpc rpc) { rpc.NextProcessor = this.processMessage31; rpc.SuccessfullyLockedInstance = true; // This also needs to happen after LockInstance, in case // we are using an AutoComplete=false transaction. if (this.transaction != null) { this.transaction.ResolveTransaction(ref rpc); if (rpc.Operation.TransactionRequired) { this.transaction.SetCurrent(ref rpc); } } if (!rpc.IsPaused) { this.ProcessMessage31(ref rpc); } else if (this.isOnServer && DiagnosticUtility.ShouldTraceInformation && !this.didTraceProcessMessage3) { this.didTraceProcessMessage3 = true; TraceUtility.TraceEvent( TraceEventType.Information, TraceCode.MessageProcessingPaused, SR.GetString(SR.TraceCodeProcessMessage3Paused, rpc.Channel.DispatchRuntime.EndpointDispatcher.ContractName, rpc.Channel.DispatchRuntime.EndpointDispatcher.EndpointAddress)); } } void ProcessMessage31(ref MessageRpc rpc) { rpc.NextProcessor = this.processMessage4; if (this.transaction != null) { if (rpc.Operation.TransactionRequired) { ReceiveContextRPCFacet receiveContext = rpc.ReceiveContext; if (receiveContext != null) { rpc.ReceiveContext = null; receiveContext.Complete(this, ref rpc, TimeSpan.MaxValue, rpc.Transaction.Current); } } } if (!rpc.IsPaused) { this.ProcessMessage4(ref rpc); } else if (this.isOnServer && DiagnosticUtility.ShouldTraceInformation && !this.didTraceProcessMessage31) { this.didTraceProcessMessage31 = true; TraceUtility.TraceEvent( TraceEventType.Information, TraceCode.MessageProcessingPaused, SR.GetString(SR.TraceCodeProcessMessage31Paused, rpc.Channel.DispatchRuntime.EndpointDispatcher.ContractName, rpc.Channel.DispatchRuntime.EndpointDispatcher.EndpointAddress)); } } void ProcessMessage4(ref MessageRpc rpc) { rpc.NextProcessor = this.processMessage41; try { this.thread.BindThread(ref rpc); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(e.Message, e); } if (!rpc.IsPaused) { this.ProcessMessage41(ref rpc); } else if (this.isOnServer && DiagnosticUtility.ShouldTraceInformation && !this.didTraceProcessMessage4) { this.didTraceProcessMessage4 = true; TraceUtility.TraceEvent( TraceEventType.Information, TraceCode.MessageProcessingPaused, SR.GetString(SR.TraceCodeProcessMessage4Paused, rpc.Channel.DispatchRuntime.EndpointDispatcher.ContractName, rpc.Channel.DispatchRuntime.EndpointDispatcher.EndpointAddress)); } } void ProcessMessage41(ref MessageRpc rpc) { rpc.NextProcessor = this.processMessage5; // This needs to happen after LockInstance--LockInstance guarantees // in-order delivery, so we can't receive the next message until we // have acquired the lock. // // This also needs to happen after BindThread, since EricZ believes // that running on UI thread should guarantee in-order delivery if // the SynchronizationContext is single threaded. // Note: for IManualConcurrencyOperationInvoker, the invoke assumes full control over pumping. if (this.concurrency.IsConcurrent(ref rpc) && !(rpc.Operation.Invoker is IManualConcurrencyOperationInvoker)) { rpc.EnsureReceive(); } this.instance.EnsureServiceInstance(ref rpc); if (!rpc.IsPaused) { this.ProcessMessage5(ref rpc); } else if (this.isOnServer && DiagnosticUtility.ShouldTraceInformation && !this.didTraceProcessMessage41) { this.didTraceProcessMessage41 = true; TraceUtility.TraceEvent( TraceEventType.Information, TraceCode.MessageProcessingPaused, SR.GetString(SR.TraceCodeProcessMessage4Paused, rpc.Channel.DispatchRuntime.EndpointDispatcher.ContractName, rpc.Channel.DispatchRuntime.EndpointDispatcher.EndpointAddress)); } } void ProcessMessage5(ref MessageRpc rpc) { rpc.NextProcessor = this.processMessage6; try { bool success = false; try { if (!rpc.Operation.IsSynchronous) { // If async call completes in [....], it tells us through the gate below rpc.PrepareInvokeContinueGate(); } if (this.transaction != null) { this.transaction.InitializeCallContext(ref rpc); } SetActivityIdOnThread(ref rpc); rpc.Operation.InvokeBegin(ref rpc); success = true; } finally { try { try { if (this.transaction != null) { this.transaction.ClearCallContext(ref rpc); } } finally { if (!rpc.Operation.IsSynchronous && rpc.IsPaused) { // Check if the callback produced the async result and set it back on the RPC on this stack // and proceed only if the gate was signaled by the callback and completed synchronously if (rpc.UnlockInvokeContinueGate(out rpc.AsyncResult)) { rpc.UnPause(); } } } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (success && (rpc.Operation.IsSynchronous || !rpc.IsPaused)) { throw; } this.error.HandleError(e); } } } catch { // This catch clause forces ClearCallContext to run prior to stackwalks exiting this frame. throw; } // Proceed if rpc is unpaused and invoke begin was successful. if (!rpc.IsPaused) { this.ProcessMessage6(ref rpc); } } void ProcessMessage6(ref MessageRpc rpc) { rpc.NextProcessor = (rpc.Operation.IsSynchronous) ? this.processMessage8 : this.processMessage7; try { this.thread.BindEndThread(ref rpc); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(e.Message, e); } if (!rpc.IsPaused) { if (rpc.Operation.IsSynchronous) { this.ProcessMessage8(ref rpc); } else { this.ProcessMessage7(ref rpc); } } } void ProcessMessage7(ref MessageRpc rpc) { rpc.NextProcessor = null; try { bool success = false; try { if (this.transaction != null) { this.transaction.InitializeCallContext(ref rpc); } rpc.Operation.InvokeEnd(ref rpc); success = true; } finally { try { if (this.transaction != null) { this.transaction.ClearCallContext(ref rpc); } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (success) { // Throw the transaction.ClearContextException only if // there isn't an exception on the thread already. throw; } this.error.HandleError(e); } } } catch { // Make sure user Exception filters are not run with bad call context throw; } // this never pauses this.ProcessMessage8(ref rpc); } void ProcessMessage8(ref MessageRpc rpc) { rpc.NextProcessor = this.processMessage9; try { this.error.ProvideMessageFault(ref rpc); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.error.HandleError(e); } this.PrepareReply(ref rpc); if (rpc.CanSendReply) { rpc.ReplyTimeoutHelper = new TimeoutHelper(rpc.Channel.OperationTimeout); if (this.sendAsynchronously) { this.BeginFinalizeCorrelation(ref rpc); } else { this.FinalizeCorrelation(ref rpc); } } if (!rpc.IsPaused) { this.ProcessMessage9(ref rpc); } } void ProcessMessage9(ref MessageRpc rpc) { rpc.NextProcessor = this.processMessageCleanup; if (rpc.FinalizeCorrelationImplicitly && this.sendAsynchronously) { this.EndFinalizeCorrelation(ref rpc); } if (rpc.CorrelationCallback == null || rpc.FinalizeCorrelationImplicitly) { this.ResolveTransactionOutcome(ref rpc); } if (rpc.CanSendReply) { if (rpc.Reply != null) { TraceUtility.MessageFlowAtMessageSent(rpc.Reply, rpc.EventTraceActivity); } if (this.sendAsynchronously) { this.BeginReply(ref rpc); } else { this.Reply(ref rpc); } } if (!rpc.IsPaused) { this.ProcessMessageCleanup(ref rpc); } } // Logic for knowing when to close stuff: // // ASSUMPTIONS: // Closing a stream over a message also closes the message. // Closing a message over a stream does not close the stream. // (OperationStreamProvider.ReleaseStream is no-op) // // This is a table of what should be disposed in what cases. // The rows represent the type of parameter to the method and // whether we are disposing parameters or not. The columns // are for the inputs vs. the outputs. The cells contain the // values that need to be Disposed. M^P means that exactly // one of the message and parameter needs to be disposed, // since they refer to the same object. // // Request Reply // Message | M or P | M or P // Dispose Stream | P | M and P // Params | M and P | M and P // | | // Message | none | none // NoDispose Stream | none | M // Params | M | M // // By choosing to dispose the parameter in both of the "M or P" // cases, the logic needed to generate this table is: // // CloseRequestMessage = IsParams // CloseRequestParams = rpc.Operation.DisposeParameters // CloseReplyMessage = rpc.Operation.SerializeReply // CloseReplyParams = rpc.Operation.DisposeParameters // // IsParams can be calculated based on whether the request // message was consumed after deserializing but before calling // the user. This is stored as rpc.DidDeserializeRequestBody. // void ProcessMessageCleanup(ref MessageRpc rpc) { Fx.Assert( !object.ReferenceEquals(rpc.ErrorProcessor, this.processMessageCleanupError), "ProcessMessageCleanup run twice on the same MessageRpc!"); rpc.ErrorProcessor = this.processMessageCleanupError; bool replyWasSent = false; if (rpc.CanSendReply) { if (this.sendAsynchronously) { replyWasSent = this.EndReply(ref rpc); } else { replyWasSent = rpc.SuccessfullySendReply; } } try { try { if (rpc.DidDeserializeRequestBody) { rpc.Request.Close(); } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.error.HandleError(e); } if (rpc.HostingProperty != null) { try { rpc.HostingProperty.Close(); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(e.Message, e); } } // for wf, wf owns the lifetime of the request message. So in that case, we should not dispose the inputs IManualConcurrencyOperationInvoker manualInvoker = rpc.Operation.Invoker as IManualConcurrencyOperationInvoker; rpc.DisposeParameters(manualInvoker != null && manualInvoker.OwnsFormatter); //Dispose all input/output/return parameters if (rpc.FaultInfo.IsConsideredUnhandled) { if (!replyWasSent) { rpc.AbortRequestContext(); rpc.AbortChannel(); } else { rpc.CloseRequestContext(); rpc.CloseChannel(); } rpc.AbortInstanceContext(); } else { if (rpc.RequestContextThrewOnReply) { rpc.AbortRequestContext(); } else { rpc.CloseRequestContext(); } } if ((rpc.Reply != null) && (rpc.Reply != rpc.ReturnParameter)) { try { rpc.Reply.Close(); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.error.HandleError(e); } } if ((rpc.FaultInfo.Fault != null) && (rpc.FaultInfo.Fault.State != MessageState.Closed)) { // maybe ProvideFault gave a Message, but then BeforeSendReply replaced it // in that case, we need to close the one from ProvideFault try { rpc.FaultInfo.Fault.Close(); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.error.HandleError(e); } } try { rpc.OperationContext.FireOperationCompleted(); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } this.instance.AfterReply(ref rpc, this.error); if (rpc.SuccessfullyLockedInstance) { try { this.concurrency.UnlockInstance(ref rpc); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } Fx.Assert("Exceptions should be caught by callee"); rpc.InstanceContext.FaultInternal(); this.error.HandleError(e); } } if (this.terminate != null) { try { this.terminate.AfterReply(ref rpc); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.error.HandleError(e); } } if (rpc.SuccessfullyIncrementedActivity) { try { rpc.Channel.DecrementActivity(); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.error.HandleError(e); } } } finally { if (rpc.MessageRpcOwnsInstanceContextThrottle && rpc.channelHandler.InstanceContextServiceThrottle != null) { rpc.channelHandler.InstanceContextServiceThrottle.DeactivateInstanceContext(); } if (rpc.Activity != null && DiagnosticUtility.ShouldUseActivity) { rpc.Activity.Stop(); } } this.error.HandleError(ref rpc); } void ProcessMessageCleanupError(ref MessageRpc rpc) { this.error.HandleError(ref rpc); } void ResolveTransactionOutcome(ref MessageRpc rpc) { if (this.transaction != null) { try { bool hadError = (rpc.Error != null); try { this.transaction.ResolveOutcome(ref rpc); } catch (FaultException e) { if (rpc.Error == null) { rpc.Error = e; } } finally { if (!hadError && rpc.Error != null) { this.error.ProvideMessageFault(ref rpc); this.PrepareAndAddressReply(ref rpc); } } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.error.HandleError(e); } } } [Fx.Tag.SecurityNote(Critical = "Calls security critical method to set the ActivityId on the thread", Safe = "Set the ActivityId only when MessageRpc is available")] [SecuritySafeCritical] void SetActivityIdOnThread(ref MessageRpc rpc) { if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled && rpc.EventTraceActivity != null) { // Propogate the ActivityId to the service operation EventTraceActivityHelper.SetOnThread(rpc.EventTraceActivity); } } void TransferChannelFromPendingList(ref MessageRpc rpc) { if (rpc.Channel.IsPending) { rpc.Channel.IsPending = false; ChannelDispatcher channelDispatcher = rpc.Channel.ChannelDispatcher; IInstanceContextProvider provider = this.instance.InstanceContextProvider; if (!InstanceContextProviderBase.IsProviderSessionful(provider) && !InstanceContextProviderBase.IsProviderSingleton(provider)) { IChannel proxy = rpc.Channel.Proxy as IChannel; if (!rpc.InstanceContext.IncomingChannels.Contains(proxy)) { channelDispatcher.Channels.Add(proxy); } } channelDispatcher.PendingChannels.Remove(rpc.Channel.Binder.Channel); } } interface IDemuxer { DispatchOperationRuntime GetOperation(ref Message request); } class ActionDemuxer : IDemuxer { HybridDictionary map; DispatchOperationRuntime unhandled; internal ActionDemuxer() { this.map = new HybridDictionary(); } internal void Add(string action, DispatchOperationRuntime operation) { if (map.Contains(action)) { DispatchOperationRuntime existingOperation = (DispatchOperationRuntime)map[action]; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxActionDemuxerDuplicate, existingOperation.Name, operation.Name, action))); } this.map.Add(action, operation); } internal void SetUnhandled(DispatchOperationRuntime operation) { this.unhandled = operation; } public DispatchOperationRuntime GetOperation(ref Message request) { string action = request.Headers.Action; if (action == null) { action = MessageHeaders.WildcardAction; } DispatchOperationRuntime operation = (DispatchOperationRuntime)this.map[action]; if (operation != null) { return operation; } return this.unhandled; } } class CustomDemuxer : IDemuxer { Dictionary<string, DispatchOperationRuntime> map; IDispatchOperationSelector selector; DispatchOperationRuntime unhandled; internal CustomDemuxer(IDispatchOperationSelector selector) { this.selector = selector; this.map = new Dictionary<string, DispatchOperationRuntime>(); } internal void Add(string name, DispatchOperationRuntime operation) { this.map.Add(name, operation); } internal void SetUnhandled(DispatchOperationRuntime operation) { this.unhandled = operation; } public DispatchOperationRuntime GetOperation(ref Message request) { string operationName = this.selector.SelectOperation(ref request); DispatchOperationRuntime operation = null; if (this.map.TryGetValue(operationName, out operation)) { return operation; } else { return this.unhandled; } } } class RpcCorrelationCallbackMessageProperty : CorrelationCallbackMessageProperty { CorrelationCallbackMessageProperty innerCallback; MessageRpc rpc; ImmutableDispatchRuntime runtime; TransactionScope scope; // This constructor should be used when creating the RPCCorrelationMessageproperty the first time // Here we copy the data & the needed data from the original callback public RpcCorrelationCallbackMessageProperty(CorrelationCallbackMessageProperty innerCallback, ImmutableDispatchRuntime runtime, ref MessageRpc rpc) : base(innerCallback) { this.innerCallback = innerCallback; this.runtime = runtime; this.rpc = rpc; } // This constructor should be used when we are making a copy from the already initialized RPCCorrelationCallbackMessageProperty public RpcCorrelationCallbackMessageProperty(RpcCorrelationCallbackMessageProperty rpcCallbackMessageProperty) : base(rpcCallbackMessageProperty) { this.innerCallback = rpcCallbackMessageProperty.innerCallback; this.runtime = rpcCallbackMessageProperty.runtime; this.rpc = rpcCallbackMessageProperty.rpc; } public override IMessageProperty CreateCopy() { return new RpcCorrelationCallbackMessageProperty(this); } protected override IAsyncResult OnBeginFinalizeCorrelation(Message message, TimeSpan timeout, AsyncCallback callback, object state) { bool success = false; this.Enter(); try { IAsyncResult result = this.innerCallback.BeginFinalizeCorrelation(message, timeout, callback, state); success = true; return result; } finally { this.Leave(success); } } protected override Message OnEndFinalizeCorrelation(IAsyncResult result) { bool success = false; this.Enter(); try { Message message = this.innerCallback.EndFinalizeCorrelation(result); success = true; return message; } finally { this.Leave(success); this.CompleteTransaction(); } } protected override Message OnFinalizeCorrelation(Message message, TimeSpan timeout) { bool success = false; this.Enter(); try { Message newMessage = this.innerCallback.FinalizeCorrelation(message, timeout); success = true; return newMessage; } finally { this.Leave(success); this.CompleteTransaction(); } } void CompleteTransaction() { this.runtime.ResolveTransactionOutcome(ref this.rpc); } void Enter() { if (this.rpc.transaction != null && this.rpc.transaction.Current != null) { this.scope = new TransactionScope(this.rpc.transaction.Current); } } void Leave(bool complete) { if (this.scope != null) { if (complete) { scope.Complete(); } scope.Dispose(); this.scope = null; } } } } }
using System; using System.Security.Cryptography; using Microsoft.Extensions.Options; using Xunit; namespace Scalider.Security.Password.Argon2 { public class Argon2PasswordHasherOfTUserTests { private static readonly FakeUser User1; private static readonly FakeUser User2; static Argon2PasswordHasherOfTUserTests() { using var rng = RandomNumberGenerator.Create(); var assignedData = new byte[16]; rng.GetBytes(assignedData); User1 = new FakeUser {AssignedData = assignedData}; assignedData = new byte[16]; rng.GetBytes(assignedData); User2 = new FakeUser {AssignedData = assignedData}; } [Fact] public void HashPassword_WhenNullPassword_ExpectArgumentNull() { Assert.Throws<ArgumentNullException>(() => { var passwordHasher = CreateWithDefaultOptions(); passwordHasher.HashPassword(null); }); } [Fact] public void IsValidPassword_WhenHashedPasswordProvided_ExpectTrue() { var password = Guid.NewGuid().ToString(); var passwordHasher = CreateWithDefaultOptions(); var hashedPassword = passwordHasher.HashPassword(password); Assert.True(passwordHasher.IsValidPasswordHash(hashedPassword)); } [Fact] public void IsValidPassword_WhenHashedPasswordNotProvided_ExpectFalse() { var passwordHasher = CreateWithDefaultOptions(); Assert.False(passwordHasher.IsValidPasswordHash(null)); } [Fact] public void IsValidPassword_WhenHashedPasswordNotHashed_ExpectFalse() { var password = Guid.NewGuid().ToString(); var passwordHasher = CreateWithDefaultOptions(); Assert.False(passwordHasher.IsValidPasswordHash(password)); } [Fact] public void VerifyPassword_WhenPasswordNotProvided_ExpectArgumentNull() { Assert.Throws<ArgumentNullException>(() => { var passwordHasher = CreateWithDefaultOptions(); passwordHasher.VerifyHashedPassword(null, null); }); } [Fact] public void VerifyPassword_WhenHashedPasswordNotProvided_ExpectArgumentNull() { Assert.Throws<ArgumentNullException>(() => { var passwordHasher = CreateWithDefaultOptions(); passwordHasher.VerifyHashedPassword(string.Empty, null); }); } [Fact] public void VerifyPassword_WhenHashedPasswordNotNotHashed_ExpectFailure() { var password = Guid.NewGuid().ToString(); var passwordHasher = CreateWithDefaultOptions(); var verifyResult = passwordHasher.VerifyHashedPassword(password, password); Assert.Equal(PasswordVerificationResult.Failed, verifyResult); } [Fact] public void VerifyPassword_WithDefaultOptions_ExpectSuccess() { var password = Guid.NewGuid().ToString(); var passwordHasher = CreateWithDefaultOptions(); var hashedPassword = passwordHasher.HashPassword(password); var verifyResult = passwordHasher.VerifyHashedPassword(password, hashedPassword); Assert.Equal(PasswordVerificationResult.Success, verifyResult); } [Fact] public void VerifyPassword_WithCustomOptions_ExpectSuccess() { var password = Guid.NewGuid().ToString(); var passwordHasher = CreateWithCustomOptions(); var hashedPassword = passwordHasher.HashPassword(password); var verifyResult = passwordHasher.VerifyHashedPassword(password, hashedPassword); Assert.Equal(PasswordVerificationResult.Success, verifyResult); } [Fact] public void VerifyPassword_WithDifferentOptions_WhenFirstOptionsAreWeaker_ExpectSuccessRehashNeeded() { var password = Guid.NewGuid().ToString(); var passwordHasher1 = CreateWithDefaultOptions(); var passwordHasher2 = CreateWithCustomOptions(); var hashedPassword = passwordHasher1.HashPassword(password); var verifyResult = passwordHasher2.VerifyHashedPassword(password, hashedPassword); Assert.Equal(PasswordVerificationResult.SuccessRehashNeeded, verifyResult); } [Fact] public void VerifyPassword_WithDifferentOptions_WhenFirstOptionsAreStronger_ExpectSuccess() { var password = Guid.NewGuid().ToString(); var passwordHasher1 = CreateWithCustomOptions(); var passwordHasher2 = CreateWithDefaultOptions(); var hashedPassword = passwordHasher1.HashPassword(password); var verifyResult = passwordHasher2.VerifyHashedPassword(password, hashedPassword); Assert.Equal(PasswordVerificationResult.Success, verifyResult); } [Fact] public void VerifyPassword_WithDefaultOptions_WhenDoesntMatch_ExpectFailure() { var password1 = Guid.NewGuid().ToString(); var password2 = Guid.NewGuid().ToString(); var passwordHasher = CreateWithDefaultOptions(); var hashedPassword = passwordHasher.HashPassword(password1); var verifyResult = passwordHasher.VerifyHashedPassword(password2, hashedPassword); Assert.Equal(PasswordVerificationResult.Failed, verifyResult); } [Fact] public void VerifyPassword_WithCustomOptions_WhenDoesntMatch_ExpectFailure() { var password1 = Guid.NewGuid().ToString(); var password2 = Guid.NewGuid().ToString(); var passwordHasher = CreateWithCustomOptions(); var hashedPassword = passwordHasher.HashPassword(password1); var verifyResult = passwordHasher.VerifyHashedPassword(password2, hashedPassword); Assert.Equal(PasswordVerificationResult.Failed, verifyResult); } [Fact] public void VerifyPassword_WithDifferentOptions_WhenPasswordDoesnt_MatchExpectFailure() { var password1 = Guid.NewGuid().ToString(); var password2 = Guid.NewGuid().ToString(); var passwordHasher1 = CreateWithCustomOptions(); var passwordHasher2 = CreateWithDefaultOptions(); var hashedPassword = passwordHasher1.HashPassword(password1); var verifyResult = passwordHasher2.VerifyHashedPassword(password2, hashedPassword); Assert.Equal(PasswordVerificationResult.Failed, verifyResult); } [Fact] public void VerifyPassword_WithDefaultOptions_WhenDifferentAssignedData_ExpectFailure() { var password = Guid.NewGuid().ToString(); var passwordHasher = CreateWithDefaultOptions(); var hashedPassword = passwordHasher.HashPassword(User1, password); var verifyPassword = passwordHasher.VerifyHashedPassword(User2, password, hashedPassword); Assert.Equal(PasswordVerificationResult.Failed, verifyPassword); } [Fact] public void VerifyPassword_WithCustomOptions_WhenDifferentAssignedData_ExpectFailure() { var password = Guid.NewGuid().ToString(); var passwordHasher = CreateWithCustomOptions(); var hashedPassword = passwordHasher.HashPassword(User1, password); var verifyPassword = passwordHasher.VerifyHashedPassword(User2, password, hashedPassword); Assert.Equal(PasswordVerificationResult.Failed, verifyPassword); } [Fact] public void VerifyPassword_WithDifferentOptions_WhenDifferentAssignedData_ExpectFailure() { var password = Guid.NewGuid().ToString(); var passwordHasher1 = CreateWithDefaultOptions(); var passwordHasher2 = CreateWithCustomOptions(); var hashedPassword = passwordHasher1.HashPassword(User1, password); var verifyPassword = passwordHasher2.VerifyHashedPassword(User2, password, hashedPassword); Assert.Equal(PasswordVerificationResult.Failed, verifyPassword); hashedPassword = passwordHasher2.HashPassword(User1, password); verifyPassword = passwordHasher1.VerifyHashedPassword(User2, password, hashedPassword); Assert.Equal(PasswordVerificationResult.Failed, verifyPassword); } private static IPasswordHasher<FakeUser> CreateWithDefaultOptions() => Create(new Argon2PasswordHasherOptions<FakeUser>()); private static IPasswordHasher<FakeUser> CreateWithCustomOptions(int iterations = 20, int degreeOfParallelism = 8) => Create(new Argon2PasswordHasherOptions<FakeUser> { Iterations = iterations, DegreeOfParallelism = degreeOfParallelism }); private static IPasswordHasher<FakeUser> Create(Argon2PasswordHasherOptions<FakeUser> options) { options.GetUserAssociatedData = user => user.AssignedData; var optionsAccessor = new OptionsWrapper<Argon2PasswordHasherOptions<FakeUser>>(options); return new Argon2PasswordHasher<FakeUser>(optionsAccessor); } private class FakeUser { public byte[] AssignedData { get; 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 Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; namespace System.IO { internal sealed partial class Win32FileSystem : FileSystem { internal const int GENERIC_READ = unchecked((int)0x80000000); public override int MaxPath { get { return Interop.Kernel32.MAX_PATH; } } public override int MaxDirectoryPath { get { return Interop.Kernel32.MAX_DIRECTORY_PATH; } } public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite) { Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES); int errorCode = Interop.Kernel32.CopyFile(sourceFullPath, destFullPath, !overwrite); if (errorCode != Interop.Errors.ERROR_SUCCESS) { string fileName = destFullPath; if (errorCode != Interop.Errors.ERROR_FILE_EXISTS) { // For a number of error codes (sharing violation, path // not found, etc) we don't know if the problem was with // the source or dest file. Try reading the source file. using (SafeFileHandle handle = Interop.Kernel32.UnsafeCreateFile(sourceFullPath, GENERIC_READ, FileShare.Read, ref secAttrs, FileMode.Open, 0, IntPtr.Zero)) { if (handle.IsInvalid) fileName = sourceFullPath; } if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED) { if (DirectoryExists(destFullPath)) throw new IOException(SR.Format(SR.Arg_FileIsDirectory_Name, destFullPath), Interop.Errors.ERROR_ACCESS_DENIED); } } throw Win32Marshal.GetExceptionForWin32Error(errorCode, fileName); } } public override void ReplaceFile(string sourceFullPath, string destFullPath, string destBackupFullPath, bool ignoreMetadataErrors) { int flags = Interop.Kernel32.REPLACEFILE_WRITE_THROUGH; if (ignoreMetadataErrors) { flags |= Interop.Kernel32.REPLACEFILE_IGNORE_MERGE_ERRORS; } if (!Interop.Kernel32.ReplaceFile(destFullPath, sourceFullPath, destBackupFullPath, flags, IntPtr.Zero, IntPtr.Zero)) { throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } [System.Security.SecuritySafeCritical] public override void CreateDirectory(string fullPath) { if (PathInternal.IsDirectoryTooLong(fullPath)) throw new PathTooLongException(SR.IO_PathTooLong); // We can save a bunch of work if the directory we want to create already exists. This also // saves us in the case where sub paths are inaccessible (due to ERROR_ACCESS_DENIED) but the // final path is accessible and the directory already exists. For example, consider trying // to create c:\Foo\Bar\Baz, where everything already exists but ACLS prevent access to c:\Foo // and c:\Foo\Bar. In that case, this code will think it needs to create c:\Foo, and c:\Foo\Bar // and fail to due so, causing an exception to be thrown. This is not what we want. if (DirectoryExists(fullPath)) return; List<string> stackDir = new List<string>(); // Attempt to figure out which directories don't exist, and only // create the ones we need. Note that InternalExists may fail due // to Win32 ACL's preventing us from seeing a directory, and this // isn't threadsafe. bool somepathexists = false; int length = fullPath.Length; // We need to trim the trailing slash or the code will try to create 2 directories of the same name. if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath)) length--; int lengthRoot = PathInternal.GetRootLength(fullPath); if (length > lengthRoot) { // Special case root (fullpath = X:\\) int i = length - 1; while (i >= lengthRoot && !somepathexists) { string dir = fullPath.Substring(0, i + 1); if (!DirectoryExists(dir)) // Create only the ones missing stackDir.Add(dir); else somepathexists = true; while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i])) i--; i--; } } int count = stackDir.Count; // If we were passed a DirectorySecurity, convert it to a security // descriptor and set it in he call to CreateDirectory. Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES); bool r = true; int firstError = 0; string errorString = fullPath; // If all the security checks succeeded create all the directories while (stackDir.Count > 0) { string name = stackDir[stackDir.Count - 1]; stackDir.RemoveAt(stackDir.Count - 1); r = Interop.Kernel32.CreateDirectory(name, ref secAttrs); if (!r && (firstError == 0)) { int currentError = Marshal.GetLastWin32Error(); // While we tried to avoid creating directories that don't // exist above, there are at least two cases that will // cause us to see ERROR_ALREADY_EXISTS here. InternalExists // can fail because we didn't have permission to the // directory. Secondly, another thread or process could // create the directory between the time we check and the // time we try using the directory. Thirdly, it could // fail because the target does exist, but is a file. if (currentError != Interop.Errors.ERROR_ALREADY_EXISTS) firstError = currentError; else { // If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw. if (File.InternalExists(name) || (!DirectoryExists(name, out currentError) && currentError == Interop.Errors.ERROR_ACCESS_DENIED)) { firstError = currentError; errorString = name; } } } } // We need this check to mask OS differences // Handle CreateDirectory("X:\\") when X: doesn't exist. Similarly for n/w paths. if ((count == 0) && !somepathexists) { string root = Directory.InternalGetDirectoryRoot(fullPath); if (!DirectoryExists(root)) throw Win32Marshal.GetExceptionForWin32Error(Interop.Errors.ERROR_PATH_NOT_FOUND, root); return; } // Only throw an exception if creating the exact directory we // wanted failed to work correctly. if (!r && (firstError != 0)) throw Win32Marshal.GetExceptionForWin32Error(firstError, errorString); } public override void DeleteFile(string fullPath) { bool r = Interop.Kernel32.DeleteFile(fullPath); if (!r) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) return; else throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override bool DirectoryExists(string fullPath) { int lastError = Interop.Errors.ERROR_SUCCESS; return DirectoryExists(fullPath, out lastError); } private bool DirectoryExists(string path, out int lastError) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); lastError = FillAttributeInfo(path, ref data, returnErrorOnNotFound: true); return (lastError == 0) && (data.fileAttributes != -1) && ((data.fileAttributes & Interop.Kernel32.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) != 0); } public override IEnumerable<string> EnumeratePaths(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { return Win32FileSystemEnumerableFactory.CreateFileNameIterator(fullPath, fullPath, searchPattern, (searchTarget & SearchTarget.Files) == SearchTarget.Files, (searchTarget & SearchTarget.Directories) == SearchTarget.Directories, searchOption); } public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { switch (searchTarget) { case SearchTarget.Directories: return Win32FileSystemEnumerableFactory.CreateDirectoryInfoIterator(fullPath, fullPath, searchPattern, searchOption); case SearchTarget.Files: return Win32FileSystemEnumerableFactory.CreateFileInfoIterator(fullPath, fullPath, searchPattern, searchOption); case SearchTarget.Both: return Win32FileSystemEnumerableFactory.CreateFileSystemInfoIterator(fullPath, fullPath, searchPattern, searchOption); default: throw new ArgumentException(SR.ArgumentOutOfRange_Enum, nameof(searchTarget)); } } /// <summary> /// Returns 0 on success, otherwise a Win32 error code. Note that /// classes should use -1 as the uninitialized state for dataInitialized. /// </summary> /// <param name="returnErrorOnNotFound">Return the error code for not found errors?</param> [System.Security.SecurityCritical] internal static int FillAttributeInfo(string path, ref Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data, bool returnErrorOnNotFound) { int errorCode = Interop.Errors.ERROR_SUCCESS; // Neither GetFileAttributes or FindFirstFile like trailing separators path = path.TrimEnd(PathHelpers.DirectorySeparatorChars); using (new DisableMediaInsertionPrompt()) { if (!Interop.Kernel32.GetFileAttributesEx(path, Interop.Kernel32.GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, ref data)) { errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED) { // Files that are marked for deletion will not let you GetFileAttributes, // ERROR_ACCESS_DENIED is given back without filling out the data struct. // FindFirstFile, however, will. Historically we always gave back attributes // for marked-for-deletion files. var findData = new Interop.Kernel32.WIN32_FIND_DATA(); using (SafeFindHandle handle = Interop.Kernel32.FindFirstFile(path, ref findData)) { if (handle.IsInvalid) { errorCode = Marshal.GetLastWin32Error(); } else { errorCode = Interop.Errors.ERROR_SUCCESS; data.PopulateFrom(ref findData); } } } } } if (errorCode != Interop.Errors.ERROR_SUCCESS && !returnErrorOnNotFound) { switch (errorCode) { case Interop.Errors.ERROR_FILE_NOT_FOUND: case Interop.Errors.ERROR_PATH_NOT_FOUND: case Interop.Errors.ERROR_NOT_READY: // Removable media not ready // Return default value for backward compatibility data.fileAttributes = -1; return Interop.Errors.ERROR_SUCCESS; } } return errorCode; } public override bool FileExists(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: true); return (errorCode == 0) && (data.fileAttributes != -1) && ((data.fileAttributes & Interop.Kernel32.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) == 0); } public override FileAttributes GetAttributes(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: true); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); return (FileAttributes)data.fileAttributes; } public override string GetCurrentDirectory() { StringBuilder sb = StringBuilderCache.Acquire(Interop.Kernel32.MAX_PATH + 1); if (Interop.Kernel32.GetCurrentDirectory(sb.Capacity, sb) == 0) throw Win32Marshal.GetExceptionForLastWin32Error(); string currentDirectory = sb.ToString(); // Note that if we have somehow put our command prompt into short // file name mode (i.e. by running edlin or a DOS grep, etc), then // this will return a short file name. if (currentDirectory.IndexOf('~') >= 0) { int r = Interop.Kernel32.GetLongPathName(currentDirectory, sb, sb.Capacity); if (r == 0 || r >= Interop.Kernel32.MAX_PATH) { int errorCode = Marshal.GetLastWin32Error(); if (r >= Interop.Kernel32.MAX_PATH) errorCode = Interop.Errors.ERROR_FILENAME_EXCED_RANGE; if (errorCode != Interop.Errors.ERROR_FILE_NOT_FOUND && errorCode != Interop.Errors.ERROR_PATH_NOT_FOUND && errorCode != Interop.Errors.ERROR_INVALID_FUNCTION && // by design - enough said. errorCode != Interop.Errors.ERROR_ACCESS_DENIED) throw Win32Marshal.GetExceptionForWin32Error(errorCode); } currentDirectory = sb.ToString(); } StringBuilderCache.Release(sb); return currentDirectory; } public override DateTimeOffset GetCreationTime(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: false); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); long dt = ((long)(data.ftCreationTimeHigh) << 32) | ((long)data.ftCreationTimeLow); return DateTimeOffset.FromFileTime(dt); } public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory) { return asDirectory ? (IFileSystemObject)new DirectoryInfo(fullPath, null) : (IFileSystemObject)new FileInfo(fullPath, null); } public override DateTimeOffset GetLastAccessTime(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: false); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); long dt = ((long)(data.ftLastAccessTimeHigh) << 32) | ((long)data.ftLastAccessTimeLow); return DateTimeOffset.FromFileTime(dt); } public override DateTimeOffset GetLastWriteTime(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: false); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); long dt = ((long)data.ftLastWriteTimeHigh << 32) | ((long)data.ftLastWriteTimeLow); return DateTimeOffset.FromFileTime(dt); } public override void MoveDirectory(string sourceFullPath, string destFullPath) { if (!Interop.Kernel32.MoveFile(sourceFullPath, destFullPath)) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) throw Win32Marshal.GetExceptionForWin32Error(Interop.Errors.ERROR_PATH_NOT_FOUND, sourceFullPath); // This check was originally put in for Win9x (unfortunately without special casing it to be for Win9x only). We can't change the NT codepath now for backcomp reasons. if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED) // WinNT throws IOException. This check is for Win9x. We can't change it for backcomp. throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), Win32Marshal.MakeHRFromErrorCode(errorCode)); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } public override void MoveFile(string sourceFullPath, string destFullPath) { if (!Interop.Kernel32.MoveFile(sourceFullPath, destFullPath)) { throw Win32Marshal.GetExceptionForLastWin32Error(); } } [System.Security.SecurityCritical] private static SafeFileHandle OpenHandle(string fullPath, bool asDirectory) { string root = fullPath.Substring(0, PathInternal.GetRootLength(fullPath)); if (root == fullPath && root[1] == Path.VolumeSeparatorChar) { // intentionally not fullpath, most upstack public APIs expose this as path. throw new ArgumentException(SR.Arg_PathIsVolume, "path"); } Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES); SafeFileHandle handle = Interop.Kernel32.SafeCreateFile( fullPath, Interop.Kernel32.GenericOperations.GENERIC_WRITE, FileShare.ReadWrite | FileShare.Delete, ref secAttrs, FileMode.Open, asDirectory ? Interop.Kernel32.FileOperations.FILE_FLAG_BACKUP_SEMANTICS : (int)FileOptions.None, IntPtr.Zero ); if (handle.IsInvalid) { int errorCode = Marshal.GetLastWin32Error(); // NT5 oddity - when trying to open "C:\" as a File, // we usually get ERROR_PATH_NOT_FOUND from the OS. We should // probably be consistent w/ every other directory. if (!asDirectory && errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND && fullPath.Equals(Directory.GetDirectoryRoot(fullPath))) errorCode = Interop.Errors.ERROR_ACCESS_DENIED; throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } return handle; } public override void RemoveDirectory(string fullPath, bool recursive) { // Do not recursively delete through reparse points. Perhaps in a // future version we will add a new flag to control this behavior, // but for now we're much safer if we err on the conservative side. // This applies to symbolic links and mount points. Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: true); if (errorCode != 0) { // Ensure we throw a DirectoryNotFoundException. if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) errorCode = Interop.Errors.ERROR_PATH_NOT_FOUND; throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } if (((FileAttributes)data.fileAttributes & FileAttributes.ReparsePoint) != 0) recursive = false; // We want extended syntax so we can delete "extended" subdirectories and files // (most notably ones with trailing whitespace or periods) RemoveDirectoryHelper(PathInternal.EnsureExtendedPrefix(fullPath), recursive, true); } [System.Security.SecurityCritical] // auto-generated private static void RemoveDirectoryHelper(string fullPath, bool recursive, bool throwOnTopLevelDirectoryNotFound) { bool r; int errorCode; Exception ex = null; // Do not recursively delete through reparse points. Perhaps in a // future version we will add a new flag to control this behavior, // but for now we're much safer if we err on the conservative side. // This applies to symbolic links and mount points. // Note the logic to check whether fullPath is a reparse point is // in Delete(string, string, bool), and will set "recursive" to false. // Note that Win32's DeleteFile and RemoveDirectory will just delete // the reparse point itself. if (recursive) { Interop.Kernel32.WIN32_FIND_DATA data = new Interop.Kernel32.WIN32_FIND_DATA(); // Open a Find handle using (SafeFindHandle hnd = Interop.Kernel32.FindFirstFile(Directory.EnsureTrailingDirectorySeparator(fullPath) + "*", ref data)) { if (hnd.IsInvalid) throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); do { bool isDir = (0 != (data.dwFileAttributes & Interop.Kernel32.FileAttributes.FILE_ATTRIBUTE_DIRECTORY)); if (isDir) { // Skip ".", "..". if (data.cFileName.Equals(".") || data.cFileName.Equals("..")) continue; // Recurse for all directories, unless they are // reparse points. Do not follow mount points nor // symbolic links, but do delete the reparse point // itself. bool shouldRecurse = (0 == (data.dwFileAttributes & (int)FileAttributes.ReparsePoint)); if (shouldRecurse) { string newFullPath = Path.Combine(fullPath, data.cFileName); try { RemoveDirectoryHelper(newFullPath, recursive, false); } catch (Exception e) { if (ex == null) ex = e; } } else { // Check to see if this is a mount point, and // unmount it. if (data.dwReserved0 == Interop.Kernel32.IOReparseOptions.IO_REPARSE_TAG_MOUNT_POINT) { // Use full path plus a trailing '\' string mountPoint = Path.Combine(fullPath, data.cFileName + PathHelpers.DirectorySeparatorCharAsString); if (!Interop.Kernel32.DeleteVolumeMountPoint(mountPoint)) { errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_SUCCESS && errorCode != Interop.Errors.ERROR_PATH_NOT_FOUND) { try { throw Win32Marshal.GetExceptionForWin32Error(errorCode, data.cFileName); } catch (Exception e) { if (ex == null) ex = e; } } } } // RemoveDirectory on a symbolic link will // remove the link itself. string reparsePoint = Path.Combine(fullPath, data.cFileName); r = Interop.Kernel32.RemoveDirectory(reparsePoint); if (!r) { errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_PATH_NOT_FOUND) { try { throw Win32Marshal.GetExceptionForWin32Error(errorCode, data.cFileName); } catch (Exception e) { if (ex == null) ex = e; } } } } } else { string fileName = Path.Combine(fullPath, data.cFileName); r = Interop.Kernel32.DeleteFile(fileName); if (!r) { errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_FILE_NOT_FOUND) { try { throw Win32Marshal.GetExceptionForWin32Error(errorCode, data.cFileName); } catch (Exception e) { if (ex == null) ex = e; } } } } } while (Interop.Kernel32.FindNextFile(hnd, ref data)); // Make sure we quit with a sensible error. errorCode = Marshal.GetLastWin32Error(); } if (ex != null) throw ex; if (errorCode != 0 && errorCode != Interop.Errors.ERROR_NO_MORE_FILES) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } r = Interop.Kernel32.RemoveDirectory(fullPath); if (!r) { errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) // A dubious error code. errorCode = Interop.Errors.ERROR_PATH_NOT_FOUND; // This check was originally put in for Win9x (unfortunately without special casing it to be for Win9x only). We can't change the NT codepath now for backcomp reasons. if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED) throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, fullPath)); // don't throw the DirectoryNotFoundException since this is a subdir and // there could be a race condition between two Directory.Delete callers if (errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND && !throwOnTopLevelDirectoryNotFound) return; throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override void SetAttributes(string fullPath, FileAttributes attributes) { SetAttributesInternal(fullPath, attributes); } private static void SetAttributesInternal(string fullPath, FileAttributes attributes) { bool r = Interop.Kernel32.SetFileAttributes(fullPath, (int)attributes); if (!r) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_INVALID_PARAMETER) throw new ArgumentException(SR.Arg_InvalidFileAttrs, nameof(attributes)); throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory) { SetCreationTimeInternal(fullPath, time, asDirectory); } private static void SetCreationTimeInternal(string fullPath, DateTimeOffset time, bool asDirectory) { using (SafeFileHandle handle = OpenHandle(fullPath, asDirectory)) { bool r = Interop.Kernel32.SetFileTime(handle, creationTime: time.ToFileTime()); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); } } } public override void SetCurrentDirectory(string fullPath) { if (!Interop.Kernel32.SetCurrentDirectory(fullPath)) { // If path doesn't exist, this sets last error to 2 (File // not Found). LEGACY: This may potentially have worked correctly // on Win9x, maybe. int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) errorCode = Interop.Errors.ERROR_PATH_NOT_FOUND; throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory) { SetLastAccessTimeInternal(fullPath, time, asDirectory); } private static void SetLastAccessTimeInternal(string fullPath, DateTimeOffset time, bool asDirectory) { using (SafeFileHandle handle = OpenHandle(fullPath, asDirectory)) { bool r = Interop.Kernel32.SetFileTime(handle, lastAccessTime: time.ToFileTime()); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); } } } public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory) { SetLastWriteTimeInternal(fullPath, time, asDirectory); } private static void SetLastWriteTimeInternal(string fullPath, DateTimeOffset time, bool asDirectory) { using (SafeFileHandle handle = OpenHandle(fullPath, asDirectory)) { bool r = Interop.Kernel32.SetFileTime(handle, lastWriteTime: time.ToFileTime()); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); } } } public override string[] GetLogicalDrives() { return DriveInfoInternal.GetLogicalDrives(); } } }
using UnityEngine; using XInputDotNetPure; // Required in C# public class XInputTest : MonoBehaviour { AdvanceGamePad pad = new AdvanceGamePad(PlayerIndex.One, GamePadDeadZone.Circular); string previousText; GameObject textObject; GameObject cubeObject; float cubeAngle = 0.0f; // Use this for initialization void Start() { // No need to initialize anything for the plugin previousText = ""; // However, I need that for the purpose of the demo textObject = GameObject.Find("GUI Text"); cubeObject = GameObject.Find("Cube"); } // Update is called once per frame void Update() { // Find a PlayerIndex, for a single player game if(!pad.IsConnected) { Debug.Log(string.Format("GamePad not found")); return; } pad.Update(); string text = "Use left stick to turn the cube\n"; text += string.Format("IsConnected {0} Packet #{1}\n", pad.IsConnected, pad.PacketNumber); text += string.Format("\tTriggers {0} {1}\n", pad.Triggers.Left, pad.Triggers.Right); text += string.Format("\tD-Pad {0} {1} {2} {3}\n", pad.DPad.Up, pad.DPad.Right, pad.DPad.Down, pad.DPad.Left); text += string.Format("\tButtons Start {0} Back {1}\n", pad.Buttons.Start, pad.Buttons.Back); text += string.Format("\tButtons LeftStick {0} RightStick {1} LeftShoulder {2} RightShoulder {3}\n", pad.Buttons.LeftStick, pad.Buttons.RightStick, pad.Buttons.LeftShoulder, pad.Buttons.RightShoulder); text += string.Format("\tButtons A {0} B {1} X {2} Y {3}\n", pad.Buttons.A, pad.Buttons.B, pad.Buttons.X, pad.Buttons.Y); text += string.Format("\tSticks Left {0} {1} Right {2} {3}\n", pad.ThumbSticks.Left.X, pad.ThumbSticks.Left.Y, pad.ThumbSticks.Right.X, pad.ThumbSticks.Right.Y); LogAdvancedCommands(); text += previousText; pad.Vibrate(pad.Triggers.Left, pad.Triggers.Right); LogAdvancedCommands(); // Display the pad information textObject.guiText.text = text; // Make the cube turn cubeAngle += pad.ThumbSticks.Left.X * 25.0f * Time.deltaTime; cubeObject.transform.localRotation = Quaternion.Euler(0.0f, cubeAngle, 0.0f); } void LogAdvancedCommands() { string oldText = previousText; previousText = ""; if(pad.IsConnected) { // TRIGGERED if(pad.AnyTriggered((uint)ButtonsConstants.A)) { previousText +="A Triggered\n"; } if(pad.AnyTriggered((uint)ButtonsConstants.B)) { previousText +="B Triggered\n"; } if(pad.AnyTriggered((uint)ButtonsConstants.X)) { previousText +="X Triggered\n"; } if(pad.AnyTriggered((uint)ButtonsConstants.Y)) { previousText +="Y Triggered\n"; } if(pad.AnyTriggered((uint)ButtonsConstants.DPadDown)) { previousText +=" DPadDown Triggered\n"; } if(pad.AnyTriggered((uint)ButtonsConstants.DPadLeft)) { previousText +=" DPadLeft Triggered\n"; } if(pad.AnyTriggered((uint)ButtonsConstants.DPadRight)) { previousText +=" DPadRight Triggered\n"; } if(pad.AnyTriggered((uint)ButtonsConstants.DPadUp)) { previousText +=" DPadUp Triggered\n"; } if(pad.AnyTriggered((uint)ButtonsConstants.Back)) { previousText +="back Triggered\n"; } if(pad.AnyTriggered((uint)ButtonsConstants.Start)) { previousText +="start Triggered\n"; } if(pad.AnyTriggered((uint)ButtonsConstants.LeftShoulder)) { previousText +="LeftShoulder Triggered\n"; } if(pad.AnyTriggered((uint)ButtonsConstants.RightShoulder)) { previousText +="RightShoulder Triggered\n"; } if(pad.AnyTriggered((uint)ButtonsConstants.LeftTrigger)) { previousText +="LeftTrigger Triggered\n"; } if(pad.AnyTriggered((uint)ButtonsConstants.RightTrigger)) { previousText +="RightTrigger Triggered\n"; } if(pad.AnyTriggered((uint)ButtonsConstants.LeftTrigger | (uint)ButtonsConstants.RightTrigger)) { previousText +="RightTrigger OR LeftTrigger Triggered\n"; } if(pad.AnyTriggered((uint)ButtonsConstants.A | (uint)ButtonsConstants.B)) { previousText +="A OR B Triggered\n"; } if(pad.AnyPressed((uint)ButtonsConstants.Start | (uint)ButtonsConstants.Back)) { previousText +="Start OR Back pressed\n"; } if(pad.AnyTriggered((uint)ButtonsConstants.LeftThumb)) { previousText +="RightThumb Triggered\n"; } if(pad.AnyTriggered((uint)ButtonsConstants.RightThumb)) { previousText +="RightThumb Triggered\n"; } // RELEASE if(pad.AnyReleased((uint)ButtonsConstants.A)) { previousText +="A Released\n"; } if(pad.AnyReleased((uint)ButtonsConstants.B)) { previousText +="B Released\n"; } if(pad.AnyReleased((uint)ButtonsConstants.X)) { previousText +="X Released\n"; } if(pad.AnyReleased((uint)ButtonsConstants.Y)) { previousText +="Y Released\n"; pad.Vibrate(0,0); } if(pad.AnyReleased((uint)ButtonsConstants.DPadDown)) { previousText +=" DPadDown Released\n"; } if(pad.AnyReleased((uint)ButtonsConstants.DPadLeft)) { previousText +=" DPadLeft Released\n"; } if(pad.AnyReleased((uint)ButtonsConstants.DPadRight)) { previousText +=" DPadRight Released\n"; } if(pad.AnyReleased((uint)ButtonsConstants.DPadUp)) { previousText +=" DPadUp Released\n"; } if(pad.AnyReleased((uint)ButtonsConstants.Back)) { previousText +="back Released\n"; } if(pad.AnyReleased((uint)ButtonsConstants.Start)) { previousText +="start Released\n"; } if(pad.AnyReleased((uint)ButtonsConstants.LeftShoulder)) { previousText +="LeftShoulder Released\n"; } if(pad.AnyReleased((uint)ButtonsConstants.RightShoulder)) { previousText +="RightShoulder Released\n"; } if(pad.AnyReleased((uint)ButtonsConstants.LeftTrigger)) { previousText +="LeftTrigger Released\n"; } if(pad.AnyReleased((uint)ButtonsConstants.RightTrigger)) { previousText +="RightTrigger Released\n"; } if(pad.AnyReleased((uint)ButtonsConstants.LeftTrigger | (uint)ButtonsConstants.RightTrigger)) { previousText +="LeftTrigger OR RightTrigger Released\n"; } if(pad.AnyReleased((uint)ButtonsConstants.A | (uint)ButtonsConstants.B)) { previousText +="A OR B Released\n"; } if(pad.AnyReleased((uint)ButtonsConstants.LeftThumb)) { previousText +="RightThumb Released\n"; } if(pad.AnyReleased((uint)ButtonsConstants.RightThumb)) { previousText +="RightThumb Released\n"; } // Pressed if(pad.AllPressed((uint)ButtonsConstants.A | (uint)ButtonsConstants.LeftTrigger)) { previousText +="A and LeftTrigger Pressed\n"; } if(pad.AllPressed((uint)ButtonsConstants.LeftTrigger | (uint)ButtonsConstants.RightTrigger)) { previousText +="LeftTrigger AND right Pressed\n"; } if(pad.AnyPressed((uint)ButtonsConstants.DPadDown | (uint)ButtonsConstants.DPadLeft)) { previousText +="down or left pressed Pressed\n"; } // VIBRATION + MULTITEST if(pad.AllPressed((uint)ButtonsConstants.A | (uint)ButtonsConstants.B)) { previousText +="A and B Pressed\n"; } if(pad.AllPressed((uint)ButtonsConstants.A | (uint)ButtonsConstants.X)) { previousText +="A and X Pressed\n"; } if(pad.AllPressed((uint)ButtonsConstants.X | (uint)ButtonsConstants.B)) { previousText +="X and B Pressed\n"; } if(pad.AnyPressed()) { //previousText +="one pressed Pressed\n"; } if(pad.NonePressed()) { //previousText +="None Pressed\n"; } if(pad.NonePressed((uint)ButtonsConstants.X | (uint)ButtonsConstants.B)) { //previousText +="X and B not Pressed\n"; } if(previousText == "") { previousText = oldText; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Linq; using System.Management.Automation; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using Microsoft.Win32; namespace Microsoft.PowerShell.Commands { internal static class ContentHelper { #region Constants // default codepage encoding for web content. See RFC 2616. private const string _defaultCodePage = "ISO-8859-1"; #endregion Constants #region Fields // used to split contentType arguments private static readonly char[] s_contentTypeParamSeparator = { ';' }; #endregion Fields #region Internal Methods internal static string GetContentType(HttpResponseMessage response) { // ContentType may not exist in response header. Return null if not. return response.Content.Headers.ContentType?.MediaType; } internal static Encoding GetDefaultEncoding() { return GetEncodingOrDefault((string)null); } internal static Encoding GetEncoding(HttpResponseMessage response) { // ContentType may not exist in response header. string charSet = response.Content.Headers.ContentType?.CharSet; return GetEncodingOrDefault(charSet); } internal static Encoding GetEncodingOrDefault(string characterSet) { // get the name of the codepage to use for response content string codepage = (string.IsNullOrEmpty(characterSet) ? _defaultCodePage : characterSet); Encoding encoding = null; try { encoding = Encoding.GetEncoding(codepage); } catch (ArgumentException) { // 0, default code page encoding = Encoding.GetEncoding(0); } return encoding; } internal static StringBuilder GetRawContentHeader(HttpResponseMessage response) { StringBuilder raw = new StringBuilder(); string protocol = WebResponseHelper.GetProtocol(response); if (!string.IsNullOrEmpty(protocol)) { int statusCode = WebResponseHelper.GetStatusCode(response); string statusDescription = WebResponseHelper.GetStatusDescription(response); raw.AppendFormat("{0} {1} {2}", protocol, statusCode, statusDescription); raw.AppendLine(); } HttpHeaders[] headerCollections = { response.Headers, response.Content == null ? null : response.Content.Headers }; foreach (var headerCollection in headerCollections) { if (headerCollection == null) { continue; } foreach (var header in headerCollection) { // Headers may have multiple entries with different values foreach (var headerValue in header.Value) { raw.Append(header.Key); raw.Append(": "); raw.Append(headerValue); raw.AppendLine(); } } } raw.AppendLine(); return raw; } internal static bool IsJson(string contentType) { contentType = GetContentTypeSignature(contentType); return CheckIsJson(contentType); } internal static bool IsText(string contentType) { contentType = GetContentTypeSignature(contentType); return CheckIsText(contentType); } internal static bool IsXml(string contentType) { contentType = GetContentTypeSignature(contentType); return CheckIsXml(contentType); } #endregion Internal Methods #region Private Helper Methods private static bool CheckIsJson(string contentType) { if (string.IsNullOrEmpty(contentType)) return false; // the correct type for JSON content, as specified in RFC 4627 bool isJson = contentType.Equals("application/json", StringComparison.OrdinalIgnoreCase); // add in these other "javascript" related types that // sometimes get sent down as the mime type for JSON content isJson |= contentType.Equals("text/json", StringComparison.OrdinalIgnoreCase) || contentType.Equals("application/x-javascript", StringComparison.OrdinalIgnoreCase) || contentType.Equals("text/x-javascript", StringComparison.OrdinalIgnoreCase) || contentType.Equals("application/javascript", StringComparison.OrdinalIgnoreCase) || contentType.Equals("text/javascript", StringComparison.OrdinalIgnoreCase); return (isJson); } private static bool CheckIsText(string contentType) { if (string.IsNullOrEmpty(contentType)) return false; // any text, xml or json types are text bool isText = contentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) || CheckIsXml(contentType) || CheckIsJson(contentType); // Further content type analysis is available on Windows if (Platform.IsWindows && !isText) { // Media types registered with Windows as having a perceived type of text, are text using (RegistryKey contentTypeKey = Registry.ClassesRoot.OpenSubKey(@"MIME\Database\Content Type\" + contentType)) { if (contentTypeKey != null) { string extension = contentTypeKey.GetValue("Extension") as string; if (extension != null) { using (RegistryKey extensionKey = Registry.ClassesRoot.OpenSubKey(extension)) { if (extensionKey != null) { string perceivedType = extensionKey.GetValue("PerceivedType") as string; isText = (perceivedType == "text"); } } } } } } return (isText); } private static bool CheckIsXml(string contentType) { if (string.IsNullOrEmpty(contentType)) return false; // RFC 3023: Media types with the suffix "+xml" are XML bool isXml = (contentType.Equals("application/xml", StringComparison.OrdinalIgnoreCase) || contentType.Equals("application/xml-external-parsed-entity", StringComparison.OrdinalIgnoreCase) || contentType.Equals("application/xml-dtd", StringComparison.OrdinalIgnoreCase)); isXml |= contentType.EndsWith("+xml", StringComparison.OrdinalIgnoreCase); return (isXml); } private static string GetContentTypeSignature(string contentType) { if (string.IsNullOrEmpty(contentType)) return null; string sig = contentType.Split(s_contentTypeParamSeparator, 2)[0].ToUpperInvariant(); return (sig); } #endregion Private Helper Methods } }
// 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.Net.Sockets; using System.Net.Test.Common; using System.Runtime.ExceptionServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Security.Tests { using Configuration = System.Net.Test.Common.Configuration; public class ServerAsyncAuthenticateTest : IDisposable { private readonly ITestOutputHelper _log; private readonly ITestOutputHelper _logVerbose; private readonly X509Certificate2 _serverCertificate; public ServerAsyncAuthenticateTest() { _log = TestLogging.GetInstance(); _logVerbose = VerboseTestLogging.GetInstance(); _serverCertificate = Configuration.Certificates.GetServerCertificate(); } public void Dispose() { _serverCertificate.Dispose(); } [Theory] [ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))] [ActiveIssue(16516, TestPlatforms.Windows)] public async Task ServerAsyncAuthenticate_EachSupportedProtocol_Success(SslProtocols protocol) { await ServerAsyncSslHelper(protocol, protocol); } [Theory] [ClassData(typeof(SslProtocolSupport.UnsupportedSslProtocolsTestData))] [ActiveIssue(16516, TestPlatforms.Windows)] public async Task ServerAsyncAuthenticate_EachServerUnsupportedProtocol_Fail(SslProtocols protocol) { await Assert.ThrowsAsync<NotSupportedException>(() => { return ServerAsyncSslHelper( SslProtocolSupport.SupportedSslProtocols, protocol, expectedToFail: true); }); } [Theory] [MemberData(nameof(ProtocolMismatchData))] [ActiveIssue(16516, TestPlatforms.Windows)] public async Task ServerAsyncAuthenticate_MismatchProtocols_Fails( SslProtocols serverProtocol, SslProtocols clientProtocol, Type expectedException) { await Assert.ThrowsAsync( expectedException, () => { return ServerAsyncSslHelper( serverProtocol, clientProtocol, expectedToFail: true); }); } [Fact] [ActiveIssue(16516, TestPlatforms.Windows)] public async Task ServerAsyncAuthenticate_UnsupportedAllServer_Fail() { await Assert.ThrowsAsync<NotSupportedException>(() => { return ServerAsyncSslHelper( SslProtocolSupport.SupportedSslProtocols, SslProtocolSupport.UnsupportedSslProtocols, expectedToFail: true); }); } [Theory] [ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))] [ActiveIssue(16516, TestPlatforms.Windows)] public async Task ServerAsyncAuthenticate_AllClientVsIndividualServerSupportedProtocols_Success( SslProtocols serverProtocol) { await ServerAsyncSslHelper(SslProtocolSupport.SupportedSslProtocols, serverProtocol); } private static IEnumerable<object[]> ProtocolMismatchData() { yield return new object[] { SslProtocols.Tls, SslProtocols.Tls11, typeof(AuthenticationException) }; yield return new object[] { SslProtocols.Tls, SslProtocols.Tls12, typeof(AuthenticationException) }; yield return new object[] { SslProtocols.Tls11, SslProtocols.Tls, typeof(TimeoutException) }; yield return new object[] { SslProtocols.Tls11, SslProtocols.Tls12, typeof(AuthenticationException) }; yield return new object[] { SslProtocols.Tls12, SslProtocols.Tls, typeof(TimeoutException) }; yield return new object[] { SslProtocols.Tls12, SslProtocols.Tls11, typeof(TimeoutException) }; } #region Helpers private async Task ServerAsyncSslHelper( SslProtocols clientSslProtocols, SslProtocols serverSslProtocols, bool expectedToFail = false) { _log.WriteLine( "Server: " + serverSslProtocols + "; Client: " + clientSslProtocols + " expectedToFail: " + expectedToFail); int timeOut = expectedToFail ? TestConfiguration.FailingTestTimeoutMiliseconds : TestConfiguration.PassingTestTimeoutMilliseconds; IPEndPoint endPoint = new IPEndPoint(IPAddress.IPv6Loopback, 0); var server = new TcpListener(endPoint); server.Start(); using (var clientConnection = new TcpClient(AddressFamily.InterNetworkV6)) { IPEndPoint serverEndPoint = (IPEndPoint)server.LocalEndpoint; Task clientConnect = clientConnection.ConnectAsync(serverEndPoint.Address, serverEndPoint.Port); Task<TcpClient> serverAccept = server.AcceptTcpClientAsync(); // We expect that the network-level connect will always complete. await Task.WhenAll(new Task[] { clientConnect, serverAccept }).TimeoutAfter( TestConfiguration.PassingTestTimeoutMilliseconds); using (TcpClient serverConnection = await serverAccept) using (SslStream sslClientStream = new SslStream(clientConnection.GetStream())) using (SslStream sslServerStream = new SslStream( serverConnection.GetStream(), false, AllowAnyServerCertificate)) { string serverName = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false); _logVerbose.WriteLine("ServerAsyncAuthenticateTest.AuthenticateAsClientAsync start."); Task clientAuthentication = sslClientStream.AuthenticateAsClientAsync( serverName, null, clientSslProtocols, false); _logVerbose.WriteLine("ServerAsyncAuthenticateTest.AuthenticateAsServerAsync start."); Task serverAuthentication = sslServerStream.AuthenticateAsServerAsync( _serverCertificate, true, serverSslProtocols, false); try { await clientAuthentication.TimeoutAfter(timeOut); _logVerbose.WriteLine("ServerAsyncAuthenticateTest.clientAuthentication complete."); } catch (Exception ex) { // Ignore client-side errors: we're only interested in server-side behavior. _log.WriteLine("Client exception: " + ex); } await serverAuthentication.TimeoutAfter(timeOut); _logVerbose.WriteLine("ServerAsyncAuthenticateTest.serverAuthentication complete."); _log.WriteLine( "Server({0}) authenticated with encryption cipher: {1} {2}-bit strength", serverEndPoint, sslServerStream.CipherAlgorithm, sslServerStream.CipherStrength); Assert.True( sslServerStream.CipherAlgorithm != CipherAlgorithmType.Null, "Cipher algorithm should not be NULL"); Assert.True(sslServerStream.CipherStrength > 0, "Cipher strength should be greater than 0"); } } } // The following method is invoked by the RemoteCertificateValidationDelegate. private bool AllowAnyServerCertificate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { Assert.True( (sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) == SslPolicyErrors.RemoteCertificateNotAvailable, "Client didn't supply a cert, the server required one, yet sslPolicyErrors is " + sslPolicyErrors); return true; // allow everything } #endregion Helpers } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Marten.Events; using Marten.Exceptions; using Marten.Services; using Marten.Services.Events; using Marten.Testing.Harness; using Newtonsoft.Json; using Shouldly; using Xunit; namespace Marten.Testing.Events { public class ScenarioAggregateAndRepository: IntegrationContext { public ScenarioAggregateAndRepository(DefaultStoreFixture fixture) : base(fixture) { StoreOptions(options => { options.Events.StreamIdentity = StreamIdentity.AsString; options.Events.UseAggregatorLookup(AggregationLookupStrategy.UsePublicAndPrivateApply); }); } [Fact] public void CanStoreAndHydrateAggregate() { var invoice = CreateInvoice(); // SAMPLE: scenario-aggregate-storeandreadinvoice var repository = new AggregateRepository(theStore); repository.Store(invoice); var invoiceFromRepository = repository.Load<Invoice>(invoice.Id); Assert.Equal(invoice.ToString(), invoiceFromRepository.ToString()); Assert.Equal(invoice.Total, invoiceFromRepository.Total); // ENDSAMPLE } [Fact] public void CanStoreAndHydrateAggregatePreviousVersion() { var repository = new AggregateRepository(theStore); var invoice = CreateInvoice(); repository.Store(invoice); // SAMPLE: scenario-aggregate-versionedload var invoiceFromRepository = repository.Load<Invoice>(invoice.Id, 2); Assert.Equal(124, invoiceFromRepository.Total); // ENDSAMPLE } [Fact] public void CanGuardVersion() { var repository = new AggregateRepository(theStore); // SAMPLE: scenario-aggregate-conflict var invoice = CreateInvoice(); var invoiceWithSameIdentity = CreateInvoice(); repository.Store(invoice); Assert.Throws<EventStreamUnexpectedMaxEventIdException>(() => { repository.Store(invoiceWithSameIdentity); }); // ENDSAMPLE } [Fact] public void CanRetrieveVersion() { var repository = new AggregateRepository(theStore); var invoice = CreateInvoice(); invoice.Version.ShouldBe(3); repository.Store(invoice); // Assert version was incremented properly var invoiceFromRepository = repository.Load<Invoice>(invoice.Id); invoiceFromRepository.Version.ShouldBe(3); // Update aggregate invoiceFromRepository.AddLine(100, 23, "Some nice product with 23% VAT"); repository.Store(invoiceFromRepository); // Assert version was incremented properly invoiceFromRepository = repository.Load<Invoice>(invoice.Id); invoiceFromRepository.Version.ShouldBe(4); } private static Invoice CreateInvoice() { // SAMPLE: scenario-aggregate-createinvoice var invoice = new Invoice(42); invoice.AddLine(100, 24, "Joo Janta 200 Super-Chromatic Peril Sensitive Sunglasses"); invoice.AddLine(200, 16, "Happy Vertical People Transporter"); // ENDSAMPLE return invoice; } } // SAMPLE: scenario-aggregate-invoice public sealed class Invoice: AggregateBase { public Invoice(int invoiceNumber) { if (invoiceNumber <= 0) { throw new ArgumentException("Invoice number needs to be positive", nameof(invoiceNumber)); } // Instantiation creates our initial event, capturing the invoice number var @event = new InvoiceCreated(invoiceNumber); // Call Apply to mutate state of aggregate based on event Apply(@event); // Add the event to uncommitted events to use it while persisting the events to Marten events store AddUncommittedEvent(@event); } private Invoice() { } // Enforce any contracts on input, then raise event capturing the data public void AddLine(decimal price, decimal vat, string description) { if (string.IsNullOrEmpty(description)) { throw new ArgumentException("Description cannot be empty", nameof(description)); } var @event = new LineItemAdded(price, vat, description); // Call Apply to mutate state of aggregate based on event Apply(@event); // Add the event to uncommitted events to use it while persisting the events to Marten events store AddUncommittedEvent(@event); } public override string ToString() { var lineItems = string.Join(Environment.NewLine, lines.Select(x => $"{x.Item1}: {x.Item2} ({x.Item3}% VAT)")); return $"{lineItems}{Environment.NewLine}Total: {Total}"; } public decimal Total { get; private set; } private readonly List<Tuple<string, decimal, decimal>> lines = new List<Tuple<string, decimal, decimal>>(); // Apply the deltas to mutate our state private void Apply(InvoiceCreated @event) { Id = @event.InvoiceNumber.ToString(CultureInfo.InvariantCulture); // Ensure to update version on every Apply method. Version++; } // Apply the deltas to mutate our state private void Apply(LineItemAdded @event) { var price = @event.Price * (1 + @event.Vat / 100); Total += price; lines.Add(Tuple.Create(@event.Description, price, @event.Vat)); // Ensure to update version on every Apply method. Version++; } } // ENDSAMPLE // SAMPLE: scenario-aggregate-events public sealed class InvoiceCreated { public int InvoiceNumber { get; } public InvoiceCreated(int invoiceNumber) { InvoiceNumber = invoiceNumber; } } public sealed class LineItemAdded { public decimal Price { get; } public decimal Vat { get; } public string Description { get; } public LineItemAdded(decimal price, decimal vat, string description) { Price = price; Vat = vat; Description = description; } } // ENDSAMPLE // SAMPLE: scenario-aggregate-base // Infrastructure to capture modifications to state in events public abstract class AggregateBase { // For indexing our event streams public string Id { get; protected set; } // For protecting the state, i.e. conflict prevention public int Version { get; protected set; } // JsonIgnore - for making sure that it won't be stored in inline projection [JsonIgnore] private readonly List<object> _uncommittedEvents = new List<object>(); // Get the deltas, i.e. events that make up the state, not yet persisted public IEnumerable<object> GetUncommittedEvents() { return _uncommittedEvents; } // Mark the deltas as persisted. public void ClearUncommittedEvents() { _uncommittedEvents.Clear(); } protected void AddUncommittedEvent(object @event) { // add the event to the uncommitted list _uncommittedEvents.Add(@event); } } // ENDSAMPLE // SAMPLE: scenario-aggregate-repository public sealed class AggregateRepository { private readonly IDocumentStore store; public AggregateRepository(IDocumentStore store) { this.store = store; } public void Store(AggregateBase aggregate) { using (var session = store.OpenSession()) { // Take non-persisted events, push them to the event stream, indexed by the aggregate ID var events = aggregate.GetUncommittedEvents().ToArray(); session.Events.Append(aggregate.Id, aggregate.Version, events); session.SaveChanges(); } // Once successfully persisted, clear events from list of uncommitted events aggregate.ClearUncommittedEvents(); } public T Load<T>(string id, int? version = null) where T : AggregateBase { using (var session = store.LightweightSession()) { var aggregate = session.Events.AggregateStream<T>(id, version ?? 0); return aggregate ?? throw new InvalidOperationException($"No aggregate by id {id}."); } } } // ENDSAMPLE }
using System; using System.Collections; using System.Data; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Text; using Epi.Collections; using Epi.Analysis; using Epi.Windows.Dialogs; using Epi.Windows.Analysis; namespace Epi.Windows.Analysis.Dialogs { /// <summary> /// Dialog for Display command /// </summary> public partial class DisplayDialog : CommandDesignDialog { #region Private Class Members private const int scaleBy = 200; private int startingHeight; #endregion //Private Class Members #region Constructors /// <summary> /// Default constructor - NOT TO BE USED FOR INSTANTIATION /// </summary> [Obsolete("Use of default constructor not allowed", true)] public DisplayDialog() { InitializeComponent(); } /// <summary> /// Constructor for Display dialog /// </summary> public DisplayDialog(Epi.Windows.Analysis.Forms.AnalysisMainForm frm) : base(frm) { InitializeComponent(); Construct(); } private void Construct() { if (!this.DesignMode) { this.btnOK.Click += new System.EventHandler(this.btnOK_Click); this.btnSaveOnly.Click += new System.EventHandler(this.btnSaveOnly_Click); } } #endregion //Constructors #region Protected Methods /// <summary> /// Generate the DISPLAY command /// </summary> protected override void GenerateCommand() { StringBuilder sb = new StringBuilder(); // Add Command name sb.Append(Epi.CommandNames.DISPLAY); sb.Append(StringLiterals.SPACE); if (rdbViews.Checked) { sb.Append(Epi.CommandNames.DBVIEWS); string s = txtDatabase.Text; if (!string.IsNullOrEmpty(s)) { sb.Append(StringLiterals.SPACE).Append(StringLiterals.SINGLEQUOTES); sb.Append(s).Append(StringLiterals.SINGLEQUOTES); } } else if (rdbTables.Checked) { sb.Append(Epi.CommandNames.TABLES); string s = txtDatabase.Text; if (!string.IsNullOrEmpty(s)) { sb.Append(StringLiterals.SPACE).Append(StringLiterals.SINGLEQUOTES); sb.Append(s).Append(StringLiterals.SINGLEQUOTES); } } else { sb.Append(CommandNames.DBVARIABLES); switch (cmbVariables.SelectedIndex) { case 1: sb.Append(StringLiterals.SPACE).Append(CommandNames.DEFINE); break; case 2: sb.Append(StringLiterals.SPACE).Append(CommandNames.FIELDVAR); break; case 3: sb.Append(StringLiterals.SPACE).Append(CommandNames.LIST).Append(GetSelectedVariables()); break; default: break; } if (this.cmbVariables.SelectedIndex > 3) { } } if (!string.IsNullOrEmpty(this.txtOutput.Text)) { sb.Append(StringLiterals.SPACE); sb.Append(CommandNames.OUTTABLE).Append(StringLiterals.EQUAL).Append(txtOutput.Text); } CommandText = sb.ToString(); } /// <summary> /// Before executing the command, preprocesses information gathered from the dialog. /// If the current project has changed, updates Global.CurrentProject /// </summary> protected override void PreProcess() { //base.PreProcess(); } /// <summary> /// Checks if the input provided is sufficient and enables control buttons accordingly. /// </summary> public override void CheckForInputSufficiency() { bool inputValid = ValidateInput(); btnOK.Enabled = inputValid; btnSaveOnly.Enabled = inputValid; } /// <summary> /// Validates user input /// </summary> /// <returns>True/False depending upon whether error messages were found</returns> protected override bool ValidateInput() { base.ValidateInput(); if (this.cmbVariables.Text == "--Selected variables" && this.lbxVariables.SelectedItems.Count == 0) { ErrorMessages.Add("Please select variables to display."); } return (ErrorMessages.Count == 0); } #endregion #region Event Handlers private void btnEllipse_Click(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "All Files(*.mdb)|" + "*.mdb"; if (dlg.ShowDialog(this) == DialogResult.OK) { this.txtDatabase.Text = dlg.FileName; } } /// <summary> /// Sets txtRecAffected text with value selected from cmbAvailableVar /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbVariables_SelectedIndexChanged(object sender, System.EventArgs e) { EnableListbox(cmbVariables.SelectedIndex == 3); } /// <summary> /// Common event handler for radiobuttons /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void RadioButtonClick(object sender, System.EventArgs e) { if (rdbVariables.Checked) { lblFrom.Text = "&From"; ToggleControls(false); } else { lblFrom.Text = "&Database (Blank for current)"; ToggleControls(true); } } /// <summary> /// Clears user selection /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void btnClear_Click(object sender, System.EventArgs e) { rdbVariables.Checked = true; ToggleControls(false); } /// <summary> /// Opens a process to show the related help topic /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> protected override void btnHelp_Click(object sender, System.EventArgs e) { System.Diagnostics.Process.Start("http://www.cdc.gov/epiinfo/user-guide/command-reference/analysis-commands-display.html"); } #endregion //Event Handlers #region Private Methods private string GetSelectedVariables() { StringBuilder sb = new StringBuilder(); foreach (string s in lbxVariables.SelectedItems) { sb.Append(StringLiterals.SPACE); sb.Append(FieldNameNeedsBrackets(s) ? Util.InsertInSquareBrackets(s) : s); } return sb.ToString(); } /// <summary> /// Show and hide the listbox; resizing in the process /// </summary> /// <param name="enabled">Whether to enable or disable the 'Variables' listbox</param> private void EnableListbox(bool enabled) { int ofs; this.lbxVariables.Visible = enabled; this.lbxVariables.Enabled = enabled; ofs = 0; if (!enabled && (this.Height > startingHeight)) { ofs = -scaleBy; } else if (enabled && (this.Height <= startingHeight)) { ofs = scaleBy; } this.Height += ofs; btnOK.Top += ofs; btnCancel.Top += ofs; btnClear.Top += ofs; btnSaveOnly.Top += ofs; btnHelp.Top += ofs; } /// <summary> /// Show and hide controls based on radiobutton selection /// </summary> /// <param name="visible">Boolean to determine whether controls will be visible</param> private void ToggleControls(bool visible) { cmbVariables.Visible = !(visible); txtDatabase.Visible = visible; btnEllipse.Visible = visible; } /// <summary> /// Loads Variables into the combo /// </summary> private void LoadComboVariables() { try { // Clear the list in case there's anything there cmbVariables.Items.Clear(); // next add the predefineds so they'll show up first cmbVariables.Items.Add("--Variables currently available"); cmbVariables.Items.Add("--Defined variables currently available"); cmbVariables.Items.Add("--Field variables currently available"); cmbVariables.Items.Add("--Selected variables"); // get project reference Project project = this.EpiInterpreter.Context.CurrentProject; if (project != null) { ViewCollection views = project.Views; if (views != null) { foreach (View view in views) { cmbVariables.Items.Add(view.Name); } } cmbVariables.SelectedIndex = 0; } } catch (Exception ex) { Epi.Windows.MsgBox.ShowInformation(ex.Message); } finally { }//finally } private void DisplayDialog_Load(object sender, System.EventArgs e) { VariableType scopeWord = VariableType.DataSource | VariableType.Standard | VariableType.Global | VariableType.Permanent; FillVariableListBox(lbxVariables, scopeWord); lbxVariables.SelectedIndex = -1; startingHeight = this.Height; LoadComboVariables(); this.cmbVariables.SelectedIndexChanged += new System.EventHandler(this.cmbVariables_SelectedIndexChanged); } #endregion //Private Methods } }
// // StationSource.cs // // Authors: // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2007-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Data; using System.IO; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Threading; using Mono.Unix; using Gtk; using Hyena; using Hyena.Data.Sqlite; using Lastfm; using ConnectionState = Lastfm.ConnectionState; using Banshee.Base; using Banshee.Widgets; using Banshee.Database; using Banshee.Sources; using Banshee.Metadata; using Banshee.MediaEngine; using Banshee.Collection; using Banshee.ServiceStack; using Banshee.PlaybackController; namespace Banshee.Lastfm.Radio { public class StationSource : Source, ITrackModelSource, IUnmapableSource, IDisposable, IBasicPlaybackController { private static string generic_name = Catalog.GetString ("Last.fm Station"); public static StationSource CreateFromUrl (LastfmSource lastfm, string url) { foreach (StationType type in StationType.Types) { string regex = Regex.Escape (type.GetStationFor ("XXX")).Replace ("XXX", "([^\\/]+)"); Match match = Regex.Match (url, regex); if (match.Groups.Count == 2 && match.Groups[0].Captures.Count > 0) { Log.DebugFormat ("Creating last.fm station from url {0}", url); string arg = match.Groups[1].Captures[0].Value; StationSource station = new StationSource (lastfm, arg, type.Name, arg); lastfm.AddChildSource (station); station.NotifyUser (); } } return null; } private MemoryTrackListModel track_model; private LastfmSource lastfm; public LastfmSource LastfmSource { get { return lastfm; } } private string station; public string Station { get { return station; } protected set { station = value; } } private StationType type; public StationType Type { get { return type; } set { type = value; if (type.IconName != null) Properties.SetString ("Icon.Name", type.IconName); } } public override string TypeName { get { return Type.Name; } } private string arg; public string Arg { get { return arg; } set { arg = value; } } private int play_count; public int PlayCount { get { return play_count; } set { play_count = value; } } private int dbid; // For StationSources that already exist in the db protected StationSource (LastfmSource lastfm, int dbId, string name, string type, string arg, int playCount) : base (generic_name, name, 150, dbId.ToString ()) { this.lastfm = lastfm; dbid = dbId; Type = StationType.FindByName (type); Arg = arg; PlayCount = playCount; Station = Type.GetStationFor (arg); StationInitialize (); } public StationSource (LastfmSource lastfm, string name, string type, string arg) : base (generic_name, name, 150) { this.lastfm = lastfm; Type = StationType.FindByName (type); Arg = arg; Station = Type.GetStationFor (arg); Save (); StationInitialize (); } private void StationInitialize () { track_model = new MemoryTrackListModel (); ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent, PlayerEvent.StateChange); lastfm.Connection.StateChanged += HandleConnectionStateChanged; Properties.SetString ("GtkActionPath", "/LastfmStationSourcePopup"); Properties.SetString ("SourcePropertiesActionLabel", Catalog.GetString ("Edit Last.fm Station")); Properties.SetString ("UnmapSourceActionLabel", Catalog.GetString ("Delete Last.fm Station")); UpdateUI (lastfm.Connection.State); } public void Dispose () { ServiceManager.PlayerEngine.DisconnectEvent (OnPlayerEvent); lastfm.Connection.StateChanged -= HandleConnectionStateChanged; } public virtual void Save () { if (dbid <= 0) Create (); else Update (); OnUpdated (); } private void Create () { HyenaSqliteCommand command = new HyenaSqliteCommand ( @"INSERT INTO LastfmStations (Creator, Name, Type, Arg, PlayCount) VALUES (?, ?, ?, ?, ?)", lastfm.Account.UserName, Name, Type.ToString (), Arg, PlayCount ); dbid = ServiceManager.DbConnection.Execute (command); TypeUniqueId = dbid.ToString (); } private void Update () { HyenaSqliteCommand command = new HyenaSqliteCommand ( @"UPDATE LastfmStations SET Name = ?, Type = ?, Arg = ?, PlayCount = ? WHERE StationID = ?", Name, Type.ToString (), Arg, PlayCount, dbid ); ServiceManager.DbConnection.Execute (command); Station = Type.GetStationFor (Arg); OnUpdated (); } //private bool shuffle; public override void Activate () { base.Activate (); //action_service.GlobalActions ["PreviousAction"].Sensitive = false; // We lazy load the Last.fm connection, so if we're not already connected, do it if (lastfm.Connection.State == ConnectionState.Connected) TuneAndLoad (); else if (lastfm.Connection.State == ConnectionState.Disconnected) lastfm.Connection.Connect (); } private void TuneAndLoad () { ThreadPool.QueueUserWorkItem (delegate { if (ChangeToThisStation ()) { Thread.Sleep (250); // sleep for a bit to try to avoid Last.fm timeouts if (TracksLeft < 2) Refresh (); else HideStatus (); } }); } public override void Deactivate () { //Globals.ActionManager["PreviousAction"].Sensitive = true; } // Last.fm requires you to 'tune' to a station before requesting a track list/playing it public bool ChangeToThisStation () { if (lastfm.Connection.Station == Station) return false; Log.Debug (String.Format ("Tuning Last.fm to {0}", Name), null); SetStatus (Catalog.GetString ("Tuning Last.fm to {0}."), false); StationError error = lastfm.Connection.ChangeStationTo (Station); if (error == StationError.None) { Log.Debug (String.Format ("Successfully tuned Last.fm to {0}", station), null); return true; } else { Log.Debug (String.Format ("Failed to tune Last.fm to {0}", Name), RadioConnection.ErrorMessageFor (error)); SetStatus (String.Format ( // Translators: {0} is an error message sentence from RadioConnection.cs. Catalog.GetString ("Failed to tune in station. {0}"), RadioConnection.ErrorMessageFor (error)), true ); return false; } } public override void SetStatus (string message, bool error) { base.SetStatus (message, error); LastfmSource.SetStatus (status_message, lastfm, error, ConnectionState.Connected); } public void SetStatus (string message, bool error, ConnectionState state) { base.SetStatus (message, error); LastfmSource.SetStatus (status_message, lastfm, error, state); } /*public override void ShowPropertiesDialog () { Editor ed = new Editor (this); ed.RunDialog (); }*/ /*private bool playback_requested = false; public override void StartPlayback () { if (CurrentTrack != null) { ServiceManager.PlayerEngine.OpenPlay (CurrentTrack); } else if (playback_requested == false) { playback_requested = true; Refresh (); } }*/ private int current_track = 0; public TrackInfo CurrentTrack { get { return GetTrack (current_track); } set { int i = track_model.IndexOf (value); if (i != -1) current_track = i; } } #region IBasicPlaybackController bool IBasicPlaybackController.First () { return ((IBasicPlaybackController)this).Next (false); } private bool playback_requested; bool IBasicPlaybackController.Next (bool restart) { TrackInfo next = NextTrack; if (next != null) { ServiceManager.PlayerEngine.OpenPlay (next); } else { playback_requested = true; } return true; } bool IBasicPlaybackController.Previous (bool restart) { return true; } #endregion public TrackInfo NextTrack { get { return GetTrack (current_track + 1); } } private TrackInfo GetTrack (int track_num) { return (track_num > track_model.Count - 1) ? null : track_model[track_num]; } private int TracksLeft { get { int left = track_model.Count - current_track - 1; return (left < 0) ? 0 : left; } } public bool HasDependencies { get { return false; } } private bool refreshing = false; public void Refresh () { lock (this) { if (refreshing || lastfm.Connection.Station != Station) { return; } refreshing = true; } if (TracksLeft == 0) { SetStatus (Catalog.GetString ("Getting new songs for {0}."), false); } ThreadAssist.Spawn (delegate { Media.Playlists.Xspf.Playlist playlist = lastfm.Connection.LoadPlaylistFor (Station); if (playlist != null) { if (playlist.TrackCount == 0) { SetStatus (Catalog.GetString ("No new songs available for {0}."), true); } else { List<TrackInfo> new_tracks = new List<TrackInfo> (); foreach (Media.Playlists.Xspf.Track track in playlist.Tracks) { TrackInfo ti = new LastfmTrackInfo (track, this, track.GetExtendedValue ("trackauth")); new_tracks.Add (ti); lock (track_model) { track_model.Add (ti); } } HideStatus (); ThreadAssist.ProxyToMain (delegate { //OnTrackAdded (null, new_tracks); track_model.Reload (); OnUpdated (); if (playback_requested) { if (this == ServiceManager.PlaybackController.Source ) { ((IBasicPlaybackController)this).Next (false); } playback_requested = false; } }); } } else { SetStatus (Catalog.GetString ("Failed to get new songs for {0}."), true); } refreshing = false; }); } private void OnPlayerEvent (PlayerEventArgs args) { if (((PlayerEventStateChangeArgs)args).Current == PlayerState.Loaded && track_model.Contains (ServiceManager.PlayerEngine.CurrentTrack)) { CurrentTrack = ServiceManager.PlayerEngine.CurrentTrack; lock (track_model) { // Remove all but 5 played or skipped tracks if (current_track > 5) { for (int i = 0; i < (current_track - 5); i++) { track_model.Remove (track_model[0]); } current_track = 5; } // Set all previous tracks as CanPlay = false foreach (TrackInfo track in track_model) { if (track == CurrentTrack) break; if (track.CanPlay) { track.CanPlay = false; } } OnUpdated (); } if (TracksLeft <= 2) { Refresh (); } } } private void HandleConnectionStateChanged (object sender, ConnectionStateChangedArgs args) { UpdateUI (args.State); } private void UpdateUI (ConnectionState state) { if (state == ConnectionState.Connected) { HideStatus (); if (this == ServiceManager.SourceManager.ActiveSource) { TuneAndLoad (); } } else { track_model.Clear (); SetStatus (RadioConnection.MessageFor (state), state != ConnectionState.Connecting, state); OnUpdated (); } } public override string GetStatusText () { return String.Format ( Catalog.GetPluralString ("{0} song played", "{0} songs played", PlayCount), PlayCount ); } public override bool CanRename { get { return true; } } #region ITrackModelSource Implementation public TrackListModel TrackModel { get { return track_model; } } public AlbumListModel AlbumModel { get { return null; } } public ArtistListModel ArtistModel { get { return null; } } public void Reload () { track_model.Reload (); } public void RemoveSelectedTracks () { } public void DeleteSelectedTracks () { throw new Exception ("Should not call DeleteSelectedTracks on StationSource"); } public bool CanAddTracks { get { return false; } } public bool CanRemoveTracks { get { return false; } } public bool CanDeleteTracks { get { return false; } } public bool ConfirmRemoveTracks { get { return false; } } public virtual bool CanRepeat { get { return false; } } public virtual bool CanShuffle { get { return false; } } public bool ShowBrowser { get { return false; } } public bool Indexable { get { return false; } } #endregion #region IUnmapableSource Implementation public bool Unmap () { ServiceManager.DbConnection.Execute (String.Format ( @"DELETE FROM LastfmStations WHERE StationID = '{0}'", dbid )); Parent.RemoveChildSource (this); ServiceManager.SourceManager.RemoveSource (this); return true; } public bool CanUnmap { get { return true; } } public bool ConfirmBeforeUnmap { get { return true; } } #endregion public override void Rename (string newName) { base.Rename (newName); Save (); } public override bool HasProperties { get { return true; } } public static List<StationSource> LoadAll (LastfmSource lastfm, string creator) { List<StationSource> stations = new List<StationSource> (); HyenaSqliteCommand command = new HyenaSqliteCommand ( "SELECT StationID, Name, Type, Arg, PlayCount FROM LastfmStations WHERE Creator = ?", creator ); using (IDataReader reader = ServiceManager.DbConnection.Query (command)) { while (reader.Read ()) { try { stations.Add (new StationSource (lastfm, Convert.ToInt32 (reader[0]), reader[1] as string, reader[2] as string, reader[3] as string, Convert.ToInt32 (reader[4]) )); } catch (Exception e) { Log.Warning ("Error Loading Last.fm Station", e.ToString (), false); } } } // Create some default stations if the user has none if (stations.Count == 0) { stations.Add (new StationSource (lastfm, Catalog.GetString ("Recommended"), "Recommended", creator)); stations.Add (new StationSource (lastfm, Catalog.GetString ("Personal"), "Personal", creator)); stations.Add (new StationSource (lastfm, Catalog.GetString ("Loved"), "Loved", creator)); stations.Add (new StationSource (lastfm, Catalog.GetString ("Banshee Group"), "Group", "Banshee")); stations.Add (new StationSource (lastfm, Catalog.GetString ("Neighbors"), "Neighbor", creator)); stations.Add (new StationSource (lastfm, Catalog.GetString ("Creative Commons"), "Tag", "creative commons")); } return stations; } static StationSource () { if (!ServiceManager.DbConnection.TableExists ("LastfmStations")) { ServiceManager.DbConnection.Execute (@" CREATE TABLE LastfmStations ( StationID INTEGER PRIMARY KEY, Creator STRING NOT NULL, Name STRING NOT NULL, Type STRING NOT NULL, Arg STRING NOT NULL, PlayCount INTEGER NOT NULL ) "); } else { try { ServiceManager.DbConnection.Query<int> ("SELECT PlayCount FROM LastfmStations LIMIT 1"); } catch { Log.Debug ("Adding new database column", "Table: LastfmStations, Column: PlayCount INTEGER"); ServiceManager.DbConnection.Execute ("ALTER TABLE LastfmStations ADD PlayCount INTEGER"); ServiceManager.DbConnection.Execute ("UPDATE LastfmStations SET PlayCount = 0"); } } } } }
// 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.AzureStack.Management.Fabric.Admin { using Microsoft.AzureStack; using Microsoft.AzureStack.Management; using Microsoft.AzureStack.Management.Fabric; 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> /// ComputeFabricOperations operations. /// </summary> internal partial class ComputeFabricOperations : IServiceOperations<FabricAdminClient>, IComputeFabricOperations { /// <summary> /// Initializes a new instance of the ComputeFabricOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ComputeFabricOperations(FabricAdminClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the FabricAdminClient /// </summary> public FabricAdminClient Client { get; private set; } /// <summary> /// Get the status of a compute fabric operation. /// </summary> /// <param name='location'> /// Location of the resource. /// </param> /// <param name='provider'> /// Name of the provider. /// </param> /// <param name='computeOperationResult'> /// Id of a compute fabric operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<OperationStatus>> GetWithHttpMessagesAsync(string location, string provider, string computeOperationResult, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (provider == null) { throw new ValidationException(ValidationRules.CannotBeNull, "provider"); } if (computeOperationResult == null) { throw new ValidationException(ValidationRules.CannotBeNull, "computeOperationResult"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("location", location); tracingParameters.Add("provider", provider); tracingParameters.Add("computeOperationResult", computeOperationResult); 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/System.{location}/providers/{provider}/fabricLocations/{location}/computeOperationResults/{computeOperationResult}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); _url = _url.Replace("{provider}", System.Uri.EscapeDataString(provider)); _url = _url.Replace("{computeOperationResult}", System.Uri.EscapeDataString(computeOperationResult)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<OperationStatus>(); _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 == 202) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<OperationStatus>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.IO.Tests { public partial class PathTests : PathTestsBase { [Fact] public void GetDirectoryName_EmptyReturnsNull() { // In NetFX this throws argument exception Assert.Null(Path.GetDirectoryName(string.Empty)); } [Theory, MemberData(nameof(TestData_Spaces))] public void GetDirectoryName_Spaces(string path) { if (PlatformDetection.IsWindows) { // In Windows spaces are eaten by Win32, making them effectively empty Assert.Null(Path.GetDirectoryName(path)); } else { Assert.Empty(Path.GetDirectoryName(path)); } } [Theory, MemberData(nameof(TestData_Spaces))] public void GetDirectoryName_Span_Spaces(string path) { PathAssert.Empty(Path.GetDirectoryName(path.AsSpan())); } [Theory, MemberData(nameof(TestData_EmbeddedNull)), MemberData(nameof(TestData_ControlChars)), MemberData(nameof(TestData_UnicodeWhiteSpace))] public void GetDirectoryName_NetFxInvalid(string path) { Assert.Empty(Path.GetDirectoryName(path)); Assert.Equal(path, Path.GetDirectoryName(Path.Combine(path, path))); PathAssert.Empty(Path.GetDirectoryName(path.AsSpan())); PathAssert.Equal(path, new string(Path.GetDirectoryName(Path.Combine(path, path).AsSpan()))); } [Theory, MemberData(nameof(TestData_GetDirectoryName))] public void GetDirectoryName_Span(string path, string expected) { PathAssert.Equal(expected ?? ReadOnlySpan<char>.Empty, Path.GetDirectoryName(path.AsSpan())); } [Fact] public void GetDirectoryName_Span_CurrentDirectory() { string curDir = Directory.GetCurrentDirectory(); PathAssert.Equal(curDir, Path.GetDirectoryName(Path.Combine(curDir, "baz").AsSpan())); PathAssert.Empty(Path.GetDirectoryName(Path.GetPathRoot(curDir).AsSpan())); } [Theory, InlineData(@" C:\dir/baz", @" C:\dir"), InlineData(@" C:\dir/baz", @" C:\dir")] public void GetDirectoryName_SkipSpaces(string path, string expected) { // We no longer trim leading spaces for any path Assert.Equal(expected, Path.GetDirectoryName(path)); } [Theory, MemberData(nameof(TestData_GetExtension))] public void GetExtension_Span(string path, string expected) { PathAssert.Equal(expected, Path.GetExtension(path.AsSpan())); Assert.Equal(!string.IsNullOrEmpty(expected), Path.HasExtension(path.AsSpan())); } [Theory, MemberData(nameof(TestData_GetFileName))] public void GetFileName_Span(string path, string expected) { PathAssert.Equal(expected, Path.GetFileName(path.AsSpan())); } public static IEnumerable<object[]> TestData_GetFileName_Volume() { yield return new object[] { ":", ":" }; yield return new object[] { ".:", ".:" }; yield return new object[] { ".:.", ".:." }; // Not a valid drive letter yield return new object[] { "file:", "file:" }; yield return new object[] { ":file", ":file" }; yield return new object[] { "file:exe", "file:exe" }; yield return new object[] { Path.Combine("baz", "file:exe"), "file:exe" }; yield return new object[] { Path.Combine("bar", "baz", "file:exe"), "file:exe" }; } [Theory, MemberData(nameof(TestData_GetFileName_Volume))] public void GetFileName_Volume(string path, string expected) { // We used to break on ':' on Windows. This is a valid file name character for alternate data streams. // Additionally the character can show up on unix volumes mounted to Windows. Assert.Equal(expected, Path.GetFileName(path)); PathAssert.Equal(expected, Path.GetFileName(path.AsSpan())); } [Theory, MemberData(nameof(TestData_GetFileNameWithoutExtension))] public void GetFileNameWithoutExtension_Span(string path, string expected) { PathAssert.Equal(expected, Path.GetFileNameWithoutExtension(path.AsSpan())); } [Fact] public void GetPathRoot_Empty() { Assert.Null(Path.GetPathRoot(string.Empty)); } [Fact] public void GetPathRoot_Empty_Span() { PathAssert.Empty(Path.GetPathRoot(ReadOnlySpan<char>.Empty)); } [Theory, InlineData(nameof(TestData_Spaces)), InlineData(nameof(TestData_ControlChars)), InlineData(nameof(TestData_EmbeddedNull)), InlineData(nameof(TestData_InvalidDriveLetters)), InlineData(nameof(TestData_UnicodeWhiteSpace)), InlineData(nameof(TestData_EmptyString))] public void IsPathRooted_NegativeCases(string path) { Assert.False(Path.IsPathRooted(path)); Assert.False(Path.IsPathRooted(path.AsSpan())); } [Fact] public void GetInvalidPathChars() { Assert.All(Path.GetInvalidPathChars(), c => { string bad = c.ToString(); Assert.Equal(bad + ".ok", Path.ChangeExtension(bad, "ok")); Assert.Equal(bad + Path.DirectorySeparatorChar + "ok", Path.Combine(bad, "ok")); Assert.Equal("ok" + Path.DirectorySeparatorChar + "ok" + Path.DirectorySeparatorChar + bad, Path.Combine("ok", "ok", bad)); Assert.Equal("ok" + Path.DirectorySeparatorChar + "ok" + Path.DirectorySeparatorChar + bad + Path.DirectorySeparatorChar + "ok", Path.Combine("ok", "ok", bad, "ok")); Assert.Equal(bad + Path.DirectorySeparatorChar + bad + Path.DirectorySeparatorChar + bad + Path.DirectorySeparatorChar + bad + Path.DirectorySeparatorChar + bad, Path.Combine(bad, bad, bad, bad, bad)); Assert.Equal("", Path.GetDirectoryName(bad)); Assert.Equal(string.Empty, Path.GetExtension(bad)); Assert.Equal(bad, Path.GetFileName(bad)); Assert.Equal(bad, Path.GetFileNameWithoutExtension(bad)); if (bad[0] == '\0') { Assert.Throws<ArgumentException>("path", () => Path.GetFullPath(bad)); } else { Assert.True(Path.GetFullPath(bad).EndsWith(bad)); } Assert.Equal(string.Empty, Path.GetPathRoot(bad)); Assert.False(Path.IsPathRooted(bad)); }); } [Fact] public void GetInvalidPathChars_Span() { Assert.All(Path.GetInvalidPathChars(), c => { string bad = c.ToString(); Assert.Equal(string.Empty, new string(Path.GetDirectoryName(bad.AsSpan()))); Assert.Equal(string.Empty, new string(Path.GetExtension(bad.AsSpan()))); Assert.Equal(bad, new string(Path.GetFileName(bad.AsSpan()))); Assert.Equal(bad, new string(Path.GetFileNameWithoutExtension(bad.AsSpan()))); Assert.Equal(string.Empty, new string(Path.GetPathRoot(bad.AsSpan()))); Assert.False(Path.IsPathRooted(bad.AsSpan())); }); } [Theory, InlineData("http://www.microsoft.com"), InlineData("file://somefile")] public void GetFullPath_URIsAsFileNames(string uriAsFileName) { // URIs are valid filenames, though the multiple slashes will be consolidated in GetFullPath Assert.Equal( Path.Combine(Directory.GetCurrentDirectory(), uriAsFileName.Replace("//", Path.DirectorySeparatorChar.ToString())), Path.GetFullPath(uriAsFileName)); } [Theory, MemberData(nameof(TestData_NonDriveColonPaths))] public void GetFullPath_NowSupportedColons(string path) { // Used to throw on Windows, now should never throw Path.GetFullPath(path); } [Theory, MemberData(nameof(TestData_InvalidUnc))] public static void GetFullPath_UNC_Invalid(string path) { // These UNCs used to throw on Windows Path.GetFullPath(path); } [Theory, MemberData(nameof(TestData_Wildcards)), MemberData(nameof(TestData_ExtendedWildcards))] public void GetFullPath_Wildcards(string wildcard) { string path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + wildcard + "ing"); Assert.Equal(path, Path.GetFullPath(path)); } public static TheoryData<string, string, string> GetFullPathBasePath_ArgumentNullException => new TheoryData<string, string, string> { { @"", null, "basePath" }, { @"tmp",null, "basePath" }, { @"\home", null, "basePath"}, { null, @"foo\bar", "path"}, { null, @"foo\bar", "path"}, }; [Theory, MemberData(nameof(GetFullPathBasePath_ArgumentNullException))] public static void GetFullPath_BasePath_NullInput(string path, string basePath, string paramName) { Assert.Throws<ArgumentNullException>(paramName, () => Path.GetFullPath(path, basePath)); } public static TheoryData<string, string, string> GetFullPathBasePath_ArgumentException => new TheoryData<string, string, string> { { @"", @"foo\bar", "basePath"}, { @"tmp", @"foo\bar", "basePath"}, { @"\home", @"foo\bar", "basePath"}, }; [Theory, MemberData(nameof(GetFullPathBasePath_ArgumentException))] public static void GetFullPath_BasePath_Input(string path, string basePath, string paramName) { Assert.Throws<ArgumentException>(paramName, () => Path.GetFullPath(path, basePath)); } } }
#if UNITY_EDITOR using UnityEngine; using System; using System.Collections; using System.Collections.Generic; /// <summary> /// Represents a circular doubly linked list. /// </summary> /// <typeparam name="T">Specifies the element type of the linked list.</typeparam> public sealed class CircularLinkedList<T> : ICollection<T>, IEnumerable<T> { private CircularLinkedListNode<T> m_rFirstNode = null; private CircularLinkedListNode<T> m_rLastNode = null; int m_iCountNode = 0; readonly IEqualityComparer<T> m_rComparer; /// <summary> /// Initializes a new instance of <see cref="CircularLinkedList"/> /// </summary> public CircularLinkedList( ) : this(null, EqualityComparer<T>.Default) { } /// <summary> /// Initializes a new instance of <see cref="CircularLinkedList"/> /// </summary> /// <param name="collection">Collection of objects that will be added to linked list</param> public CircularLinkedList(IEnumerable<T> collection) : this(collection, EqualityComparer<T>.Default) { } /// <summary> /// Initializes a new instance of <see cref="CircularLinkedList"/> /// </summary> /// <param name="a_rComparer">Comparer used for item comparison</param> /// <exception cref="ArgumentNullException">comparer is null</exception> public CircularLinkedList(IEqualityComparer<T> a_rComparer) : this(null, a_rComparer) { } /// <summary> /// Initializes a new instance of <see cref="CircularLinkedList"/> /// </summary> /// <param name="a_rCollection">Collection of objects that will be added to linked list</param> /// <param name="a_rComparer">Comparer used for item comparison</param> public CircularLinkedList(IEnumerable<T> a_rCollection, IEqualityComparer<T> a_rComparer) { if (a_rComparer == null) throw new ArgumentNullException("comparer"); this.m_rComparer = a_rComparer; if (a_rCollection != null) { foreach (T item in a_rCollection) this.AddLast(item); } } /// <summary> /// Gets Tail node. Returns NULL if no tail node found /// </summary> public CircularLinkedListNode<T> Last { get { return m_rLastNode; } } /// <summary> /// Gets the head node. Returns NULL if no node found /// </summary> public CircularLinkedListNode<T> First { get { return m_rFirstNode; } } /// <summary> /// Gets total number of items in the list /// </summary> public int Count { get { return m_iCountNode; } } /// <summary> /// Gets the item at the current index /// </summary> /// <param name="a_iIndex">Zero-based index</param> /// <exception cref="ArgumentOutOfRangeException">index is out of range</exception> public CircularLinkedListNode<T> this[int a_iIndex ] { get { if (a_iIndex >= m_iCountNode || a_iIndex < 0) throw new ArgumentOutOfRangeException("index"); else { CircularLinkedListNode<T> rNode = this.m_rFirstNode; for (int i = 0; i < a_iIndex; i++) rNode = rNode.Next; return rNode; } } } /// <summary> /// Add a new item to the end of the list /// </summary> /// <param name="a_rItem">Item to be added</param> public void AddLast(T a_rItem) { // if head is null, then this will be the first item if (m_rFirstNode == null) this.AddFirstItem(a_rItem); else { CircularLinkedListNode<T> oNewNode = new CircularLinkedListNode<T>(a_rItem); m_rLastNode.Next = oNewNode; oNewNode.Next = m_rFirstNode; oNewNode.Previous = m_rLastNode; m_rLastNode = oNewNode; m_rFirstNode.Previous = m_rLastNode; } ++m_iCountNode; } void AddFirstItem(T a_rItem) { m_rFirstNode = new CircularLinkedListNode<T>(a_rItem); m_rLastNode = m_rFirstNode; m_rFirstNode.Next = m_rLastNode; m_rFirstNode.Previous = m_rLastNode; } /// <summary> /// Adds item to the last /// </summary> /// <param name="a_rItem">Item to be added</param> public void AddFirst(T a_rItem) { if (m_rFirstNode == null) this.AddFirstItem(a_rItem); else { CircularLinkedListNode<T> oNewNode = new CircularLinkedListNode<T>(a_rItem); m_rFirstNode.Previous = oNewNode; oNewNode.Previous = m_rLastNode; oNewNode.Next = m_rFirstNode; m_rLastNode.Next = oNewNode; m_rFirstNode = oNewNode; } ++m_iCountNode; } /// <summary> /// Adds the specified item after the specified existing node in the list. /// </summary> /// <param name="a_rNode">Existing node after which new item will be inserted</param> /// <param name="a_rItem">New item to be inserted</param> /// <exception cref="ArgumentNullException"><paramref name="a_rNode"/> is NULL</exception> /// <exception cref="InvalidOperationException"><paramref name="node"/> doesn't belongs to list</exception> public void AddAfter(CircularLinkedListNode<T> a_rNode, T a_rItem) { if (a_rNode == null) throw new ArgumentNullException("node"); // ensuring the supplied node belongs to this list bool bNodeBelongsToList = this.FindNode( a_rNode ); if ( bNodeBelongsToList == false ) throw new InvalidOperationException("Node doesn't belongs to this list"); CircularLinkedListNode<T> oNewNode = new CircularLinkedListNode<T>(a_rItem); oNewNode.Next = a_rNode.Next; a_rNode.Next.Previous = oNewNode; oNewNode.Previous = a_rNode; a_rNode.Next = oNewNode; // if the node adding is tail node, then repointing tail node if (a_rNode == m_rLastNode) m_rLastNode = oNewNode; ++m_iCountNode; } /// <summary> /// Adds the new item after the specified existing item in the list. /// </summary> /// <param name="a_rExistingItem">Existing item after which new item will be added</param> /// <param name="a_rNewItem">New item to be added to the list</param> /// <exception cref="ArgumentException"><paramref name="existingItem"/> doesn't exist in the list</exception> public void AddAfter(T a_rExistingItem, T a_rNewItem) { // finding a node for the existing item CircularLinkedListNode<T> rNode = this.Find(a_rExistingItem); if (rNode == null) throw new ArgumentException("existingItem doesn't exist in the list"); this.AddAfter(rNode, a_rNewItem); } /// <summary> /// Adds the specified item before the specified existing node in the list. /// </summary> /// <param name="a_rNode">Existing node before which new item will be inserted</param> /// <param name="a_rItem">New item to be inserted</param> /// <exception cref="ArgumentNullException"><paramref name="a_rNode"/> is NULL</exception> /// <exception cref="InvalidOperationException"><paramref name="node"/> doesn't belongs to list</exception> public void AddBefore(CircularLinkedListNode<T> a_rNode, T a_rItem) { if (a_rNode == null) throw new ArgumentNullException("node"); // ensuring the supplied node belongs to this list bool bNodeBelongsToList = this.FindNode( a_rNode ); if ( bNodeBelongsToList == false ) throw new InvalidOperationException("Node doesn't belongs to this list"); CircularLinkedListNode<T> oNewNode = new CircularLinkedListNode<T>(a_rItem); a_rNode.Previous.Next = oNewNode; oNewNode.Previous = a_rNode.Previous; oNewNode.Next = a_rNode; a_rNode.Previous = oNewNode; // if the node adding is head node, then repointing head node if (a_rNode == m_rFirstNode) m_rFirstNode = oNewNode; ++m_iCountNode; } /// <summary> /// Adds the new item before the specified existing item in the list. /// </summary> /// <param name="a_rExistingItem">Existing item before which new item will be added</param> /// <param name="a_rNewItem">New item to be added to the list</param> /// <exception cref="ArgumentException"><paramref name="existingItem"/> doesn't exist in the list</exception> public void AddBefore(T a_rExistingItem, T a_rNewItem) { // finding a node for the existing item CircularLinkedListNode<T> rNode = this.Find(a_rExistingItem); if (rNode == null) throw new ArgumentException("existingItem doesn't exist in the list"); this.AddBefore(rNode, a_rNewItem); } /// <summary> /// Finds the supplied item and returns the first node which contains item. Returns NULL if item not found /// </summary> /// <param name="a_rItem">Item to search</param> /// <returns><see cref="CircularLinkedListNode&lt;T&gt;"/> instance or NULL</returns> public CircularLinkedListNode<T> Find(T a_rItem) { CircularLinkedListNode<T> rNode = FindFirstNodeWithValue(m_rFirstNode, a_rItem); return rNode; } /// <summary> /// Removes the first occurance of the supplied item /// </summary> /// <param name="a_rItem">Item to be removed</param> /// <returns>TRUE if removed, else FALSE</returns> public bool Remove(T a_rItem) { // finding the first occurance of this item CircularLinkedListNode<T> rNodeToRemove = this.Find(a_rItem); if (rNodeToRemove != null) return this.RemoveNode(rNodeToRemove); return false; } bool RemoveNode(CircularLinkedListNode<T> a_rNodeToRemove) { CircularLinkedListNode<T> rPreviousNode = a_rNodeToRemove.Previous; rPreviousNode.Next = a_rNodeToRemove.Next; a_rNodeToRemove.Next.Previous = a_rNodeToRemove.Previous; // if this is head, we need to update the head reference if (m_rFirstNode == a_rNodeToRemove) m_rFirstNode = a_rNodeToRemove.Next; else if (m_rLastNode == a_rNodeToRemove) m_rLastNode = m_rLastNode.Previous; --m_iCountNode; return true; } /// <summary> /// Removes all occurances of the supplied item /// </summary> /// <param name="a_rItem">Item to be removed</param> public void RemoveAll(T a_rItem) { bool bRemoved = false; do { bRemoved = this.Remove(a_rItem); } while (bRemoved); } /// <summary> /// Clears the list /// </summary> public void Clear() { m_rFirstNode = null; m_rLastNode = null; m_iCountNode = 0; } /// <summary> /// Removes head /// </summary> /// <returns>TRUE if successfully removed, else FALSE</returns> public bool RemoveFirst() { return this.RemoveNode(m_rFirstNode); } /// <summary> /// Removes tail /// </summary> /// <returns>TRUE if successfully removed, else FALSE</returns> public bool RemoveLast() { return this.RemoveNode(m_rLastNode); } bool FindNode( CircularLinkedListNode<T> a_rNode ) { CircularLinkedListNode<T> rNode = m_rFirstNode; do { if( rNode == a_rNode ) { return true; } rNode = rNode.Next; } while( rNode != m_rFirstNode ); return false; } CircularLinkedListNode<T> FindFirstNodeWithValue( CircularLinkedListNode<T> a_rNode, T a_rValueToCompare) { CircularLinkedListNode<T> rResult = null; if (m_rComparer.Equals(a_rNode.Value, a_rValueToCompare)) rResult = a_rNode; else if (rResult == null && a_rNode.Next != m_rFirstNode) rResult = FindFirstNodeWithValue(a_rNode.Next, a_rValueToCompare); return rResult; } /// <summary> /// Gets a forward enumerator /// </summary> /// <returns></returns> public IEnumerator<T> GetEnumerator() { CircularLinkedListNode<T> rCurrent = m_rFirstNode; if (rCurrent != null) { do { yield return rCurrent.Value; rCurrent = rCurrent.Next; } while (rCurrent != m_rFirstNode); } } /// <summary> /// Gets a reverse enumerator /// </summary> /// <returns></returns> public IEnumerator<T> GetReverseEnumerator() { CircularLinkedListNode<T> rCurrent = m_rLastNode; if (rCurrent != null) { do { yield return rCurrent.Value; rCurrent = rCurrent.Previous; } while (rCurrent != m_rLastNode); } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Determines whether a value is in the list. /// </summary> /// <param name="a_rItem">Item to check</param> /// <returns>TRUE if item exist, else FALSE</returns> public bool Contains(T a_rItem) { return Find(a_rItem) != null; } public void CopyTo(T[] a_rArray, int a_iArrayIndex) { if (a_rArray == null) throw new ArgumentNullException("array"); if (a_iArrayIndex < 0 || a_iArrayIndex > a_rArray.Length) throw new ArgumentOutOfRangeException("arrayIndex"); CircularLinkedListNode<T> rNode = this.m_rFirstNode; do { a_rArray[a_iArrayIndex++] = rNode.Value; rNode = rNode.Next; } while (rNode != m_rFirstNode); } bool ICollection<T>.IsReadOnly { get { return false; } } void ICollection<T>.Add(T a_rItem) { this.AddLast(a_rItem); } } #endif
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System; using System.Runtime; using System.ServiceModel; class ContextChannelRequestContext : RequestContext { ContextProtocol contextProtocol; TimeSpan defaultSendTimeout; RequestContext innerContext; public ContextChannelRequestContext(RequestContext innerContext, ContextProtocol contextProtocol, TimeSpan defaultSendTimeout) { if (innerContext == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("innerContext"); } if (contextProtocol == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contextProtocol"); } this.innerContext = innerContext; this.contextProtocol = contextProtocol; this.defaultSendTimeout = defaultSendTimeout; } public override Message RequestMessage { get { return this.innerContext.RequestMessage; } } public override void Abort() { this.innerContext.Abort(); } public override IAsyncResult BeginReply(Message message, TimeSpan timeout, AsyncCallback callback, object state) { return new ReplyAsyncResult(message, this, timeout, callback, state); } public override IAsyncResult BeginReply(Message message, AsyncCallback callback, object state) { return this.BeginReply(message, this.defaultSendTimeout, callback, state); } public override void Close(TimeSpan timeout) { this.innerContext.Close(timeout); } public override void Close() { this.innerContext.Close(); } public override void EndReply(IAsyncResult result) { ReplyAsyncResult.End(result); } public override void Reply(Message message, TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); Message replyMessage = message; if (message != null) { this.contextProtocol.OnOutgoingMessage(message, this); CorrelationCallbackMessageProperty callback; if (CorrelationCallbackMessageProperty.TryGet(message, out callback)) { ContextExchangeCorrelationHelper.AddOutgoingCorrelationCallbackData(callback, message, false); if (callback.IsFullyDefined) { replyMessage = callback.FinalizeCorrelation(message, timeoutHelper.RemainingTime()); // we are done finalizing correlation, removing the messageproperty since we do not need it anymore replyMessage.Properties.Remove(CorrelationCallbackMessageProperty.Name); } } } try { this.innerContext.Reply(replyMessage, timeoutHelper.RemainingTime()); } finally { if (message != null && !object.ReferenceEquals(message, replyMessage)) { replyMessage.Close(); } } } public override void Reply(Message message) { this.Reply(message, this.defaultSendTimeout); } class ReplyAsyncResult : AsyncResult { static AsyncCallback onFinalizeCorrelation = Fx.ThunkCallback(new AsyncCallback(OnFinalizeCorrelationCompletedCallback)); static AsyncCallback onReply = Fx.ThunkCallback(new AsyncCallback(OnReplyCompletedCallback)); ContextChannelRequestContext context; CorrelationCallbackMessageProperty correlationCallback; Message message; Message replyMessage; TimeoutHelper timeoutHelper; public ReplyAsyncResult(Message message, ContextChannelRequestContext context, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state) { this.context = context; this.message = this.replyMessage = message; this.timeoutHelper = new TimeoutHelper(timeout); bool shouldReply = true; if (message != null) { this.context.contextProtocol.OnOutgoingMessage(message, this.context); if (CorrelationCallbackMessageProperty.TryGet(message, out this.correlationCallback)) { ContextExchangeCorrelationHelper.AddOutgoingCorrelationCallbackData(this.correlationCallback, message, false); if (this.correlationCallback.IsFullyDefined) { IAsyncResult result = correlationCallback.BeginFinalizeCorrelation(this.message, this.timeoutHelper.RemainingTime(), onFinalizeCorrelation, this); if (result.CompletedSynchronously) { if (OnFinalizeCorrelationCompleted(result)) { base.Complete(true); } } shouldReply = false; } } } if (shouldReply) { IAsyncResult result = this.context.innerContext.BeginReply(this.message, this.timeoutHelper.RemainingTime(), onReply, this); if (result.CompletedSynchronously) { OnReplyCompleted(result); base.Complete(true); } } } public static void End(IAsyncResult result) { AsyncResult.End<ReplyAsyncResult>(result); } static void OnFinalizeCorrelationCompletedCallback(IAsyncResult result) { if (result.CompletedSynchronously) { return; } ReplyAsyncResult thisPtr = (ReplyAsyncResult)result.AsyncState; Exception completionException = null; bool completeSelf; try { completeSelf = thisPtr.OnFinalizeCorrelationCompleted(result); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } completionException = e; completeSelf = true; } if (completeSelf) { thisPtr.Complete(false, completionException); } } static void OnReplyCompletedCallback(IAsyncResult result) { if (result.CompletedSynchronously) { return; } ReplyAsyncResult thisPtr = (ReplyAsyncResult)result.AsyncState; Exception completionException = null; try { thisPtr.OnReplyCompleted(result); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } completionException = e; } thisPtr.Complete(false, completionException); } bool OnFinalizeCorrelationCompleted(IAsyncResult result) { this.replyMessage = this.correlationCallback.EndFinalizeCorrelation(result); bool throwing = true; IAsyncResult replyResult; try { replyResult = this.context.innerContext.BeginReply(this.replyMessage, this.timeoutHelper.RemainingTime(), onReply, this); throwing = false; } finally { if (throwing) { if (this.message != null && !object.ReferenceEquals(this.message, this.replyMessage)) { this.replyMessage.Close(); } } } if (replyResult.CompletedSynchronously) { OnReplyCompleted(replyResult); return true; } return false; } void OnReplyCompleted(IAsyncResult result) { try { this.context.innerContext.EndReply(result); } finally { if (this.message != null && !object.ReferenceEquals(this.message, this.replyMessage)) { this.replyMessage.Close(); } } } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.ComponentModel.Composition; using QuantConnect.Configuration; using QuantConnect.Data.Auxiliary; using QuantConnect.Interfaces; using QuantConnect.Lean.Engine.Alpha; using QuantConnect.Lean.Engine.DataFeeds; using QuantConnect.Lean.Engine.RealTime; using QuantConnect.Lean.Engine.Results; using QuantConnect.Lean.Engine.Setup; using QuantConnect.Lean.Engine.TransactionHandlers; using QuantConnect.Logging; using QuantConnect.Util; namespace QuantConnect.Lean.Engine { /// <summary> /// Provides a container for the algorithm specific handlers /// </summary> public class LeanEngineAlgorithmHandlers : IDisposable { /// <summary> /// Gets the result handler used to communicate results from the algorithm /// </summary> public IResultHandler Results { get; } /// <summary> /// Gets the setup handler used to initialize the algorithm state /// </summary> public ISetupHandler Setup { get; } /// <summary> /// Gets the data feed handler used to provide data to the algorithm /// </summary> public IDataFeed DataFeed { get; } /// <summary> /// Gets the transaction handler used to process orders from the algorithm /// </summary> public ITransactionHandler Transactions { get; } /// <summary> /// Gets the real time handler used to process real time events /// </summary> public IRealTimeHandler RealTime { get; } /// <summary> /// Gets the map file provider used as a map file source for the data feed /// </summary> public IMapFileProvider MapFileProvider { get; } /// <summary> /// Gets the map file provider used as a map file source for the data feed /// </summary> public IFactorFileProvider FactorFileProvider { get; } /// <summary> /// Gets the data file provider used to retrieve security data if it is not on the file system /// </summary> public IDataProvider DataProvider { get; } /// <summary> /// Gets the alpha handler used to process algorithm generated insights /// </summary> public IAlphaHandler Alphas { get; } /// <summary> /// Gets the object store used for persistence /// </summary> public IObjectStore ObjectStore { get; } /// <summary> /// Entity in charge of handling data permissions /// </summary> public IDataPermissionManager DataPermissionsManager { get; } /// <summary> /// Initializes a new instance of the <see cref="LeanEngineAlgorithmHandlers"/> class from the specified handlers /// </summary> /// <param name="results">The result handler for communicating results from the algorithm</param> /// <param name="setup">The setup handler used to initialize algorithm state</param> /// <param name="dataFeed">The data feed handler used to pump data to the algorithm</param> /// <param name="transactions">The transaction handler used to process orders from the algorithm</param> /// <param name="realTime">The real time handler used to process real time events</param> /// <param name="mapFileProvider">The map file provider used to retrieve map files for the data feed</param> /// <param name="factorFileProvider">Map file provider used as a map file source for the data feed</param> /// <param name="dataProvider">file provider used to retrieve security data if it is not on the file system</param> /// <param name="alphas">The alpha handler used to process generated insights</param> /// <param name="objectStore">The object store used for persistence</param> /// <param name="dataPermissionsManager">The data permission manager to use</param> public LeanEngineAlgorithmHandlers(IResultHandler results, ISetupHandler setup, IDataFeed dataFeed, ITransactionHandler transactions, IRealTimeHandler realTime, IMapFileProvider mapFileProvider, IFactorFileProvider factorFileProvider, IDataProvider dataProvider, IAlphaHandler alphas, IObjectStore objectStore, IDataPermissionManager dataPermissionsManager ) { if (results == null) { throw new ArgumentNullException(nameof(results)); } if (setup == null) { throw new ArgumentNullException(nameof(setup)); } if (dataFeed == null) { throw new ArgumentNullException(nameof(dataFeed)); } if (transactions == null) { throw new ArgumentNullException(nameof(transactions)); } if (realTime == null) { throw new ArgumentNullException(nameof(realTime)); } if (mapFileProvider == null) { throw new ArgumentNullException(nameof(mapFileProvider)); } if (factorFileProvider == null) { throw new ArgumentNullException(nameof(factorFileProvider)); } if (dataProvider == null) { throw new ArgumentNullException(nameof(dataProvider)); } if (alphas == null) { throw new ArgumentNullException(nameof(alphas)); } if (objectStore == null) { throw new ArgumentNullException(nameof(objectStore)); } if (dataPermissionsManager == null) { throw new ArgumentNullException(nameof(dataPermissionsManager)); } Results = results; Setup = setup; DataFeed = dataFeed; Transactions = transactions; RealTime = realTime; MapFileProvider = mapFileProvider; FactorFileProvider = factorFileProvider; DataProvider = dataProvider; Alphas = alphas; ObjectStore = objectStore; DataPermissionsManager = dataPermissionsManager; } /// <summary> /// Creates a new instance of the <see cref="LeanEngineAlgorithmHandlers"/> class from the specified composer using type names from configuration /// </summary> /// <param name="composer">The composer instance to obtain implementations from</param> /// <returns>A fully hydrates <see cref="LeanEngineSystemHandlers"/> instance.</returns> /// <exception cref="CompositionException">Throws a CompositionException during failure to load</exception> public static LeanEngineAlgorithmHandlers FromConfiguration(Composer composer) { var setupHandlerTypeName = Config.Get("setup-handler", "ConsoleSetupHandler"); var transactionHandlerTypeName = Config.Get("transaction-handler", "BacktestingTransactionHandler"); var realTimeHandlerTypeName = Config.Get("real-time-handler", "BacktestingRealTimeHandler"); var dataFeedHandlerTypeName = Config.Get("data-feed-handler", "FileSystemDataFeed"); var resultHandlerTypeName = Config.Get("result-handler", "BacktestingResultHandler"); var mapFileProviderTypeName = Config.Get("map-file-provider", "LocalDiskMapFileProvider"); var factorFileProviderTypeName = Config.Get("factor-file-provider", "LocalDiskFactorFileProvider"); var dataProviderTypeName = Config.Get("data-provider", "DefaultDataProvider"); var alphaHandlerTypeName = Config.Get("alpha-handler", "DefaultAlphaHandler"); var objectStoreTypeName = Config.Get("object-store", "LocalObjectStore"); var dataPermissionManager = Config.Get("data-permission-manager", "DataPermissionManager"); var result = new LeanEngineAlgorithmHandlers( composer.GetExportedValueByTypeName<IResultHandler>(resultHandlerTypeName), composer.GetExportedValueByTypeName<ISetupHandler>(setupHandlerTypeName), composer.GetExportedValueByTypeName<IDataFeed>(dataFeedHandlerTypeName), composer.GetExportedValueByTypeName<ITransactionHandler>(transactionHandlerTypeName), composer.GetExportedValueByTypeName<IRealTimeHandler>(realTimeHandlerTypeName), composer.GetExportedValueByTypeName<IMapFileProvider>(mapFileProviderTypeName), composer.GetExportedValueByTypeName<IFactorFileProvider>(factorFileProviderTypeName), composer.GetExportedValueByTypeName<IDataProvider>(dataProviderTypeName), composer.GetExportedValueByTypeName<IAlphaHandler>(alphaHandlerTypeName), composer.GetExportedValueByTypeName<IObjectStore>(objectStoreTypeName), composer.GetExportedValueByTypeName<IDataPermissionManager>(dataPermissionManager) ); result.FactorFileProvider.Initialize(result.MapFileProvider, result.DataProvider); result.MapFileProvider.Initialize(result.DataProvider); if (result.DataProvider is ApiDataProvider && (result.FactorFileProvider is not LocalZipFactorFileProvider || result.MapFileProvider is not LocalZipMapFileProvider)) { throw new ArgumentException($"The {typeof(ApiDataProvider)} can only be used with {typeof(LocalZipFactorFileProvider)}" + $" and {typeof(LocalZipMapFileProvider)}, please update 'config.json'"); } return result; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <filterpriority>2</filterpriority> public void Dispose() { Log.Trace("LeanEngineAlgorithmHandlers.Dispose(): start..."); Setup.DisposeSafely(); ObjectStore.DisposeSafely(); Log.Trace("LeanEngineAlgorithmHandlers.Dispose(): Disposed of algorithm handlers."); } } }
/* * 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.Linq; using System.Net; using System.Reflection; using System.Text.RegularExpressions; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Server.Base; using OpenSim.Services.Connectors.InstantMessage; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using FriendInfo = OpenSim.Services.Interfaces.FriendInfo; using OpenSim.Services.Connectors.Hypergrid; namespace OpenSim.Services.LLLoginService { public class LLLoginService : ILoginService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly string LogHeader = "[LLOGIN SERVICE]"; private static bool Initialized = false; protected IUserAccountService m_UserAccountService; protected IGridUserService m_GridUserService; protected IAuthenticationService m_AuthenticationService; protected IInventoryService m_InventoryService; protected IInventoryService m_HGInventoryService; protected IGridService m_GridService; protected IPresenceService m_PresenceService; protected ISimulationService m_LocalSimulationService; protected ISimulationService m_RemoteSimulationService; protected ILibraryService m_LibraryService; protected IFriendsService m_FriendsService; protected IAvatarService m_AvatarService; protected IUserAgentService m_UserAgentService; protected GatekeeperServiceConnector m_GatekeeperConnector; protected string m_DefaultRegionName; protected string m_WelcomeMessage; protected bool m_RequireInventory; protected int m_MinLoginLevel; protected string m_GatekeeperURL; protected bool m_AllowRemoteSetLoginLevel; protected string m_MapTileURL; protected string m_ProfileURL; protected string m_OpenIDURL; protected string m_SearchURL; protected string m_Currency; protected string m_ClassifiedFee; protected int m_MaxAgentGroups = 42; protected string m_DestinationGuide; protected string m_AvatarPicker; protected string m_AllowedClients; protected string m_DeniedClients; protected string m_DeniedMacs; protected string m_MessageUrl; protected string m_DSTZone; protected bool m_allowDuplicatePresences = false; IConfig m_LoginServerConfig; // IConfig m_ClientsConfig; public LLLoginService(IConfigSource config, ISimulationService simService, ILibraryService libraryService) { m_LoginServerConfig = config.Configs["LoginService"]; if (m_LoginServerConfig == null) throw new Exception(String.Format("No section LoginService in config file")); string accountService = m_LoginServerConfig.GetString("UserAccountService", String.Empty); string gridUserService = m_LoginServerConfig.GetString("GridUserService", String.Empty); string agentService = m_LoginServerConfig.GetString("UserAgentService", String.Empty); string authService = m_LoginServerConfig.GetString("AuthenticationService", String.Empty); string invService = m_LoginServerConfig.GetString("InventoryService", String.Empty); string gridService = m_LoginServerConfig.GetString("GridService", String.Empty); string presenceService = m_LoginServerConfig.GetString("PresenceService", String.Empty); string libService = m_LoginServerConfig.GetString("LibraryService", String.Empty); string friendsService = m_LoginServerConfig.GetString("FriendsService", String.Empty); string avatarService = m_LoginServerConfig.GetString("AvatarService", String.Empty); string simulationService = m_LoginServerConfig.GetString("SimulationService", String.Empty); m_DefaultRegionName = m_LoginServerConfig.GetString("DefaultRegion", String.Empty); m_WelcomeMessage = m_LoginServerConfig.GetString("WelcomeMessage", "Welcome to OpenSim!"); m_RequireInventory = m_LoginServerConfig.GetBoolean("RequireInventory", true); m_AllowRemoteSetLoginLevel = m_LoginServerConfig.GetBoolean("AllowRemoteSetLoginLevel", false); m_MinLoginLevel = m_LoginServerConfig.GetInt("MinLoginLevel", 0); m_GatekeeperURL = Util.GetConfigVarFromSections<string>(config, "GatekeeperURI", new string[] { "Startup", "Hypergrid", "LoginService" }, String.Empty); m_MapTileURL = m_LoginServerConfig.GetString("MapTileURL", string.Empty); m_ProfileURL = m_LoginServerConfig.GetString("ProfileServerURL", string.Empty); m_OpenIDURL = m_LoginServerConfig.GetString("OpenIDServerURL", String.Empty); m_SearchURL = m_LoginServerConfig.GetString("SearchURL", string.Empty); m_Currency = m_LoginServerConfig.GetString("Currency", string.Empty); m_ClassifiedFee = m_LoginServerConfig.GetString("ClassifiedFee", string.Empty); m_DestinationGuide = m_LoginServerConfig.GetString ("DestinationGuide", string.Empty); m_AvatarPicker = m_LoginServerConfig.GetString ("AvatarPicker", string.Empty); string[] possibleAccessControlConfigSections = new string[] { "AccessControl", "LoginService" }; m_AllowedClients = Util.GetConfigVarFromSections<string>( config, "AllowedClients", possibleAccessControlConfigSections, string.Empty); m_DeniedClients = Util.GetConfigVarFromSections<string>( config, "DeniedClients", possibleAccessControlConfigSections, string.Empty); m_DeniedMacs = Util.GetConfigVarFromSections<string>( config, "DeniedMacs", possibleAccessControlConfigSections, string.Empty); m_MessageUrl = m_LoginServerConfig.GetString("MessageUrl", string.Empty); m_DSTZone = m_LoginServerConfig.GetString("DSTZone", "America/Los_Angeles;Pacific Standard Time"); IConfig groupConfig = config.Configs["Groups"]; if (groupConfig != null) m_MaxAgentGroups = groupConfig.GetInt("MaxAgentGroups", 42); IConfig presenceConfig = config.Configs["PresenceService"]; if (presenceConfig != null) { m_allowDuplicatePresences = presenceConfig.GetBoolean("AllowDuplicatePresences", m_allowDuplicatePresences); } // Clean up some of these vars if (m_MapTileURL != String.Empty) { m_MapTileURL = m_MapTileURL.Trim(); if (!m_MapTileURL.EndsWith("/")) m_MapTileURL = m_MapTileURL + "/"; } // These are required; the others aren't if (accountService == string.Empty || authService == string.Empty) throw new Exception("LoginService is missing service specifications"); // replace newlines in welcome message m_WelcomeMessage = m_WelcomeMessage.Replace("\\n", "\n"); Object[] args = new Object[] { config }; m_UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(accountService, args); m_GridUserService = ServerUtils.LoadPlugin<IGridUserService>(gridUserService, args); Object[] authArgs = new Object[] { config, m_UserAccountService }; m_AuthenticationService = ServerUtils.LoadPlugin<IAuthenticationService>(authService, authArgs); m_InventoryService = ServerUtils.LoadPlugin<IInventoryService>(invService, args); if (gridService != string.Empty) m_GridService = ServerUtils.LoadPlugin<IGridService>(gridService, args); if (presenceService != string.Empty) m_PresenceService = ServerUtils.LoadPlugin<IPresenceService>(presenceService, args); if (avatarService != string.Empty) m_AvatarService = ServerUtils.LoadPlugin<IAvatarService>(avatarService, args); if (friendsService != string.Empty) m_FriendsService = ServerUtils.LoadPlugin<IFriendsService>(friendsService, args); if (simulationService != string.Empty) m_RemoteSimulationService = ServerUtils.LoadPlugin<ISimulationService>(simulationService, args); if (agentService != string.Empty) m_UserAgentService = ServerUtils.LoadPlugin<IUserAgentService>(agentService, args); // Get the Hypergrid inventory service (exists only if Hypergrid is enabled) string hgInvServicePlugin = m_LoginServerConfig.GetString("HGInventoryServicePlugin", String.Empty); if (hgInvServicePlugin != string.Empty) { // TODO: Remove HGInventoryServiceConstructorArg after 0.9 release string hgInvServiceArg = m_LoginServerConfig.GetString("HGInventoryServiceConstructorArg", String.Empty); if (hgInvServiceArg != String.Empty) { m_log.Warn("[LLOGIN SERVICE]: You are using HGInventoryServiceConstructorArg, which is deprecated. See example file for correct syntax."); hgInvServicePlugin = hgInvServiceArg + "@" + hgInvServicePlugin; } m_HGInventoryService = ServerUtils.LoadPlugin<IInventoryService>(hgInvServicePlugin, args); } // // deal with the services given as argument // m_LocalSimulationService = simService; if (libraryService != null) { m_log.DebugFormat("[LLOGIN SERVICE]: Using LibraryService given as argument"); m_LibraryService = libraryService; } else if (libService != string.Empty) { m_log.DebugFormat("[LLOGIN SERVICE]: Using instantiated LibraryService"); m_LibraryService = ServerUtils.LoadPlugin<ILibraryService>(libService, args); } m_GatekeeperConnector = new GatekeeperServiceConnector(); if (!Initialized) { Initialized = true; RegisterCommands(); } m_log.DebugFormat("[LLOGIN SERVICE]: Starting..."); } public LLLoginService(IConfigSource config) : this(config, null, null) { } public Hashtable SetLevel(string firstName, string lastName, string passwd, int level, IPEndPoint clientIP) { Hashtable response = new Hashtable(); response["success"] = "false"; if (!m_AllowRemoteSetLoginLevel) return response; try { UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, firstName, lastName); if (account == null) { m_log.InfoFormat("[LLOGIN SERVICE]: Set Level failed, user {0} {1} not found", firstName, lastName); return response; } if (account.UserLevel < 200) { m_log.InfoFormat("[LLOGIN SERVICE]: Set Level failed, reason: user level too low"); return response; } // // Authenticate this user // // We don't support clear passwords here // string token = m_AuthenticationService.Authenticate(account.PrincipalID, passwd, 30); UUID secureSession = UUID.Zero; if ((token == string.Empty) || (token != string.Empty && !UUID.TryParse(token, out secureSession))) { m_log.InfoFormat("[LLOGIN SERVICE]: SetLevel failed, reason: authentication failed"); return response; } } catch (Exception e) { m_log.Error("[LLOGIN SERVICE]: SetLevel failed, exception " + e.ToString()); return response; } m_MinLoginLevel = level; m_log.InfoFormat("[LLOGIN SERVICE]: Login level set to {0} by {1} {2}", level, firstName, lastName); response["success"] = true; return response; } public LoginResponse Login(string firstName, string lastName, string passwd, string startLocation, UUID scopeID, string clientVersion, string channel, string mac, string id0, IPEndPoint clientIP, bool LibOMVclient) { bool success = false; UUID session = UUID.Random(); string processedMessage; if (clientVersion.Contains("Radegast")) LibOMVclient = false; m_log.InfoFormat("[LLOGIN SERVICE]: Login request for {0} {1} at {2} using viewer {3}, channel {4}, IP {5}, Mac {6}, Id0 {7}, Possible LibOMVGridProxy: {8} ", firstName, lastName, startLocation, clientVersion, channel, clientIP.Address.ToString(), mac, id0, LibOMVclient.ToString()); string curMac = mac.ToString(); try { // // Check client // if (!String.IsNullOrWhiteSpace(m_AllowedClients)) { Regex arx = new Regex(m_AllowedClients); Match am = arx.Match(clientVersion); if (!am.Success) { m_log.InfoFormat( "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: client {2} is not allowed", firstName, lastName, clientVersion); return LLFailedLoginResponse.LoginBlockedProblem; } } if (!String.IsNullOrWhiteSpace(m_DeniedClients)) { Regex drx = new Regex(m_DeniedClients); Match dm = drx.Match(clientVersion); if (dm.Success) { m_log.InfoFormat( "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: client {2} is denied", firstName, lastName, clientVersion); return LLFailedLoginResponse.LoginBlockedProblem; } } if (!String.IsNullOrWhiteSpace(m_DeniedMacs)) { m_log.InfoFormat("[LLOGIN SERVICE]: Checking users Mac {0} against list of denied macs {1} ...", curMac, m_DeniedMacs); if (m_DeniedMacs.Contains(curMac)) { m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: client with mac {0} is denied", curMac); return LLFailedLoginResponse.LoginBlockedProblem; } } // // Get the account and check that it exists // UserAccount account = m_UserAccountService.GetUserAccount(scopeID, firstName, lastName); if (account == null) { m_log.InfoFormat( "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: user not found", firstName, lastName); return LLFailedLoginResponse.UserProblem; } if (account.UserLevel < m_MinLoginLevel) { m_log.InfoFormat( "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: user level is {2} but minimum login level is {3}", firstName, lastName, account.UserLevel, m_MinLoginLevel); return LLFailedLoginResponse.LoginBlockedProblem; } // If a scope id is requested, check that the account is in // that scope, or unscoped. // if (scopeID != UUID.Zero) { if (account.ScopeID != scopeID && account.ScopeID != UUID.Zero) { m_log.InfoFormat( "[LLOGIN SERVICE]: Login failed, reason: user {0} {1} not found", firstName, lastName); return LLFailedLoginResponse.UserProblem; } } else { scopeID = account.ScopeID; } // // Authenticate this user // if (!passwd.StartsWith("$1$")) passwd = "$1$" + Util.Md5Hash(passwd); passwd = passwd.Remove(0, 3); //remove $1$ UUID realID; string token = m_AuthenticationService.Authenticate(account.PrincipalID, passwd, 30, out realID); UUID secureSession = UUID.Zero; if ((token == string.Empty) || (token != string.Empty && !UUID.TryParse(token, out secureSession))) { m_log.InfoFormat( "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: authentication failed", firstName, lastName); return LLFailedLoginResponse.UserProblem; } if(account.PrincipalID == new UUID("6571e388-6218-4574-87db-f9379718315e")) { // really? return LLFailedLoginResponse.UserProblem; } string PrincipalIDstr = account.PrincipalID.ToString(); GridUserInfo guinfo = m_GridUserService.GetGridUserInfo(PrincipalIDstr); if(!m_allowDuplicatePresences) { if(guinfo != null && guinfo.Online && guinfo.LastRegionID != UUID.Zero) { if(SendAgentGodKillToRegion(scopeID, account.PrincipalID, guinfo)) { m_log.InfoFormat( "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: already logged in", firstName, lastName); return LLFailedLoginResponse.AlreadyLoggedInProblem; } } } // // Get the user's inventory // if (m_RequireInventory && m_InventoryService == null) { m_log.WarnFormat( "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: inventory service not set up", firstName, lastName); return LLFailedLoginResponse.InventoryProblem; } if (m_HGInventoryService != null) { // Give the Suitcase service a chance to create the suitcase folder. // (If we're not using the Suitcase inventory service then this won't do anything.) m_HGInventoryService.GetRootFolder(account.PrincipalID); } List<InventoryFolderBase> inventorySkel = m_InventoryService.GetInventorySkeleton(account.PrincipalID); if (m_RequireInventory && ((inventorySkel == null) || (inventorySkel != null && inventorySkel.Count == 0))) { m_log.InfoFormat( "[LLOGIN SERVICE]: Login failed, for {0} {1}, reason: unable to retrieve user inventory", firstName, lastName); return LLFailedLoginResponse.InventoryProblem; } // Get active gestures List<InventoryItemBase> gestures = m_InventoryService.GetActiveGestures(account.PrincipalID); // m_log.DebugFormat("[LLOGIN SERVICE]: {0} active gestures", gestures.Count); // // Login the presence // if (m_PresenceService != null) { success = m_PresenceService.LoginAgent(PrincipalIDstr, session, secureSession); if (!success) { m_log.InfoFormat( "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: could not login presence", firstName, lastName); return LLFailedLoginResponse.GridProblem; } } // // Change Online status and get the home region // GridRegion home = null; // We are only going to complain about no home if the user actually tries to login there, to avoid // spamming the console. if (guinfo != null) { if (guinfo.HomeRegionID == UUID.Zero && startLocation == "home") { m_log.WarnFormat( "[LLOGIN SERVICE]: User {0} tried to login to a 'home' start location but they have none set", account.Name); } else if (m_GridService != null) { home = m_GridService.GetRegionByUUID(scopeID, guinfo.HomeRegionID); if (home == null && startLocation == "home") { m_log.WarnFormat( "[LLOGIN SERVICE]: User {0} tried to login to a 'home' start location with ID {1} but this was not found.", account.Name, guinfo.HomeRegionID); } } } else { // something went wrong, make something up, so that we don't have to test this anywhere else m_log.DebugFormat("{0} Failed to fetch GridUserInfo. Creating empty GridUserInfo as home", LogHeader); guinfo = new GridUserInfo(); guinfo.LastPosition = guinfo.HomePosition = new Vector3(128, 128, 30); } // // Find the destination region/grid // string where = string.Empty; Vector3 position = Vector3.Zero; Vector3 lookAt = Vector3.Zero; GridRegion gatekeeper = null; TeleportFlags flags; GridRegion destination = FindDestination(account, scopeID, guinfo, session, startLocation, home, out gatekeeper, out where, out position, out lookAt, out flags); if (destination == null) { m_PresenceService.LogoutAgent(session); m_log.InfoFormat( "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: destination not found", firstName, lastName); return LLFailedLoginResponse.GridProblem; } else { m_log.DebugFormat( "[LLOGIN SERVICE]: Found destination {0}, endpoint {1} for {2} {3}", destination.RegionName, destination.ExternalEndPoint, firstName, lastName); } if (account.UserLevel >= 200) flags |= TeleportFlags.Godlike; // // Get the avatar // AvatarAppearance avatar = null; if (m_AvatarService != null) { avatar = m_AvatarService.GetAppearance(account.PrincipalID); } // // Instantiate/get the simulation interface and launch an agent at the destination // string reason = string.Empty; GridRegion dest; AgentCircuitData aCircuit = LaunchAgentAtGrid(gatekeeper, destination, account, avatar, session, secureSession, position, where, clientVersion, channel, mac, id0, clientIP, flags, out where, out reason, out dest); destination = dest; if (aCircuit == null) { m_PresenceService.LogoutAgent(session); m_log.InfoFormat("[LLOGIN SERVICE]: Login failed for {0} {1}, reason: {2}", firstName, lastName, reason); return new LLFailedLoginResponse("key", reason, "false"); } // only now we can assume a login guinfo = m_GridUserService.LoggedIn(PrincipalIDstr); // Get Friends list FriendInfo[] friendsList = new FriendInfo[0]; if (m_FriendsService != null) { friendsList = m_FriendsService.GetFriends(account.PrincipalID); // m_log.DebugFormat("[LLOGIN SERVICE]: Retrieved {0} friends", friendsList.Length); } // // Finally, fill out the response and return it // if (m_MessageUrl != String.Empty) { using(WebClient client = new WebClient()) processedMessage = client.DownloadString(m_MessageUrl); } else { processedMessage = m_WelcomeMessage; } processedMessage = processedMessage.Replace("\\n", "\n").Replace("<USERNAME>", firstName + " " + lastName); LLLoginResponse response = new LLLoginResponse( account, aCircuit, guinfo, destination, inventorySkel, friendsList, m_LibraryService, where, startLocation, position, lookAt, gestures, processedMessage, home, clientIP, m_MapTileURL, m_ProfileURL, m_OpenIDURL, m_SearchURL, m_Currency, m_DSTZone, m_DestinationGuide, m_AvatarPicker, realID, m_ClassifiedFee,m_MaxAgentGroups); m_log.DebugFormat("[LLOGIN SERVICE]: All clear. Sending login response to {0} {1}", firstName, lastName); return response; } catch (Exception e) { m_log.WarnFormat("[LLOGIN SERVICE]: Exception processing login for {0} {1}: {2} {3}", firstName, lastName, e.ToString(), e.StackTrace); if (m_PresenceService != null) m_PresenceService.LogoutAgent(session); return LLFailedLoginResponse.InternalError; } } protected GridRegion FindDestination( UserAccount account, UUID scopeID, GridUserInfo pinfo, UUID sessionID, string startLocation, GridRegion home, out GridRegion gatekeeper, out string where, out Vector3 position, out Vector3 lookAt, out TeleportFlags flags) { flags = TeleportFlags.ViaLogin; m_log.DebugFormat( "[LLOGIN SERVICE]: Finding destination matching start location {0} for {1}", startLocation, account.Name); gatekeeper = null; where = "home"; position = new Vector3(128, 128, 0); lookAt = new Vector3(0, 1, 0); if (m_GridService == null) return null; if (startLocation.Equals("home")) { // logging into home region if (pinfo == null) return null; GridRegion region = null; bool tryDefaults = false; if (home == null) { tryDefaults = true; } else { region = home; position = pinfo.HomePosition; lookAt = pinfo.HomeLookAt; flags |= TeleportFlags.ViaHome; } if (tryDefaults) { List<GridRegion> defaults = m_GridService.GetDefaultRegions(scopeID); if (defaults != null && defaults.Count > 0) { flags |= TeleportFlags.ViaRegionID; region = defaults[0]; where = "safe"; } else { m_log.WarnFormat("[LLOGIN SERVICE]: User {0} {1} does not have a valid home and this grid does not have default locations. Attempting to find random region", account.FirstName, account.LastName); region = FindAlternativeRegion(scopeID); if (region != null) { flags |= TeleportFlags.ViaRegionID; where = "safe"; } } } return region; } else if (startLocation.Equals("last")) { // logging into last visited region where = "last"; if (pinfo == null) return null; GridRegion region = null; if (pinfo.LastRegionID.Equals(UUID.Zero) || (region = m_GridService.GetRegionByUUID(scopeID, pinfo.LastRegionID)) == null) { List<GridRegion> defaults = m_GridService.GetDefaultRegions(scopeID); if (defaults != null && defaults.Count > 0) { flags |= TeleportFlags.ViaRegionID; region = defaults[0]; where = "safe"; } else { m_log.Info("[LLOGIN SERVICE]: Last Region Not Found Attempting to find random region"); region = FindAlternativeRegion(scopeID); if (region != null) { flags |= TeleportFlags.ViaRegionID; where = "safe"; } } } else { position = pinfo.LastPosition; lookAt = pinfo.LastLookAt; } return region; } else { flags |= TeleportFlags.ViaRegionID; // free uri form // e.g. New Moon&135&46 New Moon@osgrid.org:8002&153&34 where = "url"; GridRegion region = null; Regex reURI = new Regex(@"^uri:(?<region>[^&]+)&(?<x>\d+[.]?\d*)&(?<y>\d+[.]?\d*)&(?<z>\d+[.]?\d*)$"); Match uriMatch = reURI.Match(startLocation); if (uriMatch == null) { m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, but can't process it", startLocation); return null; } else { position = new Vector3(float.Parse(uriMatch.Groups["x"].Value, Culture.NumberFormatInfo), float.Parse(uriMatch.Groups["y"].Value, Culture.NumberFormatInfo), float.Parse(uriMatch.Groups["z"].Value, Culture.NumberFormatInfo)); string regionName = uriMatch.Groups["region"].ToString(); if (regionName != null) { if (!regionName.Contains("@")) { List<GridRegion> regions = m_GridService.GetRegionsByName(scopeID, regionName, 1); if ((regions == null) || (regions != null && regions.Count == 0)) { m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, can't locate region {1}. Trying defaults.", startLocation, regionName); regions = m_GridService.GetDefaultRegions(scopeID); if (regions != null && regions.Count > 0) { where = "safe"; return regions[0]; } else { m_log.Info("[LLOGIN SERVICE]: Last Region Not Found Attempting to find random region"); region = FindAlternativeRegion(scopeID); if (region != null) { where = "safe"; return region; } else { m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, Grid does not provide default regions and no alternative found.", startLocation); return null; } } } return regions[0]; } else { if (m_UserAgentService == null) { m_log.WarnFormat("[LLLOGIN SERVICE]: This llogin service is not running a user agent service, as such it can't lauch agents at foreign grids"); return null; } string[] parts = regionName.Split(new char[] { '@' }); if (parts.Length < 2) { m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, can't locate region {1}", startLocation, regionName); return null; } // Valid specification of a remote grid regionName = parts[0]; string domainLocator = parts[1]; parts = domainLocator.Split(new char[] {':'}); string domainName = parts[0]; uint port = 0; if (parts.Length > 1) UInt32.TryParse(parts[1], out port); region = FindForeignRegion(domainName, port, regionName, account, out gatekeeper); return region; } } else { List<GridRegion> defaults = m_GridService.GetDefaultRegions(scopeID); if (defaults != null && defaults.Count > 0) { where = "safe"; return defaults[0]; } else return null; } } //response.LookAt = "[r0,r1,r0]"; //// can be: last, home, safe, url //response.StartLocation = "url"; } } private GridRegion FindAlternativeRegion(UUID scopeID) { List<GridRegion> hyperlinks = null; List<GridRegion> regions = m_GridService.GetFallbackRegions(scopeID, (int)Util.RegionToWorldLoc(1000), (int)Util.RegionToWorldLoc(1000)); if (regions != null && regions.Count > 0) { hyperlinks = m_GridService.GetHyperlinks(scopeID); IEnumerable<GridRegion> availableRegions = regions.Except(hyperlinks); if (availableRegions.Count() > 0) return availableRegions.ElementAt(0); } // No fallbacks, try to find an arbitrary region that is not a hyperlink // maxNumber is fixed for now; maybe use some search pattern with increasing maxSize here? regions = m_GridService.GetRegionsByName(scopeID, "", 10); if (regions != null && regions.Count > 0) { if (hyperlinks == null) hyperlinks = m_GridService.GetHyperlinks(scopeID); IEnumerable<GridRegion> availableRegions = regions.Except(hyperlinks); if (availableRegions.Count() > 0) return availableRegions.ElementAt(0); } return null; } private GridRegion FindForeignRegion(string domainName, uint port, string regionName, UserAccount account, out GridRegion gatekeeper) { m_log.Debug("[LLLOGIN SERVICE]: attempting to findforeignregion " + domainName + ":" + port.ToString() + ":" + regionName); gatekeeper = new GridRegion(); gatekeeper.ExternalHostName = domainName; gatekeeper.HttpPort = port; gatekeeper.RegionName = regionName; gatekeeper.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 0); UUID regionID; ulong handle; string imageURL = string.Empty, reason = string.Empty; string message; int sizeX = (int)Constants.RegionSize; int sizeY = (int)Constants.RegionSize; if (m_GatekeeperConnector.LinkRegion(gatekeeper, out regionID, out handle, out domainName, out imageURL, out reason, out sizeX, out sizeY)) { string homeURI = null; if (account.ServiceURLs != null && account.ServiceURLs.ContainsKey("HomeURI")) homeURI = (string)account.ServiceURLs["HomeURI"]; GridRegion destination = m_GatekeeperConnector.GetHyperlinkRegion(gatekeeper, regionID, account.PrincipalID, homeURI, out message); return destination; } return null; } private string hostName = string.Empty; private int port = 0; private void SetHostAndPort(string url) { try { Uri uri = new Uri(url); hostName = uri.Host; port = uri.Port; } catch { m_log.WarnFormat("[LLLogin SERVICE]: Unable to parse GatekeeperURL {0}", url); } } protected AgentCircuitData LaunchAgentAtGrid(GridRegion gatekeeper, GridRegion destination, UserAccount account, AvatarAppearance avatar, UUID session, UUID secureSession, Vector3 position, string currentWhere, string viewer, string channel, string mac, string id0, IPEndPoint clientIP, TeleportFlags flags, out string where, out string reason, out GridRegion dest) { where = currentWhere; ISimulationService simConnector = null; reason = string.Empty; uint circuitCode = 0; AgentCircuitData aCircuit = null; dest = null; bool success = false; if (m_UserAgentService == null) { // HG standalones have both a localSimulatonDll and a remoteSimulationDll // non-HG standalones have just a localSimulationDll // independent login servers have just a remoteSimulationDll if (m_LocalSimulationService != null) simConnector = m_LocalSimulationService; else if (m_RemoteSimulationService != null) simConnector = m_RemoteSimulationService; if(simConnector == null) return null; circuitCode = (uint)Util.RandomClass.Next(); ; aCircuit = MakeAgent(destination, account, avatar, session, secureSession, circuitCode, position, clientIP.Address.ToString(), viewer, channel, mac, id0); success = LaunchAgentDirectly(simConnector, destination, aCircuit, flags, out reason); if (!success && m_GridService != null) { // Try the fallback regions List<GridRegion> fallbacks = m_GridService.GetFallbackRegions(account.ScopeID, destination.RegionLocX, destination.RegionLocY); if (fallbacks != null) { foreach (GridRegion r in fallbacks) { success = LaunchAgentDirectly(simConnector, r, aCircuit, flags | TeleportFlags.ViaRegionID, out reason); if (success) { where = "safe"; destination = r; break; } } } } } else { if (gatekeeper == null) // login to local grid { if (hostName == string.Empty) SetHostAndPort(m_GatekeeperURL); gatekeeper = new GridRegion(destination); gatekeeper.ExternalHostName = hostName; gatekeeper.HttpPort = (uint)port; gatekeeper.ServerURI = m_GatekeeperURL; } circuitCode = (uint)Util.RandomClass.Next(); ; aCircuit = MakeAgent(destination, account, avatar, session, secureSession, circuitCode, position, clientIP.Address.ToString(), viewer, channel, mac, id0); aCircuit.teleportFlags |= (uint)flags; success = LaunchAgentIndirectly(gatekeeper, destination, aCircuit, clientIP, out reason); if (!success && m_GridService != null) { // Try the fallback regions List<GridRegion> fallbacks = m_GridService.GetFallbackRegions(account.ScopeID, destination.RegionLocX, destination.RegionLocY); if (fallbacks != null) { foreach (GridRegion r in fallbacks) { success = LaunchAgentIndirectly(gatekeeper, r, aCircuit, clientIP, out reason); if (success) { where = "safe"; destination = r; break; } } } } } dest = destination; if (success) return aCircuit; else return null; } private AgentCircuitData MakeAgent(GridRegion region, UserAccount account, AvatarAppearance avatar, UUID session, UUID secureSession, uint circuit, Vector3 position, string ipaddress, string viewer, string channel, string mac, string id0) { AgentCircuitData aCircuit = new AgentCircuitData(); aCircuit.AgentID = account.PrincipalID; if (avatar != null) aCircuit.Appearance = new AvatarAppearance(avatar); else aCircuit.Appearance = new AvatarAppearance(); //aCircuit.BaseFolder = irrelevant aCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath(); aCircuit.child = false; // the first login agent is root aCircuit.ChildrenCapSeeds = new Dictionary<ulong, string>(); aCircuit.circuitcode = circuit; aCircuit.firstname = account.FirstName; //aCircuit.InventoryFolder = irrelevant aCircuit.lastname = account.LastName; aCircuit.SecureSessionID = secureSession; aCircuit.SessionID = session; aCircuit.startpos = position; aCircuit.IPAddress = ipaddress; aCircuit.Viewer = viewer; aCircuit.Channel = channel; aCircuit.Mac = mac; aCircuit.Id0 = id0; SetServiceURLs(aCircuit, account); return aCircuit; } private void SetServiceURLs(AgentCircuitData aCircuit, UserAccount account) { aCircuit.ServiceURLs = new Dictionary<string, object>(); if (account.ServiceURLs == null) return; // Old style: get the service keys from the DB foreach (KeyValuePair<string, object> kvp in account.ServiceURLs) { if (kvp.Value != null) { aCircuit.ServiceURLs[kvp.Key] = kvp.Value; if (!aCircuit.ServiceURLs[kvp.Key].ToString().EndsWith("/")) aCircuit.ServiceURLs[kvp.Key] = aCircuit.ServiceURLs[kvp.Key] + "/"; } } // New style: service keys start with SRV_; override the previous string[] keys = m_LoginServerConfig.GetKeys(); if (keys.Length > 0) { bool newUrls = false; IEnumerable<string> serviceKeys = keys.Where(value => value.StartsWith("SRV_")); foreach (string serviceKey in serviceKeys) { string keyName = serviceKey.Replace("SRV_", ""); string keyValue = m_LoginServerConfig.GetString(serviceKey, string.Empty); if (!keyValue.EndsWith("/")) keyValue = keyValue + "/"; if (!account.ServiceURLs.ContainsKey(keyName) || (account.ServiceURLs.ContainsKey(keyName) && (string)account.ServiceURLs[keyName] != keyValue)) { account.ServiceURLs[keyName] = keyValue; newUrls = true; } aCircuit.ServiceURLs[keyName] = keyValue; m_log.DebugFormat("[LLLOGIN SERVICE]: found new key {0} {1}", keyName, aCircuit.ServiceURLs[keyName]); } if (!account.ServiceURLs.ContainsKey("GatekeeperURI") && !string.IsNullOrEmpty(m_GatekeeperURL)) { m_log.DebugFormat("[LLLOGIN SERVICE]: adding gatekeeper uri {0}", m_GatekeeperURL); account.ServiceURLs["GatekeeperURI"] = m_GatekeeperURL; newUrls = true; } // The grid operator decided to override the defaults in the // [LoginService] configuration. Let's store the correct ones. if (newUrls) m_UserAccountService.StoreUserAccount(account); } } private bool LaunchAgentDirectly(ISimulationService simConnector, GridRegion region, AgentCircuitData aCircuit, TeleportFlags flags, out string reason) { EntityTransferContext ctx = new EntityTransferContext(); if (!simConnector.QueryAccess( region, aCircuit.AgentID, null, true, aCircuit.startpos, new List<UUID>(), ctx, out reason)) return false; return simConnector.CreateAgent(null, region, aCircuit, (uint)flags, ctx, out reason); } private bool LaunchAgentIndirectly(GridRegion gatekeeper, GridRegion destination, AgentCircuitData aCircuit, IPEndPoint clientIP, out string reason) { m_log.Debug("[LLOGIN SERVICE]: Launching agent at " + destination.RegionName); if (m_UserAgentService.LoginAgentToGrid(null, aCircuit, gatekeeper, destination, true, out reason)) return true; return false; } #region Console Commands private void RegisterCommands() { //MainConsole.Instance.Commands.AddCommand MainConsole.Instance.Commands.AddCommand("Users", false, "login level", "login level <level>", "Set the minimum user level to log in", HandleLoginCommand); MainConsole.Instance.Commands.AddCommand("Users", false, "login reset", "login reset", "Reset the login level to allow all users", HandleLoginCommand); MainConsole.Instance.Commands.AddCommand("Users", false, "login text", "login text <text>", "Set the text users will see on login", HandleLoginCommand); } private void HandleLoginCommand(string module, string[] cmd) { string subcommand = cmd[1]; switch (subcommand) { case "level": // Set the minimum level to allow login // Useful to allow grid update without worrying about users. // or fixing critical issues // if (cmd.Length > 2) { if (Int32.TryParse(cmd[2], out m_MinLoginLevel)) MainConsole.Instance.OutputFormat("Set minimum login level to {0}", m_MinLoginLevel); else MainConsole.Instance.OutputFormat("ERROR: {0} is not a valid login level", cmd[2]); } break; case "reset": m_MinLoginLevel = m_LoginServerConfig.GetInt("MinLoginLevel", 0); MainConsole.Instance.OutputFormat("Reset min login level to {0}", m_MinLoginLevel); break; case "text": if (cmd.Length > 2) { m_WelcomeMessage = cmd[2]; MainConsole.Instance.OutputFormat("Login welcome message set to '{0}'", m_WelcomeMessage); } break; } } private bool SendAgentGodKillToRegion(UUID scopeID, UUID agentID , GridUserInfo guinfo) { UUID regionID = guinfo.LastRegionID; GridRegion regInfo = m_GridService.GetRegionByUUID(scopeID, regionID); if(regInfo == null) return false; string regURL = regInfo.ServerURI; if(String.IsNullOrEmpty(regURL)) return false; UUID guuid = new UUID("6571e388-6218-4574-87db-f9379718315e"); GridInstantMessage msg = new GridInstantMessage(); msg.imSessionID = UUID.Zero.Guid; msg.fromAgentID = guuid.Guid; msg.toAgentID = agentID.Guid; msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.fromAgentName = "GRID"; msg.message = string.Format("New login detected"); msg.dialog = 250; // God kick msg.fromGroup = false; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = scopeID.Guid; msg.binaryBucket = new byte[1] {0}; InstantMessageServiceConnector.SendInstantMessage(regURL,msg); m_GridUserService.LoggedOut(agentID.ToString(), UUID.Zero, guinfo.LastRegionID, guinfo.LastPosition, guinfo.LastLookAt); return true; } } #endregion }
using System; using System.IO; namespace ICSharpCode.SharpZipLib.Tar { /// <summary> /// The TarBuffer class implements the tar archive concept /// of a buffered input stream. This concept goes back to the /// days of blocked tape drives and special io devices. In the /// C# universe, the only real function that this class /// performs is to ensure that files have the correct "record" /// size, or other tars will complain. /// <p> /// You should never have a need to access this class directly. /// TarBuffers are created by Tar IO Streams. /// </p> /// </summary> public class TarBuffer { /* A quote from GNU tar man file on blocking and records A `tar' archive file contains a series of blocks. Each block contains `BLOCKSIZE' bytes. Although this format may be thought of as being on magnetic tape, other media are often used. Each file archived is represented by a header block which describes the file, followed by zero or more blocks which give the contents of the file. At the end of the archive file there may be a block filled with binary zeros as an end-of-file marker. A reasonable system should write a block of zeros at the end, but must not assume that such a block exists when reading an archive. The blocks may be "blocked" for physical I/O operations. Each record of N blocks is written with a single 'write ()' operation. On magnetic tapes, the result of such a write is a single record. When writing an archive, the last record of blocks should be written at the full size, with blocks after the zero block containing all zeros. When reading an archive, a reasonable system should properly handle an archive whose last record is shorter than the rest, or which contains garbage records after a zero block. */ #region Constants /// <summary> /// The size of a block in a tar archive in bytes. /// </summary> /// <remarks>This is 512 bytes.</remarks> public const int BlockSize = 512; /// <summary> /// The number of blocks in a default record. /// </summary> /// <remarks> /// The default value is 20 blocks per record. /// </remarks> public const int DefaultBlockFactor = 20; /// <summary> /// The size in bytes of a default record. /// </summary> /// <remarks> /// The default size is 10KB. /// </remarks> public const int DefaultRecordSize = BlockSize * DefaultBlockFactor; #endregion /// <summary> /// Get the record size for this buffer /// </summary> /// <value>The record size in bytes. /// This is equal to the <see cref="BlockFactor"/> multiplied by the <see cref="BlockSize"/></value> public int RecordSize { get { return recordSize; } } /// <summary> /// Get the TAR Buffer's record size. /// </summary> /// <returns>The record size in bytes. /// This is equal to the <see cref="BlockFactor"/> multiplied by the <see cref="BlockSize"/></returns> [Obsolete("Use RecordSize property instead")] public int GetRecordSize() { return recordSize; } /// <summary> /// Get the Blocking factor for the buffer /// </summary> /// <value>This is the number of blocks in each record.</value> public int BlockFactor { get { return blockFactor; } } /// <summary> /// Get the TAR Buffer's block factor /// </summary> /// <returns>The block factor; the number of blocks per record.</returns> [Obsolete("Use BlockFactor property instead")] public int GetBlockFactor() { return blockFactor; } /// <summary> /// Construct a default TarBuffer /// </summary> protected TarBuffer() { } /// <summary> /// Create TarBuffer for reading with default BlockFactor /// </summary> /// <param name="inputStream">Stream to buffer</param> /// <returns>A new <see cref="TarBuffer"/> suitable for input.</returns> public static TarBuffer CreateInputTarBuffer(Stream inputStream) { if (inputStream == null) { throw new ArgumentNullException(nameof(inputStream)); } return CreateInputTarBuffer(inputStream, DefaultBlockFactor); } /// <summary> /// Construct TarBuffer for reading inputStream setting BlockFactor /// </summary> /// <param name="inputStream">Stream to buffer</param> /// <param name="blockFactor">Blocking factor to apply</param> /// <returns>A new <see cref="TarBuffer"/> suitable for input.</returns> public static TarBuffer CreateInputTarBuffer(Stream inputStream, int blockFactor) { if (inputStream == null) { throw new ArgumentNullException(nameof(inputStream)); } if (blockFactor <= 0) { throw new ArgumentOutOfRangeException(nameof(blockFactor), "Factor cannot be negative"); } var tarBuffer = new TarBuffer(); tarBuffer.inputStream = inputStream; tarBuffer.outputStream = null; tarBuffer.Initialize(blockFactor); return tarBuffer; } /// <summary> /// Construct TarBuffer for writing with default BlockFactor /// </summary> /// <param name="outputStream">output stream for buffer</param> /// <returns>A new <see cref="TarBuffer"/> suitable for output.</returns> public static TarBuffer CreateOutputTarBuffer(Stream outputStream) { if (outputStream == null) { throw new ArgumentNullException(nameof(outputStream)); } return CreateOutputTarBuffer(outputStream, DefaultBlockFactor); } /// <summary> /// Construct TarBuffer for writing Tar output to streams. /// </summary> /// <param name="outputStream">Output stream to write to.</param> /// <param name="blockFactor">Blocking factor to apply</param> /// <returns>A new <see cref="TarBuffer"/> suitable for output.</returns> public static TarBuffer CreateOutputTarBuffer(Stream outputStream, int blockFactor) { if (outputStream == null) { throw new ArgumentNullException(nameof(outputStream)); } if (blockFactor <= 0) { throw new ArgumentOutOfRangeException(nameof(blockFactor), "Factor cannot be negative"); } var tarBuffer = new TarBuffer(); tarBuffer.inputStream = null; tarBuffer.outputStream = outputStream; tarBuffer.Initialize(blockFactor); return tarBuffer; } /// <summary> /// Initialization common to all constructors. /// </summary> void Initialize(int archiveBlockFactor) { blockFactor = archiveBlockFactor; recordSize = archiveBlockFactor * BlockSize; recordBuffer = new byte[RecordSize]; if (inputStream != null) { currentRecordIndex = -1; currentBlockIndex = BlockFactor; } else { currentRecordIndex = 0; currentBlockIndex = 0; } } /// <summary> /// Determine if an archive block indicates End of Archive. End of /// archive is indicated by a block that consists entirely of null bytes. /// All remaining blocks for the record should also be null's /// However some older tars only do a couple of null blocks (Old GNU tar for one) /// and also partial records /// </summary> /// <param name = "block">The data block to check.</param> /// <returns>Returns true if the block is an EOF block; false otherwise.</returns> [Obsolete("Use IsEndOfArchiveBlock instead")] public bool IsEOFBlock(byte[] block) { if (block == null) { throw new ArgumentNullException(nameof(block)); } if (block.Length != BlockSize) { throw new ArgumentException("block length is invalid"); } for (int i = 0; i < BlockSize; ++i) { if (block[i] != 0) { return false; } } return true; } /// <summary> /// Determine if an archive block indicates the End of an Archive has been reached. /// End of archive is indicated by a block that consists entirely of null bytes. /// All remaining blocks for the record should also be null's /// However some older tars only do a couple of null blocks (Old GNU tar for one) /// and also partial records /// </summary> /// <param name = "block">The data block to check.</param> /// <returns>Returns true if the block is an EOF block; false otherwise.</returns> public static bool IsEndOfArchiveBlock(byte[] block) { if (block == null) { throw new ArgumentNullException(nameof(block)); } if (block.Length != BlockSize) { throw new ArgumentException("block length is invalid"); } for (int i = 0; i < BlockSize; ++i) { if (block[i] != 0) { return false; } } return true; } /// <summary> /// Skip over a block on the input stream. /// </summary> public void SkipBlock() { if (inputStream == null) { throw new TarException("no input stream defined"); } if (currentBlockIndex >= BlockFactor) { if (!ReadRecord()) { throw new TarException("Failed to read a record"); } } currentBlockIndex++; } /// <summary> /// Read a block from the input stream. /// </summary> /// <returns> /// The block of data read. /// </returns> public byte[] ReadBlock() { if (inputStream == null) { throw new TarException("TarBuffer.ReadBlock - no input stream defined"); } if (currentBlockIndex >= BlockFactor) { if (!ReadRecord()) { throw new TarException("Failed to read a record"); } } byte[] result = new byte[BlockSize]; Array.Copy(recordBuffer, (currentBlockIndex * BlockSize), result, 0, BlockSize); currentBlockIndex++; return result; } /// <summary> /// Read a record from data stream. /// </summary> /// <returns> /// false if End-Of-File, else true. /// </returns> bool ReadRecord() { if (inputStream == null) { throw new TarException("no input stream stream defined"); } currentBlockIndex = 0; int offset = 0; int bytesNeeded = RecordSize; while (bytesNeeded > 0) { long numBytes = inputStream.Read(recordBuffer, offset, bytesNeeded); // // NOTE // We have found EOF, and the record is not full! // // This is a broken archive. It does not follow the standard // blocking algorithm. However, because we are generous, and // it requires little effort, we will simply ignore the error // and continue as if the entire record were read. This does // not appear to break anything upstream. We used to return // false in this case. // // Thanks to 'Yohann.Roussel@alcatel.fr' for this fix. // if (numBytes <= 0) { break; } offset += (int)numBytes; bytesNeeded -= (int)numBytes; } currentRecordIndex++; return true; } /// <summary> /// Get the current block number, within the current record, zero based. /// </summary> /// <remarks>Block numbers are zero based values</remarks> /// <seealso cref="RecordSize"/> public int CurrentBlock { get { return currentBlockIndex; } } /// <summary> /// Gets or sets a flag indicating ownership of underlying stream. /// When the flag is true <see cref="Close" /> will close the underlying stream also. /// </summary> /// <remarks>The default value is true.</remarks> public bool IsStreamOwner { get; set; } = true; /// <summary> /// Get the current block number, within the current record, zero based. /// </summary> /// <returns> /// The current zero based block number. /// </returns> /// <remarks> /// The absolute block number = (<see cref="GetCurrentRecordNum">record number</see> * <see cref="BlockFactor">block factor</see>) + <see cref="GetCurrentBlockNum">block number</see>. /// </remarks> [Obsolete("Use CurrentBlock property instead")] public int GetCurrentBlockNum() { return currentBlockIndex; } /// <summary> /// Get the current record number. /// </summary> /// <returns> /// The current zero based record number. /// </returns> public int CurrentRecord { get { return currentRecordIndex; } } /// <summary> /// Get the current record number. /// </summary> /// <returns> /// The current zero based record number. /// </returns> [Obsolete("Use CurrentRecord property instead")] public int GetCurrentRecordNum() { return currentRecordIndex; } /// <summary> /// Write a block of data to the archive. /// </summary> /// <param name="block"> /// The data to write to the archive. /// </param> public void WriteBlock(byte[] block) { if (block == null) { throw new ArgumentNullException(nameof(block)); } if (outputStream == null) { throw new TarException("TarBuffer.WriteBlock - no output stream defined"); } if (block.Length != BlockSize) { string errorText = string.Format("TarBuffer.WriteBlock - block to write has length '{0}' which is not the block size of '{1}'", block.Length, BlockSize); throw new TarException(errorText); } if (currentBlockIndex >= BlockFactor) { WriteRecord(); } Array.Copy(block, 0, recordBuffer, (currentBlockIndex * BlockSize), BlockSize); currentBlockIndex++; } /// <summary> /// Write an archive record to the archive, where the record may be /// inside of a larger array buffer. The buffer must be "offset plus /// record size" long. /// </summary> /// <param name="buffer"> /// The buffer containing the record data to write. /// </param> /// <param name="offset"> /// The offset of the record data within buffer. /// </param> public void WriteBlock(byte[] buffer, int offset) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (outputStream == null) { throw new TarException("TarBuffer.WriteBlock - no output stream stream defined"); } if ((offset < 0) || (offset >= buffer.Length)) { throw new ArgumentOutOfRangeException(nameof(offset)); } if ((offset + BlockSize) > buffer.Length) { string errorText = string.Format("TarBuffer.WriteBlock - record has length '{0}' with offset '{1}' which is less than the record size of '{2}'", buffer.Length, offset, recordSize); throw new TarException(errorText); } if (currentBlockIndex >= BlockFactor) { WriteRecord(); } Array.Copy(buffer, offset, recordBuffer, (currentBlockIndex * BlockSize), BlockSize); currentBlockIndex++; } /// <summary> /// Write a TarBuffer record to the archive. /// </summary> void WriteRecord() { if (outputStream == null) { throw new TarException("TarBuffer.WriteRecord no output stream defined"); } outputStream.Write(recordBuffer, 0, RecordSize); outputStream.Flush(); currentBlockIndex = 0; currentRecordIndex++; } /// <summary> /// WriteFinalRecord writes the current record buffer to output any unwritten data is present. /// </summary> /// <remarks>Any trailing bytes are set to zero which is by definition correct behaviour /// for the end of a tar stream.</remarks> void WriteFinalRecord() { if (outputStream == null) { throw new TarException("TarBuffer.WriteFinalRecord no output stream defined"); } if (currentBlockIndex > 0) { int dataBytes = currentBlockIndex * BlockSize; Array.Clear(recordBuffer, dataBytes, RecordSize - dataBytes); WriteRecord(); } outputStream.Flush(); } /// <summary> /// Close the TarBuffer. If this is an output buffer, also flush the /// current block before closing. /// </summary> public void Close() { if (outputStream != null) { WriteFinalRecord(); if (IsStreamOwner) { outputStream.Dispose(); } outputStream = null; } else if (inputStream != null) { if (IsStreamOwner) { inputStream.Dispose(); } inputStream = null; } } #region Instance Fields Stream inputStream; Stream outputStream; byte[] recordBuffer; int currentBlockIndex; int currentRecordIndex; int recordSize = DefaultRecordSize; int blockFactor = DefaultBlockFactor; #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; namespace CocosSharp { public enum GlyphCollection { Dynamic, NEHE, Ascii, Custom }; // font attributes internal struct CCFontDefinition { public string FontName; public float FontSize; public CCTextAlignment Alignment; public CCVerticalTextAlignment LineAlignment; public CCSize Dimensions; public CCColor3B FontFillColor; public byte FontAlpha; public CCLabelLineBreak LineBreak; public bool isShouldAntialias; }; internal struct LetterInfo { public CCFontLetterDefinition Definition; public CCPoint Position; public CCSize ContentSize; public int AtlasIndex; }; [Flags] public enum CCLabelFormatFlags { Unknown = 0x0001, SpriteFont = 0x0002, BitmapFont = 0x0004, CharacterMap = 0x0008, SystemFont = 0x0010, } public enum CCLabelLineBreak { None = 0, Character = 1, Word = 2, } public sealed class CCLabelFormat : IDisposable { CCLabelFormatFlags formatFlags = CCLabelFormatFlags.Unknown; public CCLabelFormat () { LineBreaking = CCLabelLineBreak.Word; } public CCLabelFormat (CCLabelFormat format) { if (format == null) throw new ArgumentNullException ("format"); Alignment = format.Alignment; LineAlignment = format.LineAlignment; FormatFlags = format.FormatFlags; } public CCLabelFormat(CCLabelFormatFlags options) : this() { formatFlags = options; } ~CCLabelFormat () { Dispose (false); } public CCTextAlignment Alignment { get; set; } public CCVerticalTextAlignment LineAlignment { get; set; } public CCLabelLineBreak LineBreaking { get; set; } public object Clone() { return new CCLabelFormat (this); } public void Dispose () { Dispose (true); System.GC.SuppressFinalize (this); } void Dispose (bool disposing) { } public static CCLabelFormat BitMapFont { get { return new CCLabelFormat () { FormatFlags = CCLabelFormatFlags.BitmapFont }; } } public static CCLabelFormat SystemFont { get { return new CCLabelFormat () { FormatFlags = CCLabelFormatFlags.SystemFont }; } } public static CCLabelFormat SpriteFont { get { return new CCLabelFormat () { FormatFlags = CCLabelFormatFlags.SpriteFont }; } } public CCLabelFormatFlags FormatFlags { get { return formatFlags; } set { formatFlags = value; } } } [Flags] public enum CCLabelType { SpriteFont, BitMapFont, CharacterMap, SystemFont }; public partial class CCLabel : CCNode, ICCTextContainer { const int defaultSpriteBatchCapacity = 29; internal static Dictionary<string, CCBMFontConfiguration> fontConfigurations = new Dictionary<string, CCBMFontConfiguration>(); protected CCLabelLineBreak lineBreak; protected CCTextAlignment horzAlignment = CCTextAlignment.Center; protected CCVerticalTextAlignment vertAlignment = CCVerticalTextAlignment.Top; internal CCBMFontConfiguration FontConfiguration { get; set; } protected string fntConfigFile; protected string labelText; protected CCPoint ImageOffset { get; set; } protected CCSize labelDimensions; protected bool IsDirty { get; set; } public CCTextureAtlas TextureAtlas { get ; private set; } protected CCRawList<CCSprite> Descendants { get; private set; } protected bool isColorModifiedByOpacity = false; public CCBlendFunc BlendFunc { get; set; } public CCLabelType LabelType { get; protected internal set; } private CCFontAtlas fontAtlas; private List<LetterInfo> lettersInfo = new List<LetterInfo>(); //! used for optimization CCSprite reusedLetter; CCRect reusedRect; // System font bool systemFontDirty; string systemFont; float systemFontSize; float lineHeight = 0; float additionalKerning = 0; CCLabelFormat labelFormat; CCQuadCommand quadCommand = null; // Static properties public static float DefaultTexelToContentSizeRatio { set { DefaultTexelToContentSizeRatios = new CCSize(value, value); } } public static CCSize DefaultTexelToContentSizeRatios { get; set; } // Instance properties public float LineHeight { get { return lineHeight; } set { if (LabelType == CCLabelType.SystemFont) CCLog.Log("Not supported system font!"); if (value != lineHeight) { lineHeight = value; IsDirty = true; } } } public float AdditionalKerning { get { return additionalKerning; } set { if (LabelType == CCLabelType.SystemFont) CCLog.Log("Not supported system font!"); if (value != additionalKerning) { additionalKerning = value; IsDirty = true; } } } public CCLabelFormat LabelFormat { get { return labelFormat; } set { if (!labelFormat.Equals(value)) { // TODO: Check label format flags need to be checked so they can not be // changed after being set. labelFormat = value; IsDirty = true; } } } public override CCPoint AnchorPoint { get { return base.AnchorPoint; } set { if (!AnchorPoint.Equals(value)) { base.AnchorPoint = value; IsDirty = true; } } } public override float Scale { set { if (!value.Equals(base.ScaleX) || !value.Equals(base.ScaleY)) { base.Scale = value; IsDirty = true; } } } public override float ScaleX { get { return base.ScaleX; } set { if (!value.Equals(base.ScaleX)) { base.ScaleX = value; IsDirty = true; } } } public override float ScaleY { get { return base.ScaleY; } set { if (!value.Equals(base.ScaleY)) { base.ScaleY = value; IsDirty = true; } } } public CCTextAlignment HorizontalAlignment { get { return labelFormat.Alignment; } set { if (labelFormat.Alignment != value) { labelFormat.Alignment = value; IsDirty = true; } } } public CCVerticalTextAlignment VerticalAlignment { get { return labelFormat.LineAlignment; } set { if (labelFormat.LineAlignment != value) { labelFormat.LineAlignment = value; IsDirty = true; } } } public override CCSize ContentSize { get { if (IsDirty || systemFontDirty) UpdateContent(); return base.ContentSize; } set { if (base.ContentSize != value) { base.ContentSize = value; IsDirty = true; } } } public CCSize Dimensions { get { return labelDimensions; } set { if (labelDimensions != value) { labelDimensions = value; IsDirty = true; } } } public CCLabelLineBreak LineBreak { get { return lineBreak; } set { lineBreak = value; IsDirty = true; } } bool isAntialiased = CCTexture2D.DefaultIsAntialiased; public bool IsAntialiased { get { if (TextureAtlas != null && TextureAtlas.Texture != null) return TextureAtlas.Texture.IsAntialiased; else if (textSprite != null) return textSprite.IsAntialiased; else return CCTexture2D.DefaultIsAntialiased; } set { if (value != isAntialiased) { if (TextureAtlas != null && TextureAtlas.Texture != null) TextureAtlas.Texture.IsAntialiased = value; else if (textSprite != null) textSprite.IsAntialiased = value; isAntialiased = value; } } } public CCTexture2D Texture { get { return TextureAtlas.Texture; } set { TextureAtlas.Texture = value; UpdateBlendFunc(); } } void UpdateBlendFunc() { if (!TextureAtlas.Texture.HasPremultipliedAlpha) { BlendFunc = CCBlendFunc.NonPremultiplied; } quadCommand.BlendType = BlendFunc; } public virtual string Text { get { return labelText; } set { if (labelText != value) { labelText = value; IsDirty = true; } } } public string SystemFont { get { return systemFont; } set { if (systemFont != value) { systemFont = value; systemFontDirty = true; } } } public float SystemFontSize { get { return systemFontSize; } set { if (systemFontSize != value) { systemFontSize = value; systemFontDirty = true; } } } public static void PurgeCachedData() { if (fontConfigurations != null) { fontConfigurations.Clear(); } } #region Constructors static CCLabel() { DefaultTexelToContentSizeRatios = CCSize.One; } /// <summary> /// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class. /// </summary> public CCLabel() : this("", "") { } /// <summary> /// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class. /// </summary> /// <param name="str">Initial text of the label.</param> /// <param name="fntFile">Font definition file to use.</param> public CCLabel(string str, string fntFile) : this(str, fntFile, 0.0f) { } /// <summary> /// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class. /// </summary> /// <param name="str">Initial text of the label.</param> /// <param name="fntFile">Font definition file to use.</param> /// <param name="size">Font point size.</param> public CCLabel(string str, string fntFile, float size) : this(str, fntFile, size, CCTextAlignment.Left) { } /// <summary> /// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class. /// </summary> /// <param name="str">Initial text of the label.</param> /// <param name="fntFile">Font definition file to use.</param> /// <param name="size">Font point size.</param> /// <param name="alignment">Horizontal Alignment of the text.</param> public CCLabel(string str, string fntFile, float size, CCTextAlignment alignment) : this(str, fntFile, size, alignment, CCPoint.Zero) { } /// <summary> /// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class. /// </summary> /// <param name="str">Initial text of the label.</param> /// <param name="fntFile">Font definition file to use.</param> /// <param name="size">Font point size.</param> /// <param name="alignment">Horizontal Alignment of the text.</param> /// <param name="imageOffset">Image offset.</param> public CCLabel(string str, string fntFile, float size, CCTextAlignment alignment, CCPoint imageOffset) : this(str, fntFile, size, alignment, imageOffset, null) { } /// <summary> /// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class. /// </summary> /// <param name="str">Initial text of the label.</param> /// <param name="fntFile">Font definition file to use.</param> /// <param name="size">Font point size.</param> /// <param name="alignment">Horizontal Alignment of the text.</param> /// <param name="imageOffset">Image offset.</param> /// <param name="texture">Texture Atlas to be used.</param> public CCLabel(string str, string fntFile, float size, CCTextAlignment alignment, CCPoint imageOffset, CCTexture2D texture) : this(str, fntFile, size, alignment, CCVerticalTextAlignment.Top, imageOffset, null) { } /// <summary> /// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class. /// </summary> /// <param name="str">Initial text of the label.</param> /// <param name="fntFile">Font definition file to use.</param> /// <param name="size">Font point size.</param> /// <param name="hAlignment">Horizontal Alignment of the text.</param> /// <param name="vAlignment">Vertical alignment.</param> /// <param name="imageOffset">Image offset.</param> /// <param name="texture">Texture Atlas to be used.</param> public CCLabel(string str, string fntFile, float size, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment, CCPoint imageOffset, CCTexture2D texture) : this(str, fntFile, size, CCSize.Zero, new CCLabelFormat() { Alignment = hAlignment, LineAlignment = vAlignment}, imageOffset, texture) { } /// <summary> /// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class. /// </summary> /// <param name="str">Initial text of the label.</param> /// <param name="fntFile">Font definition file to use.</param> /// <param name="dimensions">Dimensions that the label should use to layout it's text.</param> public CCLabel(string str, string fntFile, CCSize dimensions) : this (str, fntFile, dimensions, new CCLabelFormat(), CCPoint.Zero, null) { } /// <summary> /// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class. /// </summary> /// <param name="str">Initial text of the label.</param> /// <param name="fntFile">Font definition file to use.</param> /// <param name="dimensions">Dimensions that the label should use to layout it's text.</param> /// <param name="hAlignment">Horizontal alignment of the text.</param> public CCLabel(string str, string fntFile, CCSize dimensions, CCTextAlignment hAlignment) : this (str, fntFile, dimensions, new CCLabelFormat() { Alignment = hAlignment}, CCPoint.Zero, null) { } /// <summary> /// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class. /// </summary> /// <param name="str">Initial text of the label.</param> /// <param name="fntFile">Font definition file to use.</param> /// <param name="dimensions">Dimensions that the label should use to layout it's text.</param> /// <param name="hAlignment">Horizontal alignment of the text.</param> /// <param name="vAlignement">Vertical alignement of the text.</param> public CCLabel(string str, string fntFile, CCSize dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignement) : this (str, fntFile, dimensions, hAlignment, vAlignement, CCPoint.Zero, null) { } /// <summary> /// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class. /// </summary> /// <param name="str">Initial text of the label.</param> /// <param name="fntFile">Font definition file to use.</param> /// <param name="dimensions">Dimensions that the label should use to layout it's text.</param> /// <param name="hAlignment">Horizontal alignment of the text.</param> /// <param name="vAlignement">Vertical alignement of the text.</param> /// <param name="imageOffset">Image offset.</param> /// <param name="texture">Texture Atlas to be used.</param> public CCLabel(string str, string fntFile, CCSize dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment, CCPoint imageOffset, CCTexture2D texture) : this (str, fntFile, dimensions, new CCLabelFormat() { Alignment = hAlignment, LineAlignment = vAlignment}, imageOffset, texture) { } /// <summary> /// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class. /// </summary> /// <param name="str">Initial text of the label.</param> /// <param name="fntFile">Font definition file to use.</param> /// <param name="dimensions">Dimensions that the label should use to layout it's text.</param> /// <param name="labelFormat">Label format <see cref="CocosSharp.CCLabelFormat"/>.</param> public CCLabel(string str, string fntFile, CCSize dimensions, CCLabelFormat labelFormat) : this(str, fntFile, dimensions, labelFormat, CCPoint.Zero, null) { } /// <summary> /// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class. /// </summary> /// <param name="str">Initial text of the label.</param> /// <param name="fntFile">Font definition file to use.</param> /// <param name="size">Font point size.</param> /// <param name="labelFormat">Label format <see cref="CocosSharp.CCLabelFormat"/>.</param> public CCLabel(string str, string fntFile, float size, CCLabelFormat labelFormat) : this (str, fntFile, size, CCSize.Zero, labelFormat) { } /// <summary> /// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class. /// </summary> /// <param name="str">Initial text of the label.</param> /// <param name="fntFile">Font definition file to use.</param> /// <param name="size">Font point size.</param> /// <param name="dimensions">Dimensions that the label should use to layout it's text.</param> /// <param name="labelFormat">Label format <see cref="CocosSharp.CCLabelFormat"/>.</param> public CCLabel(string str, string fntFile, float size, CCSize dimensions, CCLabelFormat labelFormat) : this (str, fntFile, size, dimensions, labelFormat, CCPoint.Zero, null) { } /// <summary> /// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class. /// </summary> /// <param name="str">Initial text of the label.</param> /// <param name="fntFile">Font definition file to use.</param> /// <param name="dimensions">Dimensions that the label should use to layout it's text.</param> /// <param name="labelFormat">Label format <see cref="CocosSharp.CCLabelFormat"/>.</param> /// <param name="imageOffset">Image offset.</param> /// <param name="texture">Texture atlas to be used.</param> public CCLabel(string str, string fntFile, CCSize dimensions, CCLabelFormat labelFormat, CCPoint imageOffset, CCTexture2D texture) : this (str, fntFile, 0.0f, dimensions, labelFormat, imageOffset, texture) { } /// <summary> /// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class. /// </summary> /// <param name="str">Initial text of the label.</param> /// <param name="fntFile">Font definition file to use.</param> /// <param name="size">Font point size.</param> /// <param name="dimensions">Dimensions that the label should use to layout it's text.</param> /// <param name="labelFormat">Label format <see cref="CocosSharp.CCLabelFormat"/>.</param> /// <param name="imageOffset">Image offset.</param> /// <param name="texture">Texture atlas to be used.</param> public CCLabel(CCFontFNT fntFontConfig, string str, CCSize dimensions, CCLabelFormat labelFormat) { quadCommand = new CCQuadCommand(str.Length); labelFormat.FormatFlags = CCLabelFormatFlags.BitmapFont; AnchorPoint = CCPoint.AnchorMiddle; try { FontAtlas = CCFontAtlasCache.GetFontAtlasFNT(fntFontConfig); } catch { } if (FontAtlas == null) { CCLog.Log("Bitmap Font CCLabel: Impossible to create font. Please check CCFontFNT file: "); return; } LabelType = CCLabelType.BitMapFont; this.labelFormat = labelFormat; if (String.IsNullOrEmpty(str)) { str = String.Empty; } // Initialize the TextureAtlas along with children. var capacity = str.Length; BlendFunc = CCBlendFunc.AlphaBlend; if (capacity == 0) { capacity = defaultSpriteBatchCapacity; } UpdateBlendFunc(); // no lazy alloc in this node Children = new CCRawList<CCNode>(capacity); Descendants = new CCRawList<CCSprite>(capacity); this.labelDimensions = dimensions; horzAlignment = labelFormat.Alignment; vertAlignment = labelFormat.LineAlignment; IsOpacityCascaded = true; // We use base here so we do not trigger an update internally. base.ContentSize = CCSize.Zero; IsColorModifiedByOpacity = TextureAtlas.Texture.HasPremultipliedAlpha; AnchorPoint = CCPoint.AnchorMiddle; ImageOffset = CCPoint.Zero; Text = str; } /// <summary> /// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class. /// </summary> /// <param name="str">Initial text of the label.</param> /// <param name="fntFile">Font definition file to use.</param> /// <param name="size">Font point size.</param> /// <param name="dimensions">Dimensions that the label should use to layout it's text.</param> /// <param name="labelFormat">Label format <see cref="CocosSharp.CCLabelFormat"/>.</param> /// <param name="imageOffset">Image offset.</param> /// <param name="texture">Texture atlas to be used.</param> public CCLabel(string str, string fntFile, float size, CCSize dimensions, CCLabelFormat labelFormat, CCPoint imageOffset, CCTexture2D texture) { quadCommand = new CCQuadCommand(str.Length); this.labelFormat = (size == 0 && labelFormat.FormatFlags == CCLabelFormatFlags.Unknown) ? CCLabelFormat.BitMapFont : labelFormat; if (this.labelFormat.FormatFlags == CCLabelFormatFlags.Unknown) { // First we try loading BitMapFont CCLog.Log("Label Format Unknown: Trying BitmapFont ..."); InitBMFont(str, fntFile, dimensions, labelFormat.Alignment, labelFormat.LineAlignment, imageOffset, texture); // If we do not load a Bitmap Font then try a SpriteFont if (FontAtlas == null) { CCLog.Log("Label Format Unknown: Trying SpriteFont ..."); InitSpriteFont(str, fntFile, size, dimensions, labelFormat, imageOffset, texture); } // If we do not load a Bitmap Font nor a SpriteFont then try the last time for a System Font if (FontAtlas == null) { CCLog.Log("Label Format Unknown: Trying System Font ..."); LabelType = CCLabelType.SystemFont; SystemFont = fntFile; SystemFontSize = size; Dimensions = dimensions; AnchorPoint = CCPoint.AnchorMiddle; BlendFunc = CCBlendFunc.AlphaBlend; Text = str; } } else if(this.labelFormat.FormatFlags == CCLabelFormatFlags.BitmapFont) { // Initialize the BitmapFont InitBMFont(str, fntFile, dimensions, labelFormat.Alignment, labelFormat.LineAlignment, imageOffset, texture); } else if(this.labelFormat.FormatFlags == CCLabelFormatFlags.SpriteFont) { // Initialize the SpriteFont InitSpriteFont(str, fntFile, size, dimensions, labelFormat, imageOffset, texture); } else if(this.labelFormat.FormatFlags == CCLabelFormatFlags.SystemFont) { LabelType = CCLabelType.SystemFont; SystemFont = fntFile; SystemFontSize = size; Dimensions = dimensions; AnchorPoint = CCPoint.AnchorMiddle; BlendFunc = CCBlendFunc.AlphaBlend; Text = str; } } internal void Reset () { systemFontDirty = false; systemFont = "Helvetica"; systemFontSize = 12; } internal CCFontAtlas FontAtlas { get {return fontAtlas;} set { if (value != fontAtlas) { fontAtlas = value; if (reusedLetter == null) { reusedLetter = new CCSprite(); reusedLetter.IsColorModifiedByOpacity = isColorModifiedByOpacity; reusedLetter.AnchorPoint = CCPoint.AnchorUpperLeft; } if (fontAtlas != null) { if (TextureAtlas != null) Texture = FontAtlas.GetTexture(0); else TextureAtlas = new CCTextureAtlas(FontAtlas.GetTexture(0), defaultSpriteBatchCapacity); quadCommand.Texture = TextureAtlas.Texture; LineHeight = fontAtlas.CommonHeight; IsDirty = true; } } } } protected void InitBMFont(string theString, string fntFile, CCSize dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment, CCPoint imageOffset, CCTexture2D texture) { Debug.Assert(FontConfiguration == null, "re-init is no longer supported"); Debug.Assert((theString == null && fntFile == null) || (theString != null && fntFile != null), "Invalid params for CCLabelBMFont"); if (!String.IsNullOrEmpty(fntFile)) { try { FontAtlas = CCFontAtlasCache.GetFontAtlasFNT(fntFile, imageOffset); } catch {} if (FontAtlas == null) { CCLog.Log("Bitmap Font CCLabel: Impossible to create font. Please check file: '{0}'", fntFile); return; } } AnchorPoint = CCPoint.AnchorMiddle; FontConfiguration = CCBMFontConfiguration.FontConfigurationWithFile(fntFile); LabelType = CCLabelType.BitMapFont; if (String.IsNullOrEmpty(theString)) { theString = String.Empty; } // Initialize the TextureAtlas along with children. var capacity = theString.Length; BlendFunc = CCBlendFunc.AlphaBlend; if (capacity == 0) { capacity = defaultSpriteBatchCapacity; } UpdateBlendFunc(); // no lazy alloc in this node Children = new CCRawList<CCNode>(capacity); Descendants = new CCRawList<CCSprite>(capacity); this.labelDimensions = dimensions; horzAlignment = hAlignment; vertAlignment = vAlignment; IsOpacityCascaded = true; // We use base here so we do not trigger an update internally. base.ContentSize = CCSize.Zero; IsColorModifiedByOpacity = TextureAtlas.Texture.HasPremultipliedAlpha; AnchorPoint = CCPoint.AnchorMiddle; ImageOffset = imageOffset; Text = theString; } protected void InitSpriteFont(string theString, string fntFile, float fontSize, CCSize dimensions, CCLabelFormat labelFormat, CCPoint imageOffset, CCTexture2D texture) { Debug.Assert((theString == null && fntFile == null) || (theString != null && fntFile != null), "Invalid params for CCLabel SpriteFont"); if (!String.IsNullOrEmpty(fntFile)) { try { FontAtlas = CCFontAtlasCache.GetFontAtlasSpriteFont(fntFile, fontSize, imageOffset); Scale = FontAtlas.Font.FontScale; } catch {} if (FontAtlas == null) { CCLog.Log("SpriteFont CCLabel: Impossible to create font. Please check file: '{0}'", fntFile); return; } } AnchorPoint = CCPoint.AnchorMiddle; LabelType = CCLabelType.SpriteFont; if (String.IsNullOrEmpty(theString)) { theString = String.Empty; } // Initialize the TextureAtlas along with children. var capacity = theString.Length; BlendFunc = CCBlendFunc.AlphaBlend; if (capacity == 0) { capacity = defaultSpriteBatchCapacity; } UpdateBlendFunc(); // no lazy alloc in this node Children = new CCRawList<CCNode>(capacity); Descendants = new CCRawList<CCSprite>(capacity); this.labelDimensions = dimensions; horzAlignment = labelFormat.Alignment; vertAlignment = labelFormat.LineAlignment; IsOpacityCascaded = true; ContentSize = CCSize.Zero; IsColorModifiedByOpacity = TextureAtlas.Texture.HasPremultipliedAlpha; AnchorPoint = CCPoint.AnchorMiddle; ImageOffset = imageOffset; Text = theString; } #endregion Constructors public override void UpdateDisplayedColor(CCColor3B parentColor) { var displayedColor = CCColor3B.White; displayedColor.R = (byte)(RealColor.R * parentColor.R / 255.0f); displayedColor.G = (byte)(RealColor.G * parentColor.G / 255.0f); displayedColor.B = (byte)(RealColor.B * parentColor.B / 255.0f); base.UpdateDisplayedColor(displayedColor); if (LabelType == CCLabelType.SystemFont && textSprite != null) { textSprite.UpdateDisplayedColor(displayedColor); } } protected internal override void UpdateDisplayedOpacity(byte parentOpacity) { var displayedOpacity = (byte) (RealOpacity * parentOpacity / 255.0f); base.UpdateDisplayedOpacity(displayedOpacity); if (LabelType == CCLabelType.SystemFont && textSprite != null) { textSprite.UpdateDisplayedOpacity(displayedOpacity); } } public override void UpdateColor() { if (TextureAtlas != null && !string.IsNullOrEmpty(labelText)) { quadCommand.RequestUpdateQuads(UpdateColorCallback); } } void UpdateColorCallback(ref CCV3F_C4B_T2F_Quad[] quads) { if (TextureAtlas == null) { return; } var color4 = new CCColor4B( DisplayedColor.R, DisplayedColor.G, DisplayedColor.B, DisplayedOpacity ); // special opacity for premultiplied textures if (IsColorModifiedByOpacity) { color4.R = (byte)(color4.R * DisplayedOpacity / 255.0f); color4.G = (byte)(color4.G * DisplayedOpacity / 255.0f); color4.B = (byte)(color4.B * DisplayedOpacity / 255.0f); } if (quads != null) { var totalQuads = quads.Length; CCV3F_C4B_T2F_Quad quad; for (int index = 0; index < totalQuads; ++index) { quad = quads[index]; quad.BottomLeft.Colors = color4; quad.BottomRight.Colors = color4; quad.TopLeft.Colors = color4; quad.TopRight.Colors = color4; TextureAtlas.UpdateQuad(ref quad, index); } } } public override bool IsColorModifiedByOpacity { get { return isColorModifiedByOpacity; } set { if (isColorModifiedByOpacity != value) { isColorModifiedByOpacity = value; UpdateColor(); } } } bool isUpdatingContent = false; protected void UpdateContent() { if (isUpdatingContent) return; isUpdatingContent = true; if (string.IsNullOrEmpty(Text)) { return; } if (FontAtlas != null) { LayoutLabel(); } else { if (LabelType == CCLabelType.SystemFont) { var fontDefinition = new CCFontDefinition(); fontDefinition.FontName = systemFont; fontDefinition.FontSize = systemFontSize; fontDefinition.Alignment = labelFormat.Alignment; fontDefinition.LineAlignment = labelFormat.LineAlignment; fontDefinition.Dimensions = Dimensions; fontDefinition.FontFillColor = DisplayedColor; fontDefinition.FontAlpha = DisplayedOpacity; fontDefinition.LineBreak = labelFormat.LineBreaking; fontDefinition.isShouldAntialias = IsAntialiased; CreateSpriteWithFontDefinition(fontDefinition); } } IsDirty = false; isUpdatingContent = false; } CCSprite textSprite = null; void CreateSpriteWithFontDefinition(CCFontDefinition fontDefinition) { if (textSprite != null) textSprite.RemoveFromParent(); var texture = CreateTextSprite(Text, fontDefinition); textSprite = new CCSprite(texture); textSprite.IsAntialiased = isAntialiased; textSprite.BlendFunc = BlendFunc; textSprite.AnchorPoint = CCPoint.AnchorLowerLeft; base.ContentSize = textSprite.ContentSize; base.AddChild(textSprite,0,TagInvalid); textSprite.UpdateDisplayedColor(DisplayedColor); textSprite.UpdateDisplayedOpacity(DisplayedOpacity); } protected void UpdateFont() { if (FontAtlas != null) { //CCFontAtlasCache.ReleaseFontAtlas(FontAtlas); FontAtlas = null; } IsDirty = true; systemFontDirty = false; } void UpdateQuads() { int index; int lettersCount = lettersInfo.Count; var contentScaleFactor = DefaultTexelToContentSizeRatios; for (int ctr = 0; ctr < lettersCount; ++ctr) { var letterDef = lettersInfo[ctr].Definition; if (letterDef.IsValidDefinition) { reusedRect = letterDef.Subrect; reusedLetter.Texture = Texture; // make sure we set AtlasIndex to not initialized here or first character does not display correctly reusedLetter.AtlasIndex = CCMacros.CCSpriteIndexNotInitialized; reusedLetter.TextureRectInPixels = reusedRect; reusedLetter.ContentSize = reusedRect.Size / contentScaleFactor; reusedLetter.Position = lettersInfo[ctr].Position; index = TextureAtlas.TotalQuads; var letterInfo = lettersInfo[ctr]; letterInfo.AtlasIndex = index; lettersInfo[ctr] = letterInfo; InsertGlyph(reusedLetter, index); } } quadCommand.Quads = TextureAtlas.Quads.Elements; quadCommand.QuadCount = TextureAtlas.Quads.Count; } const float MAX_BOUNDS = 8388608; void LayoutLabel () { if (FontAtlas == null || string.IsNullOrEmpty(Text)) { ContentSize = CCSize.Zero; return; } TextureAtlas.RemoveAllQuads(); Descendants.Clear(); lettersInfo.Clear(); FontAtlas.PrepareLetterDefinitions(Text); var start = 0; var typesetter = new CCTLTextLayout(this); var length = Text.Length; var insetBounds = labelDimensions; var layoutAvailable = true; if (insetBounds.Width <= 0) { insetBounds.Width = MAX_BOUNDS; layoutAvailable = false; } if (insetBounds.Height <= 0) { insetBounds.Height = MAX_BOUNDS; layoutAvailable = false; } var contentScaleFactorWidth = CCLabel.DefaultTexelToContentSizeRatios.Width; var contentScaleFactorHeight = CCLabel.DefaultTexelToContentSizeRatios.Height; var scaleX = ScaleX; var scaleY = ScaleY; List<CCTLLine> lineList = new List<CCTLLine>(); var boundingSize = CCSize.Zero; while (start < length) { // Now we ask the typesetter to break off a line for us. // This also will take into account line feeds embedded in the text. // Example: "This is text \n with a line feed embedded inside it" int count = typesetter.SuggestLineBreak(start, insetBounds.Width); var line = typesetter.GetLine(start, start + count); lineList.Add(line); if (line.Bounds.Width > boundingSize.Width) boundingSize.Width = line.Bounds.Width; boundingSize.Height += line.Bounds.Height; start += count; } if (!layoutAvailable) { if (insetBounds.Width == MAX_BOUNDS) { insetBounds.Width = boundingSize.Width; } if (insetBounds.Height == MAX_BOUNDS) { insetBounds.Height = boundingSize.Height; } } // Calculate our vertical starting position var totalHeight = lineList.Count * LineHeight; var nextFontPositionY = totalHeight; if (layoutAvailable && labelDimensions.Height > 0) { var labelHeightPixel = labelDimensions.Height / scaleY * contentScaleFactorHeight; if (totalHeight > labelHeightPixel) { int numLines = (int)(labelHeightPixel / LineHeight); totalHeight = numLines * LineHeight; } switch (VerticalAlignment) { case CCVerticalTextAlignment.Top: nextFontPositionY = labelHeightPixel; break; case CCVerticalTextAlignment.Center: nextFontPositionY = (labelHeightPixel + totalHeight) * 0.5f; break; case CCVerticalTextAlignment.Bottom: nextFontPositionY = totalHeight; break; default: break; } } var lineGlyphIndex = 0; float longestLine = 0; // Used for calculating overlapping on last line character var lastCharWidth = 0.0f; int lastCharAdvance = 0; // Define our horizontal justification var flushFactor = (float)HorizontalAlignment / (float)CCTextAlignment.Right; // We now loop through all of our line's glyph runs foreach (var line in lineList) { var gliphRun = line.GlyphRun; var lineWidth = line.Bounds.Width * contentScaleFactorWidth; var flushWidth = (layoutAvailable) ? insetBounds.Width / scaleX : boundingSize.Width; var flush = line.PenOffsetForFlush(flushFactor, flushWidth) ; foreach (var glyph in gliphRun) { var letterPosition = glyph.Position; var letterDef = glyph.Definition; lastCharWidth = letterDef.Width * contentScaleFactorWidth; letterPosition.X += flush; letterPosition.Y = (nextFontPositionY - letterDef.YOffset) / contentScaleFactorHeight; var tmpInfo = new LetterInfo(); tmpInfo.Definition = letterDef; tmpInfo.Position = letterPosition; tmpInfo.ContentSize.Width = letterDef.Width; tmpInfo.ContentSize.Height = letterDef.Height; if (lineGlyphIndex >= lettersInfo.Count) { lettersInfo.Add(tmpInfo); } else { lettersInfo[lineGlyphIndex] = tmpInfo; } lineGlyphIndex++; lastCharAdvance = (int)glyph.Definition.XAdvance; } // calculate our longest line which is used for calculating our ContentSize if (lineWidth > longestLine) longestLine = lineWidth; nextFontPositionY -= LineHeight; } CCSize tmpSize; // If the last character processed has an xAdvance which is less that the width of the characters image, then we need // to adjust the width of the string to take this into account, or the character will overlap the end of the bounding // box if(lastCharAdvance < lastCharWidth) { tmpSize.Width = longestLine - lastCharAdvance + lastCharWidth; } else { tmpSize.Width = longestLine; } tmpSize.Height = totalHeight; if (labelDimensions.Height > 0) { tmpSize.Height = labelDimensions.Height * contentScaleFactorHeight; } // We use base here so we do not trigger an update internally. base.ContentSize = tmpSize / CCLabel.DefaultTexelToContentSizeRatios; lineList.Clear(); CCRect uvRect; CCSprite letterSprite; for (int c = 0; c < Children.Count; c++) { letterSprite = (CCSprite)Children[c]; int tag = letterSprite.Tag; if(tag >= length) { RemoveChild(letterSprite, true); } else if(tag >= 0) { if (letterSprite != null) { uvRect = lettersInfo[tag].Definition.Subrect; letterSprite.TextureRectInPixels = uvRect; letterSprite.ContentSize = uvRect.Size; } } } UpdateQuads(); UpdateColor(); } public new CCNode this[int letterIndex] { get { if (LabelType == CCLabelType.SystemFont) { return null; } if (IsDirty) { UpdateContent(); } var contentScaleFactor = DefaultTexelToContentSizeRatios; if (letterIndex < lettersInfo.Count) { var letter = lettersInfo[letterIndex]; if(! letter.Definition.IsValidDefinition) return null; var sp = (this.GetChildByTag(letterIndex)) as CCSprite; if (sp == null) { var uvRect = letter.Definition.Subrect; sp = new CCSprite(FontAtlas.GetTexture(letter.Definition.TextureID), uvRect); // The calculations for untrimmed size already take into account the // content scale factor so here we back it out or the sprite shows // up with the incorrect ratio. sp.UntrimmedSizeInPixels = uvRect.Size * contentScaleFactor; // Calc position offset taking into account the content scale factor. var offset = new CCSize((uvRect.Size.Width * 0.5f) / contentScaleFactor.Width, (uvRect.Size.Height * 0.5f) / contentScaleFactor.Height); // apply the offset to the letter position sp.PositionX = letter.Position.X + offset.Width; sp.PositionY = letter.Position.Y - offset.Height; sp.Opacity = Opacity; AddSpriteWithoutQuad(sp, letter.AtlasIndex, letterIndex); } return sp; } return null; } } private void AddSpriteWithoutQuad(CCSprite child, int z, int aTag) { Debug.Assert(child != null, "Argument must be non-NULL"); // quad index is Z child.AtlasIndex = z; child.TextureAtlas = TextureAtlas; int i = 0; if (Descendants.Count > 0) { CCSprite[] elements = Descendants.Elements; for (int j = 0, count = Descendants.Count; j < count; j++) { if (elements[i].AtlasIndex <= z) { ++i; } } } Descendants.Insert(i, child); base.AddChild(child, z, aTag); } #region Child management public override void AddChild(CCNode child, int zOrder = 0, int tag = CCNode.TagInvalid) { Debug.Assert(false, "AddChild is not allowed on CCLabel"); } private void InsertGlyph(CCSprite sprite, int atlasIndex) { Debug.Assert(sprite != null, "child should not be null"); if (TextureAtlas.TotalQuads == TextureAtlas.Capacity) { IncreaseAtlasCapacity(); } sprite.AtlasIndex = atlasIndex; sprite.TextureAtlas = TextureAtlas; var quad = sprite.Quad; TextureAtlas.InsertQuad(ref quad, atlasIndex); sprite.UpdateLocalTransformedSpriteTextureQuads(); } #endregion protected void IncreaseAtlasCapacity() { // if we're going beyond the current TextureAtlas's capacity, // all the previously initialized sprites will need to redo their texture coords // this is likely computationally expensive int quantity = (TextureAtlas.Capacity + 1) * 4 / 3; CCLog.Log(string.Format( "CocosSharp: CCLabel: resizing TextureAtlas capacity from [{0}] to [{1}].", TextureAtlas.Capacity, quantity)); TextureAtlas.ResizeCapacity(quantity); } public override void Visit(ref CCAffineTransform parentWorldTransform) { if (!Visible || string.IsNullOrEmpty(Text)) { return; } if (systemFontDirty) { UpdateFont(); } if (IsDirty) { UpdateContent(); } var worldTransform = CCAffineTransform.Identity; var affineLocalTransform = AffineLocalTransform; CCAffineTransform.Concat(ref affineLocalTransform, ref parentWorldTransform, out worldTransform); if (textSprite != null) textSprite.Visit(ref worldTransform); else VisitRenderer(ref worldTransform); } protected override void VisitRenderer(ref CCAffineTransform worldTransform) { // Optimization: Fast Dispatch if (TextureAtlas == null || TextureAtlas.TotalQuads == 0) { return; } // Loop through each of our children nodes that may have actions attached. foreach(CCSprite child in Children) { if (child.Tag >= 0) { child.UpdateLocalTransformedSpriteTextureQuads(); } } quadCommand.GlobalDepth = worldTransform.Tz; quadCommand.WorldTransform = worldTransform; Renderer.AddCommand(quadCommand); } } }
using System; using System.Collections.Generic; using System.Linq; namespace Barebone.Routing { public class RouteTree{ StaticNode _root = new StaticNode(string.Empty); Dictionary<string, Route> _routesById = new Dictionary<string, Route>(); public void Add(params Route[] routes){ foreach (var route in routes) { Add(route); } } public void Add(Route route){ var addRouteToDictionary = !string.IsNullOrEmpty(route.Id); if(addRouteToDictionary){ if (_routesById.ContainsKey(route.Id)) { throw new RouteAlreadyExistsException(route.Id); } } var segments = new Stack<Segment>(route.Segments.Segments.Reverse()); AddInternal(route, segments, _root); if(addRouteToDictionary){ _routesById.Add(route.Id, route); } } private void AddInternal(Route route, Stack<Segment> segments, StaticNode node){ if (segments.Count == 0) { node.Leaves.Add(route); return; } var segment = segments.Pop(); if (segment is StaticSegment) { StaticNode subNode; node.StaticSegments.Add(segment, out subNode); AddInternal(route, segments, subNode); } else { node.Leaves.Add(route); } } public void RemoveRoute(string routeId){ if(routeId == null) throw new ArgumentNullException("routeId", "parameterId may not be null"); if(routeId.Equals(string.Empty)) throw new ArgumentException("routeId is empty", "parameterId"); if (!_routesById.ContainsKey(routeId)) throw new ArgumentException("routeId", string.Format("Route with id {0} is not available in the routing table", routeId)); var route = _routesById[routeId]; RemoveRoute(route); } public void RemoveRoute(Route route){ _root.Remove(route); } public Route[] GetAllRoutes(){ return _root.GetAllRoutes().ToArray(); } public List<Route> GetCandidates(string path, string method) { var segments = path.Substring(1, path.Length - 1).Split('/'); var result = new List<Route>(); FindCandidates(segments, method, 0, _root, result); return result.OrderByDescending(x => x.Priority).ToList(); } private void FindCandidates(string[] segments, string method, int currentSegment, StaticNode node, List<Route> result){ var pathIsNotTooLong = currentSegment < segments.Length; if (pathIsNotTooLong){ var nextSegment = segments[currentSegment]; var subNode = node.StaticSegments.Get(nextSegment); if (subNode != null) { FindCandidates(segments, method, currentSegment + 1, subNode, result); } } foreach (var route in node.Leaves) { if (route.Method == method && route.Segments.Segments.Length == segments.Length) { result.Add(route); } } } sealed class StaticNode { /// <summary> /// Part of the path of the segment. /// </summary> /// <value>The path.</value> public string Path {get; private set;} /// <summary> /// List of Routes which have futher static segements /// </summary> /// <value>The static segments.</value> public StaticSegments StaticSegments { get; private set; } /// <summary> /// List of all Routes which do not have further static segements /// </summary> /// <value>The dynamics.</value> public Leaves Leaves {get; set;} public StaticNode (string path) { Path = path; StaticSegments = new StaticSegments(); Leaves = new Leaves(); } public void Remove(Route route){ StaticSegments.Remove(route); Leaves.Remove(route); } public IEnumerable<Route> GetAllRoutes(){ return StaticSegments.GetAllRoutes().Union(Leaves); } public override bool Equals(object obj){ if (!(obj is StaticNode)) return false; return (obj as StaticNode).Path.Equals(this.Path); } public override int GetHashCode(){ return Path.GetHashCode(); } public override string ToString(){ return Path; } } class StaticSegments { Dictionary<string, StaticNode> _nodes = new Dictionary<string, StaticNode>(); public void Add(Segment node, out StaticNode target){ if (!_nodes.ContainsKey(node.Value)) { lock (this) { if (!_nodes.ContainsKey(node.Value)) { _nodes.Add(node.Value, new StaticNode(node.Value)); } } } target = _nodes[node.Value]; } public StaticNode Get(string segment){ if (!_nodes.ContainsKey(segment)) return null; return _nodes[segment]; } public void Remove(Route route){ foreach (var item in _nodes.Values) { item.Remove(route); } } public IEnumerable<Route> GetAllRoutes(){ return _nodes.Values.SelectMany(x => x.GetAllRoutes()); } } class Leaves : IEnumerable<Route> { List<Route> _routes = new List<Route>(); public void Add(Route route){ _routes.Add(route); } public IEnumerator<Route> GetEnumerator(){ return _routes.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator(){ return _routes.GetEnumerator(); } public void Remove(Route route){ _routes.Remove(route); } } } }
// 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.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; #if !MSBUILD12 using Microsoft.Build.Construction; #endif using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.MSBuild { /// <summary> /// A workspace that can be populated by opening MSBuild solution and project files. /// </summary> public sealed class MSBuildWorkspace : Workspace { // used to serialize access to public methods private readonly NonReentrantLock _serializationLock = new NonReentrantLock(); private MSBuildProjectLoader _loader; private MSBuildWorkspace( HostServices hostServices, ImmutableDictionary<string, string> properties) : base(hostServices, "MSBuildWorkspace") { _loader = new MSBuildProjectLoader(this, properties); } /// <summary> /// Create a new instance of a workspace that can be populated by opening solution and project files. /// </summary> public static MSBuildWorkspace Create() { return Create(ImmutableDictionary<string, string>.Empty); } /// <summary> /// Create a new instance of a workspace that can be populated by opening solution and project files. /// </summary> /// <param name="properties">An optional set of MSBuild properties used when interpreting project files. /// These are the same properties that are passed to msbuild via the /property:&lt;n&gt;=&lt;v&gt; command line argument.</param> public static MSBuildWorkspace Create(IDictionary<string, string> properties) { return Create(properties, DesktopMefHostServices.DefaultServices); } /// <summary> /// Create a new instance of a workspace that can be populated by opening solution and project files. /// </summary> /// <param name="hostServices">The <see cref="HostServices"/> used to configure this workspace.</param> public static MSBuildWorkspace Create(HostServices hostServices) { return Create(ImmutableDictionary<string, string>.Empty, hostServices); } /// <summary> /// Create a new instance of a workspace that can be populated by opening solution and project files. /// </summary> /// <param name="properties">The MSBuild properties used when interpreting project files. /// These are the same properties that are passed to msbuild via the /property:&lt;n&gt;=&lt;v&gt; command line argument.</param> /// <param name="hostServices">The <see cref="HostServices"/> used to configure this workspace.</param> public static MSBuildWorkspace Create(IDictionary<string, string> properties, HostServices hostServices) { if (properties == null) { throw new ArgumentNullException(nameof(properties)); } if (hostServices == null) { throw new ArgumentNullException(nameof(hostServices)); } return new MSBuildWorkspace(hostServices, properties.ToImmutableDictionary()); } /// <summary> /// The MSBuild properties used when interpreting project files. /// These are the same properties that are passed to msbuild via the /property:&lt;n&gt;=&lt;v&gt; command line argument. /// </summary> public ImmutableDictionary<string, string> Properties { get { return _loader.Properties; } } /// <summary> /// Determines if metadata from existing output assemblies is loaded instead of opening referenced projects. /// If the referenced project is already opened, the metadata will not be loaded. /// If the metadata assembly cannot be found the referenced project will be opened instead. /// </summary> public bool LoadMetadataForReferencedProjects { get { return _loader.LoadMetadataForReferencedProjects; } set { _loader.LoadMetadataForReferencedProjects = value; } } /// <summary> /// Determines if unrecognized projects are skipped when solutions or projects are opened. /// /// An project is unrecognized if it either has /// a) an invalid file path, /// b) a non-existent project file, /// c) has an unrecognized file extension or /// d) a file extension associated with an unsupported language. /// /// If unrecognized projects cannot be skipped a corresponding exception is thrown. /// </summary> public bool SkipUnrecognizedProjects { get { return _loader.SkipUnrecognizedProjects; } set { _loader.SkipUnrecognizedProjects = value; } } /// <summary> /// Associates a project file extension with a language name. /// </summary> public void AssociateFileExtensionWithLanguage(string projectFileExtension, string language) { _loader.AssociateFileExtensionWithLanguage(projectFileExtension, language); } /// <summary> /// Close the open solution, and reset the workspace to a new empty solution. /// </summary> public void CloseSolution() { using (_serializationLock.DisposableWait()) { this.ClearSolution(); } } private string GetAbsolutePath(string path, string baseDirectoryPath) { return Path.GetFullPath(FileUtilities.ResolveRelativePath(path, baseDirectoryPath) ?? path); } #region Open Solution & Project /// <summary> /// Open a solution file and all referenced projects. /// </summary> public async Task<Solution> OpenSolutionAsync(string solutionFilePath, CancellationToken cancellationToken = default(CancellationToken)) { if (solutionFilePath == null) { throw new ArgumentNullException(nameof(solutionFilePath)); } this.ClearSolution(); var solutionInfo = await _loader.LoadSolutionInfoAsync(solutionFilePath, cancellationToken: cancellationToken).ConfigureAwait(false); // construct workspace from loaded project infos this.OnSolutionAdded(solutionInfo); this.UpdateReferencesAfterAdd(); return this.CurrentSolution; } /// <summary> /// Open a project file and all referenced projects. /// </summary> public async Task<Project> OpenProjectAsync(string projectFilePath, CancellationToken cancellationToken = default(CancellationToken)) { if (projectFilePath == null) { throw new ArgumentNullException(nameof(projectFilePath)); } var projects = await _loader.LoadProjectInfoAsync(projectFilePath, GetCurrentProjectMap(), cancellationToken).ConfigureAwait(false); // add projects to solution foreach (var project in projects) { this.OnProjectAdded(project); } this.UpdateReferencesAfterAdd(); return this.CurrentSolution.GetProject(projects[0].Id); } private ImmutableDictionary<string, ProjectId> GetCurrentProjectMap() { return this.CurrentSolution.Projects .Where(p => !string.IsNullOrEmpty(p.FilePath)) .ToImmutableDictionary(p => p.FilePath, p => p.Id); } #endregion #region Apply Changes public override bool CanApplyChange(ApplyChangesKind feature) { switch (feature) { case ApplyChangesKind.ChangeDocument: case ApplyChangesKind.AddDocument: case ApplyChangesKind.RemoveDocument: case ApplyChangesKind.AddMetadataReference: case ApplyChangesKind.RemoveMetadataReference: case ApplyChangesKind.AddProjectReference: case ApplyChangesKind.RemoveProjectReference: case ApplyChangesKind.AddAnalyzerReference: case ApplyChangesKind.RemoveAnalyzerReference: return true; default: return false; } } private bool HasProjectFileChanges(ProjectChanges changes) { return changes.GetAddedDocuments().Any() || changes.GetRemovedDocuments().Any() || changes.GetAddedMetadataReferences().Any() || changes.GetRemovedMetadataReferences().Any() || changes.GetAddedProjectReferences().Any() || changes.GetRemovedProjectReferences().Any() || changes.GetAddedAnalyzerReferences().Any() || changes.GetRemovedAnalyzerReferences().Any(); } private IProjectFile _applyChangesProjectFile; public override bool TryApplyChanges(Solution newSolution) { return TryApplyChanges(newSolution, new ProgressTracker()); } internal override bool TryApplyChanges(Solution newSolution, IProgressTracker progressTracker) { using (_serializationLock.DisposableWait()) { return base.TryApplyChanges(newSolution, progressTracker); } } protected override void ApplyProjectChanges(ProjectChanges projectChanges) { System.Diagnostics.Debug.Assert(_applyChangesProjectFile == null); var project = projectChanges.OldProject ?? projectChanges.NewProject; try { // if we need to modify the project file, load it first. if (this.HasProjectFileChanges(projectChanges)) { var projectPath = project.FilePath; IProjectFileLoader loader; if (_loader.TryGetLoaderFromProjectPath(projectPath, out loader)) { try { _applyChangesProjectFile = loader.LoadProjectFileAsync(projectPath, _loader.Properties, CancellationToken.None).Result; } catch (System.IO.IOException exception) { this.OnWorkspaceFailed(new ProjectDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, projectChanges.ProjectId)); } } } // do normal apply operations base.ApplyProjectChanges(projectChanges); // save project file if (_applyChangesProjectFile != null) { try { _applyChangesProjectFile.Save(); } catch (System.IO.IOException exception) { this.OnWorkspaceFailed(new ProjectDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, projectChanges.ProjectId)); } } } finally { _applyChangesProjectFile = null; } } protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText text) { var document = this.CurrentSolution.GetDocument(documentId); if (document != null) { Encoding encoding = DetermineEncoding(text, document); this.SaveDocumentText(documentId, document.FilePath, text, encoding ?? new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); this.OnDocumentTextChanged(documentId, text, PreservationMode.PreserveValue); } } private static Encoding DetermineEncoding(SourceText text, Document document) { if (text.Encoding != null) { return text.Encoding; } try { using (ExceptionHelpers.SuppressFailFast()) { using (var stream = new FileStream(document.FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { var onDiskText = EncodedStringText.Create(stream); return onDiskText.Encoding; } } } catch (IOException) { } catch (InvalidDataException) { } return null; } protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text) { System.Diagnostics.Debug.Assert(_applyChangesProjectFile != null); var project = this.CurrentSolution.GetProject(info.Id.ProjectId); IProjectFileLoader loader; if (_loader.TryGetLoaderFromProjectPath(project.FilePath, out loader)) { var extension = _applyChangesProjectFile.GetDocumentExtension(info.SourceCodeKind); var fileName = Path.ChangeExtension(info.Name, extension); var relativePath = (info.Folders != null && info.Folders.Count > 0) ? Path.Combine(Path.Combine(info.Folders.ToArray()), fileName) : fileName; var fullPath = GetAbsolutePath(relativePath, Path.GetDirectoryName(project.FilePath)); var newDocumentInfo = info.WithName(fileName) .WithFilePath(fullPath) .WithTextLoader(new FileTextLoader(fullPath, text.Encoding)); // add document to project file _applyChangesProjectFile.AddDocument(relativePath); // add to solution this.OnDocumentAdded(newDocumentInfo); // save text to disk if (text != null) { this.SaveDocumentText(info.Id, fullPath, text, text.Encoding ?? Encoding.UTF8); } } } private void SaveDocumentText(DocumentId id, string fullPath, SourceText newText, Encoding encoding) { try { using (ExceptionHelpers.SuppressFailFast()) { var dir = Path.GetDirectoryName(fullPath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } Debug.Assert(encoding != null); using (var writer = new StreamWriter(fullPath, append: false, encoding: encoding)) { newText.Write(writer); } } } catch (IOException exception) { this.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, id)); } } protected override void ApplyDocumentRemoved(DocumentId documentId) { Debug.Assert(_applyChangesProjectFile != null); var document = this.CurrentSolution.GetDocument(documentId); if (document != null) { _applyChangesProjectFile.RemoveDocument(document.FilePath); this.DeleteDocumentFile(document.Id, document.FilePath); this.OnDocumentRemoved(documentId); } } private void DeleteDocumentFile(DocumentId documentId, string fullPath) { try { if (File.Exists(fullPath)) { File.Delete(fullPath); } } catch (IOException exception) { this.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, documentId)); } catch (NotSupportedException exception) { this.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, documentId)); } catch (UnauthorizedAccessException exception) { this.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, documentId)); } } protected override void ApplyMetadataReferenceAdded(ProjectId projectId, MetadataReference metadataReference) { Debug.Assert(_applyChangesProjectFile != null); var identity = GetAssemblyIdentity(projectId, metadataReference); _applyChangesProjectFile.AddMetadataReference(metadataReference, identity); this.OnMetadataReferenceAdded(projectId, metadataReference); } protected override void ApplyMetadataReferenceRemoved(ProjectId projectId, MetadataReference metadataReference) { Debug.Assert(_applyChangesProjectFile != null); var identity = GetAssemblyIdentity(projectId, metadataReference); _applyChangesProjectFile.RemoveMetadataReference(metadataReference, identity); this.OnMetadataReferenceRemoved(projectId, metadataReference); } private AssemblyIdentity GetAssemblyIdentity(ProjectId projectId, MetadataReference metadataReference) { var project = this.CurrentSolution.GetProject(projectId); if (!project.MetadataReferences.Contains(metadataReference)) { project = project.AddMetadataReference(metadataReference); } var compilation = project.GetCompilationAsync(CancellationToken.None).WaitAndGetResult_CanCallOnBackground(CancellationToken.None); var symbol = compilation.GetAssemblyOrModuleSymbol(metadataReference) as IAssemblySymbol; return symbol != null ? symbol.Identity : null; } protected override void ApplyProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference) { Debug.Assert(_applyChangesProjectFile != null); var project = this.CurrentSolution.GetProject(projectReference.ProjectId); if (project != null) { _applyChangesProjectFile.AddProjectReference(project.Name, new ProjectFileReference(project.FilePath, projectReference.Aliases)); } this.OnProjectReferenceAdded(projectId, projectReference); } protected override void ApplyProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference) { Debug.Assert(_applyChangesProjectFile != null); var project = this.CurrentSolution.GetProject(projectReference.ProjectId); if (project != null) { _applyChangesProjectFile.RemoveProjectReference(project.Name, project.FilePath); } this.OnProjectReferenceRemoved(projectId, projectReference); } protected override void ApplyAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference) { Debug.Assert(_applyChangesProjectFile != null); _applyChangesProjectFile.AddAnalyzerReference(analyzerReference); this.OnAnalyzerReferenceAdded(projectId, analyzerReference); } protected override void ApplyAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference) { Debug.Assert(_applyChangesProjectFile != null); _applyChangesProjectFile.RemoveAnalyzerReference(analyzerReference); this.OnAnalyzerReferenceRemoved(projectId, analyzerReference); } } #endregion }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace Plotter.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Threading; using System.Threading.Tasks; namespace System.Data.Common { internal static partial class ADP { // The class ADP defines the exceptions that are specific to the Adapters. // The class contains functions that take the proper informational variables and then construct // the appropriate exception with an error string obtained from the resource framework. // The exception is then returned to the caller, so that the caller may then throw from its // location so that the catcher of the exception will have the appropriate call stack. // This class is used so that there will be compile time checking of error messages. internal static Task<T> CreatedTaskWithCancellation<T>() => Task.FromCanceled<T>(new CancellationToken(true)); // this method accepts BID format as an argument, this attribute allows FXCopBid rule to validate calls to it static partial void TraceException(string trace, Exception e) { Debug.Assert(e != null, "TraceException: null Exception"); if (e != null) { DataCommonEventSource.Log.Trace(trace, e); } } internal static void TraceExceptionForCapture(Exception e) { Debug.Assert(IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!"); TraceException("<comm.ADP.TraceException|ERR|CATCH> '{0}'", e); } internal static DataException Data(string message) { DataException e = new DataException(message); TraceExceptionAsReturnValue(e); return e; } internal static void CheckArgumentLength(string value, string parameterName) { CheckArgumentNull(value, parameterName); if (0 == value.Length) { throw Argument(SR.Format(SR.ADP_EmptyString, parameterName)); } } internal static void CheckArgumentLength(Array value, string parameterName) { CheckArgumentNull(value, parameterName); if (0 == value.Length) { throw Argument(SR.Format(SR.ADP_EmptyArray, parameterName)); } } // Invalid Enumeration internal static ArgumentOutOfRangeException InvalidAcceptRejectRule(AcceptRejectRule value) { #if DEBUG switch (value) { case AcceptRejectRule.None: case AcceptRejectRule.Cascade: Debug.Fail("valid AcceptRejectRule " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(AcceptRejectRule), (int)value); } // DbCommandBuilder.CatalogLocation internal static ArgumentOutOfRangeException InvalidCatalogLocation(CatalogLocation value) { #if DEBUG switch (value) { case CatalogLocation.Start: case CatalogLocation.End: Debug.Fail("valid CatalogLocation " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(CatalogLocation), (int)value); } internal static ArgumentOutOfRangeException InvalidConflictOptions(ConflictOption value) { #if DEBUG switch (value) { case ConflictOption.CompareAllSearchableValues: case ConflictOption.CompareRowVersion: case ConflictOption.OverwriteChanges: Debug.Fail("valid ConflictOption " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(ConflictOption), (int)value); } // IDataAdapter.Update internal static ArgumentOutOfRangeException InvalidDataRowState(DataRowState value) { #if DEBUG switch (value) { case DataRowState.Detached: case DataRowState.Unchanged: case DataRowState.Added: case DataRowState.Deleted: case DataRowState.Modified: Debug.Fail("valid DataRowState " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(DataRowState), (int)value); } // KeyRestrictionBehavior internal static ArgumentOutOfRangeException InvalidKeyRestrictionBehavior(KeyRestrictionBehavior value) { #if DEBUG switch (value) { case KeyRestrictionBehavior.PreventUsage: case KeyRestrictionBehavior.AllowOnly: Debug.Fail("valid KeyRestrictionBehavior " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(KeyRestrictionBehavior), (int)value); } // IDataAdapter.FillLoadOption internal static ArgumentOutOfRangeException InvalidLoadOption(LoadOption value) { #if DEBUG switch (value) { case LoadOption.OverwriteChanges: case LoadOption.PreserveChanges: case LoadOption.Upsert: Debug.Fail("valid LoadOption " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(LoadOption), (int)value); } // IDataAdapter.MissingMappingAction internal static ArgumentOutOfRangeException InvalidMissingMappingAction(MissingMappingAction value) { #if DEBUG switch (value) { case MissingMappingAction.Passthrough: case MissingMappingAction.Ignore: case MissingMappingAction.Error: Debug.Fail("valid MissingMappingAction " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(MissingMappingAction), (int)value); } // IDataAdapter.MissingSchemaAction internal static ArgumentOutOfRangeException InvalidMissingSchemaAction(MissingSchemaAction value) { #if DEBUG switch (value) { case MissingSchemaAction.Add: case MissingSchemaAction.Ignore: case MissingSchemaAction.Error: case MissingSchemaAction.AddWithKey: Debug.Fail("valid MissingSchemaAction " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(MissingSchemaAction), (int)value); } internal static ArgumentOutOfRangeException InvalidRule(Rule value) { #if DEBUG switch (value) { case Rule.None: case Rule.Cascade: case Rule.SetNull: case Rule.SetDefault: Debug.Fail("valid Rule " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(Rule), (int)value); } // IDataAdapter.FillSchema internal static ArgumentOutOfRangeException InvalidSchemaType(SchemaType value) { #if DEBUG switch (value) { case SchemaType.Source: case SchemaType.Mapped: Debug.Fail("valid SchemaType " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(SchemaType), (int)value); } // RowUpdatingEventArgs.StatementType internal static ArgumentOutOfRangeException InvalidStatementType(StatementType value) { #if DEBUG switch (value) { case StatementType.Select: case StatementType.Insert: case StatementType.Update: case StatementType.Delete: case StatementType.Batch: Debug.Fail("valid StatementType " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(StatementType), (int)value); } // RowUpdatingEventArgs.UpdateStatus internal static ArgumentOutOfRangeException InvalidUpdateStatus(UpdateStatus value) { #if DEBUG switch (value) { case UpdateStatus.Continue: case UpdateStatus.ErrorsOccurred: case UpdateStatus.SkipAllRemainingRows: case UpdateStatus.SkipCurrentRow: Debug.Fail("valid UpdateStatus " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(UpdateStatus), (int)value); } internal static ArgumentOutOfRangeException NotSupportedStatementType(StatementType value, string method) { return NotSupportedEnumerationValue(typeof(StatementType), value.ToString(), method); } // // DbConnectionOptions, DataAccess // internal static ArgumentException InvalidKeyname(string parameterName) { return Argument(SR.ADP_InvalidKey, parameterName); } internal static ArgumentException InvalidValue(string parameterName) { return Argument(SR.ADP_InvalidValue, parameterName); } // // DataAccess // internal static Exception WrongType(Type got, Type expected) { return Argument(SR.Format(SR.SQL_WrongType, got, expected)); } // // Generic Data Provider Collection // internal static Exception CollectionUniqueValue(Type itemType, string propertyName, string propertyValue) { return Argument(SR.Format(SR.ADP_CollectionUniqueValue, itemType.Name, propertyName, propertyValue)); } // IDbDataAdapter.Fill(Schema) internal static InvalidOperationException MissingSelectCommand(string method) { return Provider(SR.Format(SR.ADP_MissingSelectCommand, method)); } // // AdapterMappingException // private static InvalidOperationException DataMapping(string error) { return InvalidOperation(error); } // DataColumnMapping.GetDataColumnBySchemaAction internal static InvalidOperationException ColumnSchemaExpression(string srcColumn, string cacheColumn) { return DataMapping(SR.Format(SR.ADP_ColumnSchemaExpression, srcColumn, cacheColumn)); } // DataColumnMapping.GetDataColumnBySchemaAction internal static InvalidOperationException ColumnSchemaMismatch(string srcColumn, Type srcType, DataColumn column) { return DataMapping(SR.Format(SR.ADP_ColumnSchemaMismatch, srcColumn, srcType.Name, column.ColumnName, column.DataType.Name)); } // DataColumnMapping.GetDataColumnBySchemaAction internal static InvalidOperationException ColumnSchemaMissing(string cacheColumn, string tableName, string srcColumn) { if (string.IsNullOrEmpty(tableName)) { return InvalidOperation(SR.Format(SR.ADP_ColumnSchemaMissing1, cacheColumn, tableName, srcColumn)); } return DataMapping(SR.Format(SR.ADP_ColumnSchemaMissing2, cacheColumn, tableName, srcColumn)); } // DataColumnMappingCollection.GetColumnMappingBySchemaAction internal static InvalidOperationException MissingColumnMapping(string srcColumn) { return DataMapping(SR.Format(SR.ADP_MissingColumnMapping, srcColumn)); } // DataTableMapping.GetDataTableBySchemaAction internal static InvalidOperationException MissingTableSchema(string cacheTable, string srcTable) { return DataMapping(SR.Format(SR.ADP_MissingTableSchema, cacheTable, srcTable)); } // DataTableMappingCollection.GetTableMappingBySchemaAction internal static InvalidOperationException MissingTableMapping(string srcTable) { return DataMapping(SR.Format(SR.ADP_MissingTableMapping, srcTable)); } // DbDataAdapter.Update internal static InvalidOperationException MissingTableMappingDestination(string dstTable) { return DataMapping(SR.Format(SR.ADP_MissingTableMappingDestination, dstTable)); } // // DataColumnMappingCollection, DataAccess // internal static Exception InvalidSourceColumn(string parameter) { return Argument(SR.ADP_InvalidSourceColumn, parameter); } internal static Exception ColumnsAddNullAttempt(string parameter) { return CollectionNullValue(parameter, typeof(DataColumnMappingCollection), typeof(DataColumnMapping)); } internal static Exception ColumnsDataSetColumn(string cacheColumn) { return CollectionIndexString(typeof(DataColumnMapping), ADP.DataSetColumn, cacheColumn, typeof(DataColumnMappingCollection)); } internal static Exception ColumnsIndexInt32(int index, IColumnMappingCollection collection) { return CollectionIndexInt32(index, collection.GetType(), collection.Count); } internal static Exception ColumnsIndexSource(string srcColumn) { return CollectionIndexString(typeof(DataColumnMapping), ADP.SourceColumn, srcColumn, typeof(DataColumnMappingCollection)); } internal static Exception ColumnsIsNotParent(ICollection collection) { return ParametersIsNotParent(typeof(DataColumnMapping), collection); } internal static Exception ColumnsIsParent(ICollection collection) { return ParametersIsParent(typeof(DataColumnMapping), collection); } internal static Exception ColumnsUniqueSourceColumn(string srcColumn) { return CollectionUniqueValue(typeof(DataColumnMapping), ADP.SourceColumn, srcColumn); } internal static Exception NotADataColumnMapping(object value) { return CollectionInvalidType(typeof(DataColumnMappingCollection), typeof(DataColumnMapping), value); } // // DataTableMappingCollection, DataAccess // internal static Exception InvalidSourceTable(string parameter) { return Argument(SR.ADP_InvalidSourceTable, parameter); } internal static Exception TablesAddNullAttempt(string parameter) { return CollectionNullValue(parameter, typeof(DataTableMappingCollection), typeof(DataTableMapping)); } internal static Exception TablesDataSetTable(string cacheTable) { return CollectionIndexString(typeof(DataTableMapping), ADP.DataSetTable, cacheTable, typeof(DataTableMappingCollection)); } internal static Exception TablesIndexInt32(int index, ITableMappingCollection collection) { return CollectionIndexInt32(index, collection.GetType(), collection.Count); } internal static Exception TablesIsNotParent(ICollection collection) { return ParametersIsNotParent(typeof(DataTableMapping), collection); } internal static Exception TablesIsParent(ICollection collection) { return ParametersIsParent(typeof(DataTableMapping), collection); } internal static Exception TablesSourceIndex(string srcTable) { return CollectionIndexString(typeof(DataTableMapping), ADP.SourceTable, srcTable, typeof(DataTableMappingCollection)); } internal static Exception TablesUniqueSourceTable(string srcTable) { return CollectionUniqueValue(typeof(DataTableMapping), ADP.SourceTable, srcTable); } internal static Exception NotADataTableMapping(object value) { return CollectionInvalidType(typeof(DataTableMappingCollection), typeof(DataTableMapping), value); } // // IDbCommand // internal static InvalidOperationException UpdateConnectionRequired(StatementType statementType, bool isRowUpdatingCommand) { string resource; if (isRowUpdatingCommand) { resource = SR.ADP_ConnectionRequired_Clone; } else { switch (statementType) { case StatementType.Insert: resource = SR.ADP_ConnectionRequired_Insert; break; case StatementType.Update: resource = SR.ADP_ConnectionRequired_Update; break; case StatementType.Delete: resource = SR.ADP_ConnectionRequired_Delete; break; case StatementType.Batch: resource = SR.ADP_ConnectionRequired_Batch; goto default; #if DEBUG case StatementType.Select: Debug.Fail("shouldn't be here"); goto default; #endif default: throw ADP.InvalidStatementType(statementType); } } return InvalidOperation(resource); } internal static InvalidOperationException ConnectionRequired_Res(string method) => InvalidOperation("ADP_ConnectionRequired_" + method); internal static InvalidOperationException UpdateOpenConnectionRequired(StatementType statementType, bool isRowUpdatingCommand, ConnectionState state) { string resource; if (isRowUpdatingCommand) { resource = SR.ADP_OpenConnectionRequired_Clone; } else { switch (statementType) { case StatementType.Insert: resource = SR.ADP_OpenConnectionRequired_Insert; break; case StatementType.Update: resource = SR.ADP_OpenConnectionRequired_Update; break; case StatementType.Delete: resource = SR.ADP_OpenConnectionRequired_Delete; break; #if DEBUG case StatementType.Select: Debug.Fail("shouldn't be here"); goto default; case StatementType.Batch: Debug.Fail("isRowUpdatingCommand should have been true"); goto default; #endif default: throw ADP.InvalidStatementType(statementType); } } return InvalidOperation(SR.Format(resource, ADP.ConnectionStateMsg(state))); } // // DbDataAdapter // internal static ArgumentException UnwantedStatementType(StatementType statementType) { return Argument(SR.Format(SR.ADP_UnwantedStatementType, statementType.ToString())); } // // DbDataAdapter.FillSchema // internal static Exception FillSchemaRequiresSourceTableName(string parameter) { return Argument(SR.ADP_FillSchemaRequiresSourceTableName, parameter); } // // DbDataAdapter.Fill // internal static Exception InvalidMaxRecords(string parameter, int max) { return Argument(SR.Format(SR.ADP_InvalidMaxRecords, max.ToString(CultureInfo.InvariantCulture)), parameter); } internal static Exception InvalidStartRecord(string parameter, int start) { return Argument(SR.Format(SR.ADP_InvalidStartRecord, start.ToString(CultureInfo.InvariantCulture)), parameter); } internal static Exception FillRequires(string parameter) { return ArgumentNull(parameter); } internal static Exception FillRequiresSourceTableName(string parameter) { return Argument(SR.ADP_FillRequiresSourceTableName, parameter); } internal static Exception FillChapterAutoIncrement() { return InvalidOperation(SR.ADP_FillChapterAutoIncrement); } internal static InvalidOperationException MissingDataReaderFieldType(int index) { return DataAdapter(SR.Format(SR.ADP_MissingDataReaderFieldType, index)); } internal static InvalidOperationException OnlyOneTableForStartRecordOrMaxRecords() { return DataAdapter(SR.ADP_OnlyOneTableForStartRecordOrMaxRecords); } // // DbDataAdapter.Update // internal static ArgumentNullException UpdateRequiresNonNullDataSet(string parameter) { return ArgumentNull(parameter); } internal static InvalidOperationException UpdateRequiresSourceTable(string defaultSrcTableName) { return InvalidOperation(SR.Format(SR.ADP_UpdateRequiresSourceTable, defaultSrcTableName)); } internal static InvalidOperationException UpdateRequiresSourceTableName(string srcTable) { return InvalidOperation(SR.Format(SR.ADP_UpdateRequiresSourceTableName, srcTable)); } internal static ArgumentNullException UpdateRequiresDataTable(string parameter) { return ArgumentNull(parameter); } internal static Exception UpdateConcurrencyViolation(StatementType statementType, int affected, int expected, DataRow[] dataRows) { string resource; switch (statementType) { case StatementType.Update: resource = SR.ADP_UpdateConcurrencyViolation_Update; break; case StatementType.Delete: resource = SR.ADP_UpdateConcurrencyViolation_Delete; break; case StatementType.Batch: resource = SR.ADP_UpdateConcurrencyViolation_Batch; break; #if DEBUG case StatementType.Select: case StatementType.Insert: Debug.Fail("should be here"); goto default; #endif default: throw ADP.InvalidStatementType(statementType); } DBConcurrencyException exception = new DBConcurrencyException(SR.Format(resource, affected.ToString(CultureInfo.InvariantCulture), expected.ToString(CultureInfo.InvariantCulture)), null, dataRows); TraceExceptionAsReturnValue(exception); return exception; } internal static InvalidOperationException UpdateRequiresCommand(StatementType statementType, bool isRowUpdatingCommand) { string resource; if (isRowUpdatingCommand) { resource = SR.ADP_UpdateRequiresCommandClone; } else { switch (statementType) { case StatementType.Select: resource = SR.ADP_UpdateRequiresCommandSelect; break; case StatementType.Insert: resource = SR.ADP_UpdateRequiresCommandInsert; break; case StatementType.Update: resource = SR.ADP_UpdateRequiresCommandUpdate; break; case StatementType.Delete: resource = SR.ADP_UpdateRequiresCommandDelete; break; #if DEBUG case StatementType.Batch: Debug.Fail("isRowUpdatingCommand should have been true"); goto default; #endif default: throw ADP.InvalidStatementType(statementType); } } return InvalidOperation(resource); } internal static ArgumentException UpdateMismatchRowTable(int i) { return Argument(SR.Format(SR.ADP_UpdateMismatchRowTable, i.ToString(CultureInfo.InvariantCulture))); } internal static DataException RowUpdatedErrors() { return Data(SR.ADP_RowUpdatedErrors); } internal static DataException RowUpdatingErrors() { return Data(SR.ADP_RowUpdatingErrors); } internal static InvalidOperationException ResultsNotAllowedDuringBatch() { return DataAdapter(SR.ADP_ResultsNotAllowedDuringBatch); } // // : DbDataAdapter // internal static InvalidOperationException DynamicSQLJoinUnsupported() { return InvalidOperation(SR.ADP_DynamicSQLJoinUnsupported); } internal static InvalidOperationException DynamicSQLNoTableInfo() { return InvalidOperation(SR.ADP_DynamicSQLNoTableInfo); } internal static InvalidOperationException DynamicSQLNoKeyInfoDelete() { return InvalidOperation(SR.ADP_DynamicSQLNoKeyInfoDelete); } internal static InvalidOperationException DynamicSQLNoKeyInfoUpdate() { return InvalidOperation(SR.ADP_DynamicSQLNoKeyInfoUpdate); } internal static InvalidOperationException DynamicSQLNoKeyInfoRowVersionDelete() { return InvalidOperation(SR.ADP_DynamicSQLNoKeyInfoRowVersionDelete); } internal static InvalidOperationException DynamicSQLNoKeyInfoRowVersionUpdate() { return InvalidOperation(SR.ADP_DynamicSQLNoKeyInfoRowVersionUpdate); } internal static InvalidOperationException DynamicSQLNestedQuote(string name, string quote) { return InvalidOperation(SR.Format(SR.ADP_DynamicSQLNestedQuote, name, quote)); } internal static InvalidOperationException NoQuoteChange() { return InvalidOperation(SR.ADP_NoQuoteChange); } internal static InvalidOperationException MissingSourceCommand() { return InvalidOperation(SR.ADP_MissingSourceCommand); } internal static InvalidOperationException MissingSourceCommandConnection() { return InvalidOperation(SR.ADP_MissingSourceCommandConnection); } // global constant strings internal const string ConnectionString = "ConnectionString"; internal const string DataSetColumn = "DataSetColumn"; internal const string DataSetTable = "DataSetTable"; internal const string Fill = "Fill"; internal const string FillSchema = "FillSchema"; internal const string SourceColumn = "SourceColumn"; internal const string SourceTable = "SourceTable"; internal static DataRow[] SelectAdapterRows(DataTable dataTable, bool sorted) { const DataRowState rowStates = DataRowState.Added | DataRowState.Deleted | DataRowState.Modified; // equivalent to but faster than 'return dataTable.Select("", "", rowStates);' int countAdded = 0, countDeleted = 0, countModifed = 0; DataRowCollection rowCollection = dataTable.Rows; foreach (DataRow dataRow in rowCollection) { switch (dataRow.RowState) { case DataRowState.Added: countAdded++; break; case DataRowState.Deleted: countDeleted++; break; case DataRowState.Modified: countModifed++; break; default: Debug.Assert(0 == (rowStates & dataRow.RowState), "flagged RowState"); break; } } var dataRows = new DataRow[countAdded + countDeleted + countModifed]; if (sorted) { countModifed = countAdded + countDeleted; countDeleted = countAdded; countAdded = 0; foreach (DataRow dataRow in rowCollection) { switch (dataRow.RowState) { case DataRowState.Added: dataRows[countAdded++] = dataRow; break; case DataRowState.Deleted: dataRows[countDeleted++] = dataRow; break; case DataRowState.Modified: dataRows[countModifed++] = dataRow; break; default: Debug.Assert(0 == (rowStates & dataRow.RowState), "flagged RowState"); break; } } } else { int index = 0; foreach (DataRow dataRow in rowCollection) { if (0 != (dataRow.RowState & rowStates)) { dataRows[index++] = dataRow; if (index == dataRows.Length) { break; } } } } return dataRows; } // { "a", "a", "a" } -> { "a", "a1", "a2" } // { "a", "a", "a1" } -> { "a", "a2", "a1" } // { "a", "A", "a" } -> { "a", "A1", "a2" } // { "a", "A", "a1" } -> { "a", "A2", "a1" } internal static void BuildSchemaTableInfoTableNames(string[] columnNameArray) { Dictionary<string, int> hash = new Dictionary<string, int>(columnNameArray.Length); int startIndex = columnNameArray.Length; // lowest non-unique index for (int i = columnNameArray.Length - 1; 0 <= i; --i) { string columnName = columnNameArray[i]; if ((null != columnName) && (0 < columnName.Length)) { columnName = columnName.ToLower(CultureInfo.InvariantCulture); int index; if (hash.TryGetValue(columnName, out index)) { startIndex = Math.Min(startIndex, index); } hash[columnName] = i; } else { columnNameArray[i] = string.Empty; startIndex = i; } } int uniqueIndex = 1; for (int i = startIndex; i < columnNameArray.Length; ++i) { string columnName = columnNameArray[i]; if (0 == columnName.Length) { // generate a unique name columnNameArray[i] = "Column"; uniqueIndex = GenerateUniqueName(hash, ref columnNameArray[i], i, uniqueIndex); } else { columnName = columnName.ToLower(CultureInfo.InvariantCulture); if (i != hash[columnName]) { GenerateUniqueName(hash, ref columnNameArray[i], i, 1); } } } } private static int GenerateUniqueName(Dictionary<string, int> hash, ref string columnName, int index, int uniqueIndex) { for (; ; ++uniqueIndex) { string uniqueName = columnName + uniqueIndex.ToString(CultureInfo.InvariantCulture); string lowerName = uniqueName.ToLower(CultureInfo.InvariantCulture); if (hash.TryAdd(lowerName, index)) { columnName = uniqueName; break; } } return uniqueIndex; } internal static int SrcCompare(string strA, string strB) => strA == strB ? 0 : 1; } }
// Visual Studio Shared Project // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; namespace Microsoft.VisualStudioTools.Project.Automation { /// <summary> /// This can navigate a collection object only (partial implementation of ProjectItems interface) /// </summary> [ComVisible(true)] public class OANavigableProjectItems : EnvDTE.ProjectItems { #region fields private OAProject project; private HierarchyNode nodeWithItems; #endregion #region properties /// <summary> /// Defines a relationship to the associated project. /// </summary> internal OAProject Project { get { return this.project; } } /// <summary> /// Defines the node that contains the items /// </summary> internal HierarchyNode NodeWithItems { get { return this.nodeWithItems; } } #endregion #region ctor /// <summary> /// Constructor. /// </summary> /// <param name="project">The associated project.</param> /// <param name="nodeWithItems">The node that defines the items.</param> internal OANavigableProjectItems(OAProject project, HierarchyNode nodeWithItems) { this.project = project; this.nodeWithItems = nodeWithItems; } #endregion #region EnvDTE.ProjectItems /// <summary> /// Gets a value indicating the number of objects in the collection. /// </summary> public virtual int Count { get { int count = 0; this.project.ProjectNode.Site.GetUIThread().Invoke(() => { for (HierarchyNode child = this.NodeWithItems.FirstChild; child != null; child = child.NextSibling) { if (!child.IsNonMemberItem && child.GetAutomationObject() is EnvDTE.ProjectItem) { count += 1; } } }); return count; } } /// <summary> /// Gets the immediate parent object of a ProjectItems collection. /// </summary> public virtual object Parent { get { return this.nodeWithItems.GetAutomationObject(); } } /// <summary> /// Gets an enumeration indicating the type of object. /// </summary> public virtual string Kind { get { // TODO: Add OAProjectItems.Kind getter implementation return null; } } /// <summary> /// Gets the top-level extensibility object. /// </summary> public virtual EnvDTE.DTE DTE { get { return (EnvDTE.DTE)this.project.DTE; } } /// <summary> /// Gets the project hosting the project item or items. /// </summary> public virtual EnvDTE.Project ContainingProject { get { return this.project; } } /// <summary> /// Adds one or more ProjectItem objects from a directory to the ProjectItems collection. /// </summary> /// <param name="directory">The directory from which to add the project item.</param> /// <returns>A ProjectItem object.</returns> public virtual EnvDTE.ProjectItem AddFromDirectory(string directory) { throw new NotImplementedException(); } /// <summary> /// Creates a new project item from an existing item template file and adds it to the project. /// </summary> /// <param name="fileName">The full path and file name of the template project file.</param> /// <param name="name">The file name to use for the new project item.</param> /// <returns>A ProjectItem object. </returns> public virtual EnvDTE.ProjectItem AddFromTemplate(string fileName, string name) { throw new NotImplementedException(); } /// <summary> /// Creates a new folder in Solution Explorer. /// </summary> /// <param name="name">The name of the folder node in Solution Explorer.</param> /// <param name="kind">The type of folder to add. The available values are based on vsProjectItemsKindConstants and vsProjectItemKindConstants</param> /// <returns>A ProjectItem object.</returns> public virtual EnvDTE.ProjectItem AddFolder(string name, string kind) { throw new NotImplementedException(); } /// <summary> /// Copies a source file and adds it to the project. /// </summary> /// <param name="filePath">The path and file name of the project item to be added.</param> /// <returns>A ProjectItem object. </returns> public virtual EnvDTE.ProjectItem AddFromFileCopy(string filePath) { throw new NotImplementedException(); } /// <summary> /// Adds a project item from a file that is installed in a project directory structure. /// </summary> /// <param name="fileName">The file name of the item to add as a project item. </param> /// <returns>A ProjectItem object. </returns> public virtual EnvDTE.ProjectItem AddFromFile(string fileName) { throw new NotImplementedException(); } /// <summary> /// Get Project Item from index /// </summary> /// <param name="index">Either index by number (1-based) or by name can be used to get the item</param> /// <returns>Project Item. ArgumentException if invalid index is specified</returns> public virtual EnvDTE.ProjectItem Item(object index) { // Changed from MPFProj: throws ArgumentException instead of returning null (http://mpfproj10.codeplex.com/workitem/9158) if (index is int) { int realIndex = (int)index - 1; if (realIndex >= 0) { for (HierarchyNode child = this.NodeWithItems.FirstChild; child != null; child = child.NextSibling) { if (child.IsNonMemberItem) { continue; } var item = child.GetAutomationObject() as EnvDTE.ProjectItem; if (item != null) { if (realIndex == 0) { return item; } realIndex -= 1; } } } } else if (index is string) { string name = (string)index; for (HierarchyNode child = this.NodeWithItems.FirstChild; child != null; child = child.NextSibling) { if (child.IsNonMemberItem) { continue; } var item = child.GetAutomationObject() as EnvDTE.ProjectItem; if (item != null && String.Compare(item.Name, name, StringComparison.OrdinalIgnoreCase) == 0) { return item; } } } throw new ArgumentException("Failed to find item: " + index); } /// <summary> /// Returns an enumeration for items in a collection. /// </summary> /// <returns>An IEnumerator for this object.</returns> public virtual IEnumerator GetEnumerator() { for (HierarchyNode child = this.NodeWithItems.FirstChild; child != null; child = child.NextSibling) { if (child.IsNonMemberItem) { continue; } var item = child.GetAutomationObject() as EnvDTE.ProjectItem; if (item != null) { yield return item; } } } #endregion } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Contract ** ** <OWNER>maf,mbarnett,[....]</OWNER> ** ** Implementation details of CLR Contracts. ** ===========================================================*/ #define DEBUG // The behavior of this contract library should be consistent regardless of build type. #if SILVERLIGHT #define FEATURE_UNTRUSTED_CALLERS #elif REDHAWK_RUNTIME #elif BARTOK_RUNTIME #else // CLR #define FEATURE_UNTRUSTED_CALLERS #define FEATURE_RELIABILITY_CONTRACTS #define FEATURE_SERIALIZATION #endif using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Reflection; #if FEATURE_RELIABILITY_CONTRACTS using System.Runtime.ConstrainedExecution; #endif #if FEATURE_UNTRUSTED_CALLERS using System.Security; using System.Security.Permissions; #endif namespace System.Diagnostics.Contracts { public static partial class Contract { #region Private Methods [ThreadStatic] private static bool _assertingMustUseRewriter; /// <summary> /// This method is used internally to trigger a failure indicating to the "programmer" that he is using the interface incorrectly. /// It is NEVER used to indicate failure of actual contracts at runtime. /// </summary> [SecuritySafeCritical] static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind) { if (_assertingMustUseRewriter) System.Diagnostics.Assert.Fail("Asserting that we must use the rewriter went reentrant.", "Didn't rewrite this mscorlib?"); _assertingMustUseRewriter = true; // For better diagnostics, report which assembly is at fault. Walk up stack and // find the first non-mscorlib assembly. Assembly thisAssembly = typeof(Contract).Assembly; // In case we refactor mscorlib, use Contract class instead of Object. StackTrace stack = new StackTrace(); Assembly probablyNotRewritten = null; for (int i = 0; i < stack.FrameCount; i++) { Assembly caller = stack.GetFrame(i).GetMethod().DeclaringType.Assembly; if (caller != thisAssembly) { probablyNotRewritten = caller; break; } } if (probablyNotRewritten == null) probablyNotRewritten = thisAssembly; String simpleName = probablyNotRewritten.GetName().Name; System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, Environment.GetResourceString("MustUseCCRewrite", contractKind, simpleName), null, null, null); _assertingMustUseRewriter = false; } #endregion Private Methods #region Failure Behavior /// <summary> /// Without contract rewriting, failing Assert/Assumes end up calling this method. /// Code going through the contract rewriter never calls this method. Instead, the rewriter produced failures call /// System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent, followed by /// System.Runtime.CompilerServices.ContractHelper.TriggerFailure. /// </summary> [SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework", MessageId = "System.Security.SecuritySafeCriticalAttribute")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif static partial void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", failureKind), "failureKind"); Contract.EndContractBlock(); // displayMessage == null means: yes we handled it. Otherwise it is the localized failure message var displayMessage = System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException); if (displayMessage == null) return; System.Runtime.CompilerServices.ContractHelper.TriggerFailure(failureKind, displayMessage, userMessage, conditionText, innerException); } #if !FEATURE_CORECLR || FEATURE_NETCORE /// <summary> /// Allows a managed application environment such as an interactive interpreter (IronPython) /// to be notified of contract failures and /// potentially "handle" them, either by throwing a particular exception type, etc. If any of the /// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will /// not pop up an assert dialog box or trigger escalation policy. Hooking this event requires /// full trust, because it will inform you of bugs in the appdomain and because the event handler /// could allow you to continue execution. /// </summary> public static event EventHandler<ContractFailedEventArgs> ContractFailed { #if FEATURE_UNTRUSTED_CALLERS [SecurityCritical] #if FEATURE_LINK_DEMAND [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] #endif #endif add { System.Runtime.CompilerServices.ContractHelper.InternalContractFailed += value; } #if FEATURE_UNTRUSTED_CALLERS [SecurityCritical] #if FEATURE_LINK_DEMAND [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] #endif #endif remove { System.Runtime.CompilerServices.ContractHelper.InternalContractFailed -= value; } } #endif // !FEATURE_CORECLR || FEATURE_NETCORE #endregion FailureBehavior } #if !FEATURE_CORECLR || FEATURE_NETCORE // Not usable on Silverlight by end users due to security, and full trust users have not yet expressed an interest. public sealed class ContractFailedEventArgs : EventArgs { private ContractFailureKind _failureKind; private String _message; private String _condition; private Exception _originalException; private bool _handled; private bool _unwind; internal Exception thrownDuringHandler; #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public ContractFailedEventArgs(ContractFailureKind failureKind, String message, String condition, Exception originalException) { Contract.Requires(originalException == null || failureKind == ContractFailureKind.PostconditionOnException); _failureKind = failureKind; _message = message; _condition = condition; _originalException = originalException; } public String Message { get { return _message; } } public String Condition { get { return _condition; } } public ContractFailureKind FailureKind { get { return _failureKind; } } public Exception OriginalException { get { return _originalException; } } // Whether the event handler "handles" this contract failure, or to fail via escalation policy. public bool Handled { get { return _handled; } } #if FEATURE_UNTRUSTED_CALLERS [SecurityCritical] #if FEATURE_LINK_DEMAND [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] #endif #endif public void SetHandled() { _handled = true; } public bool Unwind { get { return _unwind; } } #if FEATURE_UNTRUSTED_CALLERS [SecurityCritical] #if FEATURE_LINK_DEMAND [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] #endif #endif public void SetUnwind() { _unwind = true; } } #endif // !FEATURE_CORECLR || FEATURE_NETCORE #if FEATURE_SERIALIZATION [Serializable] #else [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors")] #endif [SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic")] internal sealed class ContractException : Exception { readonly ContractFailureKind _Kind; readonly string _UserMessage; readonly string _Condition; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public ContractFailureKind Kind { get { return _Kind; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string Failure { get { return this.Message; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string UserMessage { get { return _UserMessage; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string Condition { get { return _Condition; } } // Called by COM Interop, if we see COR_E_CODECONTRACTFAILED as an HRESULT. private ContractException() { HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED; } public ContractException(ContractFailureKind kind, string failure, string userMessage, string condition, Exception innerException) : base(failure, innerException) { HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED; this._Kind = kind; this._UserMessage = userMessage; this._Condition = condition; } #if FEATURE_SERIALIZATION private ContractException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { _Kind = (ContractFailureKind)info.GetInt32("Kind"); _UserMessage = info.GetString("UserMessage"); _Condition = info.GetString("Condition"); } #endif // FEATURE_SERIALIZATION #if FEATURE_UNTRUSTED_CALLERS && FEATURE_SERIALIZATION [SecurityCritical] #if FEATURE_LINK_DEMAND && FEATURE_SERIALIZATION [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] #endif // FEATURE_LINK_DEMAND #endif // FEATURE_UNTRUSTED_CALLERS public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); info.AddValue("Kind", _Kind); info.AddValue("UserMessage", _UserMessage); info.AddValue("Condition", _Condition); } } } namespace System.Runtime.CompilerServices { public static partial class ContractHelper { #region Private fields #if !FEATURE_CORECLR || FEATURE_NETCORE private static volatile EventHandler<ContractFailedEventArgs> contractFailedEvent; private static readonly Object lockObject = new Object(); #endif // !FEATURE_CORECLR || FEATURE_NETCORE internal const int COR_E_CODECONTRACTFAILED = unchecked((int)0x80131542); #endregion #if !FEATURE_CORECLR || FEATURE_NETCORE /// <summary> /// Allows a managed application environment such as an interactive interpreter (IronPython) or a /// web browser host (Jolt hosting Silverlight in IE) to be notified of contract failures and /// potentially "handle" them, either by throwing a particular exception type, etc. If any of the /// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will /// not pop up an assert dialog box or trigger escalation policy. Hooking this event requires /// full trust. /// </summary> internal static event EventHandler<ContractFailedEventArgs> InternalContractFailed { #if FEATURE_UNTRUSTED_CALLERS [SecurityCritical] #endif add { // Eagerly prepare each event handler _marked with a reliability contract_, to // attempt to reduce out of memory exceptions while reporting contract violations. // This only works if the new handler obeys the constraints placed on // constrained execution regions. Eagerly preparing non-reliable event handlers // would be a perf hit and wouldn't significantly improve reliability. // UE: Please mention reliable event handlers should also be marked with the // PrePrepareMethodAttribute to avoid CER eager preparation work when ngen'ed. System.Runtime.CompilerServices.RuntimeHelpers.PrepareContractedDelegate(value); lock (lockObject) { contractFailedEvent += value; } } #if FEATURE_UNTRUSTED_CALLERS [SecurityCritical] #endif remove { lock (lockObject) { contractFailedEvent -= value; } } } #endif // !FEATURE_CORECLR || FEATURE_NETCORE /// <summary> /// Rewriter will call this method on a contract failure to allow listeners to be notified. /// The method should not perform any failure (assert/throw) itself. /// This method has 3 functions: /// 1. Call any contract hooks (such as listeners to Contract failed events) /// 2. Determine if the listeneres deem the failure as handled (then resultFailureMessage should be set to null) /// 3. Produce a localized resultFailureMessage used in advertising the failure subsequently. /// </summary> /// <param name="resultFailureMessage">Should really be out (or the return value), but partial methods are not flexible enough. /// On exit: null if the event was handled and should not trigger a failure. /// Otherwise, returns the localized failure message</param> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS [SecuritySafeCritical] #endif static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException, ref string resultFailureMessage) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", failureKind), "failureKind"); Contract.EndContractBlock(); string returnValue; String displayMessage = "contract failed."; // Incomplete, but in case of OOM during resource lookup... #if !FEATURE_CORECLR || FEATURE_NETCORE ContractFailedEventArgs eventArgs = null; // In case of OOM. #endif // !FEATURE_CORECLR || FEATURE_NETCORE #if FEATURE_RELIABILITY_CONTRACTS System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions(); #endif try { displayMessage = GetDisplayMessage(failureKind, userMessage, conditionText); #if !FEATURE_CORECLR || FEATURE_NETCORE EventHandler<ContractFailedEventArgs> contractFailedEventLocal = contractFailedEvent; if (contractFailedEventLocal != null) { eventArgs = new ContractFailedEventArgs(failureKind, displayMessage, conditionText, innerException); foreach (EventHandler<ContractFailedEventArgs> handler in contractFailedEventLocal.GetInvocationList()) { try { handler(null, eventArgs); } catch (Exception e) { eventArgs.thrownDuringHandler = e; eventArgs.SetUnwind(); } } if (eventArgs.Unwind) { #if !FEATURE_CORECLR if (Environment.IsCLRHosted) TriggerCodeContractEscalationPolicy(failureKind, displayMessage, conditionText, innerException); #endif // unwind if (innerException == null) { innerException = eventArgs.thrownDuringHandler; } throw new ContractException(failureKind, displayMessage, userMessage, conditionText, innerException); } } #endif // !FEATURE_CORECLR || FEATURE_NETCORE } finally { #if !FEATURE_CORECLR || FEATURE_NETCORE if (eventArgs != null && eventArgs.Handled) { returnValue = null; // handled } else #endif // !FEATURE_CORECLR || FEATURE_NETCORE { returnValue = displayMessage; } } resultFailureMessage = returnValue; } /// <summary> /// Rewriter calls this method to get the default failure behavior. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "conditionText")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "userMessage")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "kind")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "innerException")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_UNTRUSTED_CALLERS && !FEATURE_CORECLR [SecuritySafeCritical] #endif static partial void TriggerFailureImplementation(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException) { // If we're here, our intent is to pop up a dialog box (if we can). For developers // interacting live with a debugger, this is a good experience. For Silverlight // hosted in Internet Explorer, the assert window is great. If we cannot // pop up a dialog box, throw an exception (consider a library compiled with // "Assert On Failure" but used in a process that can't pop up asserts, like an // NT Service). For the CLR hosted by server apps like SQL or Exchange, we should // trigger escalation policy. #if !FEATURE_CORECLR if (Environment.IsCLRHosted) { TriggerCodeContractEscalationPolicy(kind, displayMessage, conditionText, innerException); // Hosts like SQL may choose to abort the thread, so we will not get here in all cases. // But if the host's chosen action was to throw an exception, we should throw an exception // here (which is easier to do in managed code with the right parameters). throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException); } #endif // !FEATURE_CORECLR if (!Environment.UserInteractive) { throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException); } // May need to rethink Assert.Fail w/ TaskDialogIndirect as a model. Window title. Main instruction. Content. Expanded info. // Optional info like string for collapsed text vs. expanded text. String windowTitle = Environment.GetResourceString(GetResourceNameForFailure(kind)); const int numStackFramesToSkip = 2; // To make stack traces easier to read System.Diagnostics.Assert.Fail(conditionText, displayMessage, windowTitle, COR_E_CODECONTRACTFAILED, StackTrace.TraceFormat.Normal, numStackFramesToSkip); // If we got here, the user selected Ignore. Continue. } private static String GetResourceNameForFailure(ContractFailureKind failureKind, bool withCondition = false) { String resourceName = null; switch (failureKind) { case ContractFailureKind.Assert: resourceName = withCondition ? "AssertionFailed_Cnd" : "AssertionFailed"; break; case ContractFailureKind.Assume: resourceName = withCondition ? "AssumptionFailed_Cnd" : "AssumptionFailed"; break; case ContractFailureKind.Precondition: resourceName = withCondition ? "PreconditionFailed_Cnd" : "PreconditionFailed"; break; case ContractFailureKind.Postcondition: resourceName = withCondition ? "PostconditionFailed_Cnd" : "PostconditionFailed"; break; case ContractFailureKind.Invariant: resourceName = withCondition ? "InvariantFailed_Cnd" : "InvariantFailed"; break; case ContractFailureKind.PostconditionOnException: resourceName = withCondition ? "PostconditionOnExceptionFailed_Cnd" : "PostconditionOnExceptionFailed"; break; default: Contract.Assume(false, "Unreachable code"); resourceName = "AssumptionFailed"; break; } return resourceName; } #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif private static String GetDisplayMessage(ContractFailureKind failureKind, String userMessage, String conditionText) { String resourceName = GetResourceNameForFailure(failureKind, !String.IsNullOrEmpty(conditionText)); // Well-formatted English messages will take one of four forms. A sentence ending in // either a period or a colon, the condition string, then the message tacked // on to the end with two spaces in front. // Note that both the conditionText and userMessage may be null. Also, // on Silverlight we may not be able to look up a friendly string for the // error message. Let's leverage Silverlight's default error message there. String failureMessage; if (!String.IsNullOrEmpty(conditionText)) { failureMessage = Environment.GetResourceString(resourceName, conditionText); } else { failureMessage = Environment.GetResourceString(resourceName); } // Now add in the user message, if present. if (!String.IsNullOrEmpty(userMessage)) { return failureMessage + " " + userMessage; } else { return failureMessage; } } #if !FEATURE_CORECLR // Will trigger escalation policy, if hosted and the host requested us to do something (such as // abort the thread or exit the process). Starting in Dev11, for hosted apps the default behavior // is to throw an exception. // Implementation notes: // We implement our default behavior of throwing an exception by simply returning from our native // method inside the runtime and falling through to throw an exception. // We must call through this method before calling the method on the Environment class // because our security team does not yet support SecuritySafeCritical on P/Invoke methods. // Note this can be called in the context of throwing another exception (EnsuresOnThrow). [SecuritySafeCritical] [DebuggerNonUserCode] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private static void TriggerCodeContractEscalationPolicy(ContractFailureKind failureKind, String message, String conditionText, Exception innerException) { String exceptionAsString = null; if (innerException != null) exceptionAsString = innerException.ToString(); Environment.TriggerCodeContractFailure(failureKind, message, conditionText, exceptionAsString); } #endif // !FEATURE_CORECLR } } // namespace System.Runtime.CompilerServices
using System; using System.Collections.Generic; using System.Composition.Hosting; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OmniSharp.Endpoint.Exports; using OmniSharp.Mef; using OmniSharp.Models; using OmniSharp.Models.UpdateBuffer; using OmniSharp.Plugins; using OmniSharp.Protocol; namespace OmniSharp.Endpoint { public abstract class EndpointHandler { public abstract Task<object> Handle(RequestPacket packet); public static EndpointHandler Create<TRequest, TResponse>(IPredicateHandler languagePredicateHandler, CompositionHost host, ILogger logger, OmniSharpEndpointMetadata metadata, IEnumerable<Lazy<IRequestHandler, OmniSharpRequestHandlerMetadata>> handlers, Lazy<EndpointHandler<UpdateBufferRequest, object>> updateBufferHandler, IEnumerable<Plugin> plugins) { return new EndpointHandler<TRequest, TResponse>(languagePredicateHandler, host, logger, metadata, handlers.Where(x => x.Metadata.EndpointName == metadata.EndpointName), updateBufferHandler, plugins); } public static EndpointHandler Factory(IPredicateHandler languagePredicateHandler, CompositionHost host, ILogger logger, OmniSharpEndpointMetadata metadata, IEnumerable<Lazy<IRequestHandler, OmniSharpRequestHandlerMetadata>> handlers, Lazy<EndpointHandler<UpdateBufferRequest, object>> updateBufferHandler, IEnumerable<Plugin> plugins) { var createMethod = typeof(EndpointHandler).GetTypeInfo().DeclaredMethods.First(x => x.Name == nameof(EndpointHandler.Create)); return (EndpointHandler)createMethod.MakeGenericMethod(metadata.RequestType, metadata.ResponseType).Invoke(null, new object[] { languagePredicateHandler, host, logger, metadata, handlers, updateBufferHandler, plugins }); } } public class EndpointHandler<TRequest, TResponse> : EndpointHandler { private readonly CompositionHost _host; private readonly IPredicateHandler _languagePredicateHandler; private readonly Lazy<Task<Dictionary<string, ExportHandler<TRequest, TResponse>[]>>> _exports; private readonly OmniSharpWorkspace _workspace; private readonly bool _hasLanguageProperty; private readonly bool _hasFileNameProperty; private readonly bool _canBeAggregated; private readonly ILogger _logger; private readonly IEnumerable<Plugin> _plugins; private readonly Lazy<EndpointHandler<UpdateBufferRequest, object>> _updateBufferHandler; public EndpointHandler(IPredicateHandler languagePredicateHandler, CompositionHost host, ILogger logger, OmniSharpEndpointMetadata metadata, IEnumerable<Lazy<IRequestHandler, OmniSharpRequestHandlerMetadata>> handlers, Lazy<EndpointHandler<UpdateBufferRequest, object>> updateBufferHandler, IEnumerable<Plugin> plugins) { EndpointName = metadata.EndpointName; _host = host; _logger = logger; _languagePredicateHandler = languagePredicateHandler; _plugins = plugins; _workspace = host.GetExport<OmniSharpWorkspace>(); _hasLanguageProperty = metadata.RequestType.GetRuntimeProperty(nameof(LanguageModel.Language)) != null; _hasFileNameProperty = metadata.RequestType.GetRuntimeProperty(nameof(Request.FileName)) != null; _canBeAggregated = typeof(IAggregateResponse).IsAssignableFrom(metadata.ResponseType); _updateBufferHandler = updateBufferHandler; _exports = new Lazy<Task<Dictionary<string, ExportHandler<TRequest, TResponse>[]>>>(() => LoadExportHandlers(handlers)); } private Task<Dictionary<string, ExportHandler<TRequest, TResponse>[]>> LoadExportHandlers(IEnumerable<Lazy<IRequestHandler, OmniSharpRequestHandlerMetadata>> handlers) { var interfaceHandlers = handlers .Select(export => new RequestHandlerExportHandler<TRequest, TResponse>(export.Metadata.Language, (IRequestHandler<TRequest, TResponse>)export.Value)) .Cast<ExportHandler<TRequest, TResponse>>(); var plugins = _plugins.Where(x => x.Config.Endpoints.Contains(EndpointName)) .Select(plugin => new PluginExportHandler<TRequest, TResponse>(EndpointName, plugin)) .Cast<ExportHandler<TRequest, TResponse>>(); // Group handlers by language and sort each group for consistency return Task.FromResult(interfaceHandlers .Concat(plugins) .GroupBy(export => export.Language, StringComparer.OrdinalIgnoreCase) .ToDictionary( group => group.Key, group => group.OrderBy(g => g).ToArray())); } public string EndpointName { get; } public override Task<object> Handle(RequestPacket packet) { var requestObject = DeserializeRequestObject(packet.ArgumentsStream); var model = GetLanguageModel(requestObject); return Process(packet, model, requestObject); } public async Task<object> Process(RequestPacket packet, LanguageModel model, JToken requestObject) { var request = requestObject.ToObject<TRequest>(); if (request is Request && _updateBufferHandler.Value != null) { var realRequest = request as Request; if (!string.IsNullOrWhiteSpace(realRequest.FileName) && (realRequest.Buffer != null || realRequest.Changes != null)) { await _updateBufferHandler.Value.Process(packet, model, requestObject); } } if (_hasLanguageProperty) { // Handle cases where a request isn't aggrgate and a language isn't specified. // This helps with editors calling a legacy end point, for example /metadata if (!_canBeAggregated && string.IsNullOrWhiteSpace(model.Language)) { model.Language = LanguageNames.CSharp; } return await HandleLanguageRequest(model.Language, request, packet); } else if (_hasFileNameProperty) { var language = _languagePredicateHandler.GetLanguageForFilePath(model.FileName ?? string.Empty); return await HandleLanguageRequest(language, request, packet); } else { var language = _languagePredicateHandler.GetLanguageForFilePath(string.Empty); if (!string.IsNullOrEmpty(language)) { return await HandleLanguageRequest(language, request, packet); } } return await HandleAllRequest(request, packet); } private Task<object> HandleLanguageRequest(string language, TRequest request, RequestPacket packet) { if (!string.IsNullOrEmpty(language)) { return HandleRequestForLanguage(language, request, packet); } return HandleAllRequest(request, packet); } private async Task<IAggregateResponse> AggregateResponsesFromLanguageHandlers(ExportHandler<TRequest, TResponse>[] handlers, TRequest request) { if (!_canBeAggregated) { throw new NotSupportedException($"Must be able to aggregate responses from all handlers for {EndpointName}"); } IAggregateResponse aggregateResponse = null; if (handlers.Length == 1) { var response = handlers[0].Handle(request); return (IAggregateResponse)await response; } else { var responses = new List<Task<TResponse>>(); foreach (var handler in handlers) { responses.Add(handler.Handle(request)); } foreach (IAggregateResponse response in await Task.WhenAll(responses)) { if (aggregateResponse != null) { aggregateResponse = aggregateResponse.Merge(response); } else { aggregateResponse = response; } } } return aggregateResponse; } private async Task<object> GetFirstNotEmptyResponseFromHandlers(ExportHandler<TRequest, TResponse>[] handlers, TRequest request) { var responses = new List<Task<TResponse>>(); foreach (var handler in handlers) { responses.Add(handler.Handle(request)); } foreach (object response in await Task.WhenAll(responses)) { var canBeEmptyResponse = response as ICanBeEmptyResponse; if (canBeEmptyResponse != null) { if (!canBeEmptyResponse.IsEmpty) { return response; } } else if (response != null) { return response; } } return null; } private async Task<object> HandleRequestForLanguage(string language, TRequest request, RequestPacket packet) { var exports = await _exports.Value; if (exports.TryGetValue(language, out var handlers)) { if (_canBeAggregated) { return await AggregateResponsesFromLanguageHandlers(handlers, request); } return await GetFirstNotEmptyResponseFromHandlers(handlers, request); } throw new NotSupportedException($"{language} does not support {EndpointName}"); } private async Task<object> HandleAllRequest(TRequest request, RequestPacket packet) { if (!_canBeAggregated) { throw new NotSupportedException($"Must be able to aggregate the response to spread them out across all plugins for {EndpointName}"); } var exports = await _exports.Value; IAggregateResponse aggregateResponse = null; var responses = new List<Task<IAggregateResponse>>(); foreach (var export in exports) { responses.Add(AggregateResponsesFromLanguageHandlers(export.Value, request)); } foreach (IAggregateResponse exportResponse in await Task.WhenAll(responses)) { if (aggregateResponse != null) { aggregateResponse = aggregateResponse.Merge(exportResponse); } else { aggregateResponse = exportResponse; } } object response = aggregateResponse; if (response != null) { return response; } return null; } private LanguageModel GetLanguageModel(JToken jtoken) { var response = new LanguageModel(); var jobject = jtoken as JObject; if (jobject == null) { return response; } if (jobject.TryGetValue(nameof(LanguageModel.Language), StringComparison.OrdinalIgnoreCase, out var token)) { response.Language = token.ToString(); } if (jobject.TryGetValue(nameof(LanguageModel.FileName), StringComparison.OrdinalIgnoreCase, out token)) { response.FileName = token.ToString(); } return response; } private JToken DeserializeRequestObject(Stream readStream) { try { using (var streamReader = new StreamReader(readStream)) { using (var textReader = new JsonTextReader(streamReader)) { return JToken.Load(textReader); } } } catch { return new JObject(); } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="JsonTypeConverterProblem.cs"> // Copyright (c) 2011-2016 https://github.com/logjam2. // </copyright> // Licensed under the <a href="https://github.com/logjam2/logjam/blob/master/LICENSE.txt">Apache License, Version 2.0</a>; // you may not use this file except in compliance with the License. // -------------------------------------------------------------------------------------------------------------------- using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; using Xunit; using Xunit.Abstractions; using LogJam.Shared.Internal; public class A { public string Id { get; set; } public A Child { get; set; } } public class B : A { } public class C : A { } /// <summary> /// Shows the problem I'm having serializing classes with Json. /// </summary> public sealed class JsonTypeConverterProblem { private readonly ITestOutputHelper _testOutputHelper; public JsonTypeConverterProblem(ITestOutputHelper testOutputHelper) { Arg.NotNull(testOutputHelper, nameof(testOutputHelper)); _testOutputHelper = testOutputHelper; } [Fact(Skip = "Bug still exists")] public void ShowSerializationBug() { A a = new B() { Id = "foo", Child = new C() { Id = "bar" } }; JsonSerializerSettings jsonSettings = new JsonSerializerSettings { ContractResolver = new TypeHintContractResolver() }; string json = JsonConvert.SerializeObject(a, Formatting.Indented, jsonSettings); _testOutputHelper.WriteLine(json); Assert.Contains(@"""Target"": ""B""", json); Assert.Contains(@"""Is"": ""C""", json); } [Fact] public void DeserializationWorks() { string json = @"{ ""Target"": ""B"", ""Id"": ""foo"", ""Child"": { ""Is"": ""C"", ""Id"": ""bar"", } }"; JsonSerializerSettings jsonSettings = new JsonSerializerSettings { ContractResolver = new TypeHintContractResolver() }; A a = JsonConvert.DeserializeObject<A>(json, jsonSettings); Assert.IsType<B>(a); Assert.IsType<C>(a.Child); } } public class TypeHintContractResolver : DefaultContractResolver { public override JsonContract ResolveContract(Type type) { JsonContract contract = base.ResolveContract(type); if ((contract is JsonObjectContract) && ((type == typeof(A)) || (type == typeof(B)))) // In the real implementation, this is checking against a registry of types { contract.Converter = new TypeHintJsonConverter(type); } return contract; } } public class TypeHintJsonConverter : JsonConverter { private readonly Type _declaredType; public TypeHintJsonConverter(Type declaredType) { _declaredType = declaredType; } public override bool CanConvert(Type objectType) { return objectType == _declaredType; } // The real implementation of the next 2 methods uses reflection on concrete types to determine the declaredType hint. // TypeFromTypeHint and TypeHintPropertyForType are the inverse of each other. private Type TypeFromTypeHint(JObject jo) { if (new JValue("B").Equals(jo["Target"])) { return typeof(B); } else if (new JValue("A").Equals(jo["Hint"])) { return typeof(A); } else if (new JValue("C").Equals(jo["Is"])) { return typeof(C); } else { throw new ArgumentException("Type not recognized from JSON"); } } private JProperty TypeHintPropertyForType(Type type) { if (type == typeof(A)) { return new JProperty("Hint", "A"); } else if (type == typeof(B)) { return new JProperty("Target", "B"); } else if (type == typeof(C)) { return new JProperty("Is", "C"); } else { return null; } } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (! CanConvert(objectType)) { throw new InvalidOperationException("Can't convert declaredType " + objectType + "; expected " + _declaredType); } // Load JObject from stream. Turns out we're also called for null arrays of our objects, // so handle a null by returning one. var jToken = JToken.Load(reader); if (jToken.Type == JTokenType.Null) { return null; } if (jToken.Type != JTokenType.Object) { throw new InvalidOperationException("Json: expected " + _declaredType + "; got " + jToken.Type); } JObject jObject = (JObject) jToken; // Select the declaredType based on TypeHint Type deserializingType = TypeFromTypeHint(jObject); var target = Activator.CreateInstance(deserializingType); serializer.Populate(jObject.CreateReader(), target); return target; } public override bool CanWrite { get { return true; } } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { JProperty typeHintProperty = TypeHintPropertyForType(value.GetType()); //BUG: JsonSerializationException : Self referencing loop detected with type 'B'. Path ''. // Same error occurs whether I use the serializer parameter or a separate serializer. JObject jo = JObject.FromObject(value, serializer); if (typeHintProperty != null) { jo.AddFirst(typeHintProperty); } writer.WriteToken(jo.CreateReader()); } }
using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.Drawing; namespace IronAHK.Rusty { partial class Core { static bool? OnOff(string mode) { switch (mode.ToLowerInvariant()) { case Keyword_On: case "1": return true; case Keyword_Off: case "0": return false; default: return null; } } static bool IsAnyBlank(params string[] args) { foreach (var str in args) if (string.IsNullOrEmpty(str)) return true; return false; } static Dictionary<char, string> KeyValues(string Options, bool Lowercase, char[] Exceptions) { var table = new Dictionary<char, string>(); var buf = new StringBuilder(); int i = 0; bool exp = false; char key = default(char); string val; if (Lowercase) for (i = 0; i < Exceptions.Length; i++) Exceptions[i] = char.ToLowerInvariant(Exceptions[i]); i = 0; while (i < Options.Length) { char sym = Options[i]; i++; if (char.IsWhiteSpace(sym) || i == Options.Length) { if (buf.Length == 0) continue; if (exp) { exp = false; val = buf.ToString(); buf.Length = 0; if (table.ContainsKey(key)) table[key] = val; else table.Add(key, val); continue; } key = buf[0]; if (Lowercase) key = char.ToLowerInvariant(key); foreach (var ex in Exceptions) if (key == ex) { exp = true; buf.Length = 0; continue; } val = buf.Length > 1 ? buf.Remove(0, 1).ToString() : string.Empty; if (table.ContainsKey(key)) table[key] = val; else table.Add(key, val); buf.Length = 0; } else buf.Append(sym); } if (exp && key != default(char)) { if (table.ContainsKey(key)) table[key] = null; else table.Add(key, null); } return table; } static List<string> ParseFlags(ref string arg) { var list = new List<string>(); const char flag = '*'; var i = -1; foreach (var sym in arg) { i++; if (Array.IndexOf(Keyword_Spaces, sym) != -1) continue; if (sym != flag) break; var z = i; for (; i < arg.Length; i++) if (char.IsWhiteSpace(arg, i) || arg[i] == flag) break; if (z == i) continue; var item = arg.Substring(z, i - z); list.Add(item); } arg = arg.Substring(i); return list; } static string[] ParseOptions(string options) { return options.Split(Keyword_Spaces, StringSplitOptions.RemoveEmptyEntries); } static bool IsOption(string options, string search) { if (string.IsNullOrEmpty(options) || string.IsNullOrEmpty(search)) return false; return options.Trim().Equals(search, StringComparison.OrdinalIgnoreCase); } static bool OptionContains(string options, params string[] keys) { foreach (string key in keys) if (!OptionContains(options, key)) return false; return true; } static bool OptionContains(string options, string key, bool casesensitive = false) { // TODO: test OptionContains method var comp = casesensitive ? StringComparison.CurrentCulture : StringComparison.OrdinalIgnoreCase; var i = 0; while (i < options.Length) { var z = options.IndexOf(key, i, comp); var p = z == 0 || !char.IsLetter(options, z - 1); z += key.Length; if (!p) continue; p = z == options.Length || !char.IsLetter(options, z + 1); if (!p) continue; return true; } return false; } static Dictionary<string, string> ParseOptionsRegex(ref string options, Dictionary<string, Regex> items, bool remove = true) { var results = new Dictionary<string, string>(); foreach(var item in items) { if(item.Value.IsMatch(options)) { var match = item.Value.Match(options).Groups[1].Captures[0]; results.Add(item.Key, match.Value); if(remove) options = options.Substring(0, match.Index) + options.Substring(match.Index + match.Length); } else { results.Add(item.Key, ""); } } return results; } /// <summary> /// Parse a string and get Coordinates /// </summary> /// <param name="input">String in Format X123 Y123</param> /// <param name="p">out Point Struct if possible</param> /// <returns>true if parsing succesful</returns> private static bool TryParseCoordinate(string input, out Point p) { throw new NotImplementedException(); } /// <summary> /// Merges two Dictionarys in generic way /// </summary> /// <typeparam name="T">any</typeparam> /// <typeparam name="T2">any</typeparam> /// <param name="dict1">Dictionary 1</param> /// <param name="dict2">Dictionary 2</param> /// <returns>Merged Dictionary</returns> static Dictionary<T, T2> MergeDictionarys<T, T2>(Dictionary<T, T2> dict1, Dictionary<T, T2> dict2) { var merged = new Dictionary<T, T2>(); foreach(var key in dict1.Keys) { merged.Add(key, dict1[key]); } foreach(var key in dict2.Keys) { if(!merged.ContainsKey(key)) merged.Add(key, dict2[key]); } return merged; } } }
//------------------------------------------------------------------------------ // <copyright file="SmtpMail.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* * Simple SMTP send mail utility * * Copyright (c) 2000, Microsoft Corporation */ namespace System.Web.Mail { using System; using System.Collections; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Serialization.Formatters; using System.Security.Permissions; using System.Text; using System.Web.Hosting; using System.Web.Management; using System.Web.Util; /* * Class that sends MailMessage using CDONTS/CDOSYS */ /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Obsolete("The recommended alternative is System.Net.Mail.SmtpClient. http://go.microsoft.com/fwlink/?linkid=14202")] public class SmtpMail { private static object _lockObject = new object(); private SmtpMail() { } #if !FEATURE_PAL // FEATURE_PAL does not enable SmtpMail // // Late bound helper // internal class LateBoundAccessHelper { private String _progId; private Type _type; internal LateBoundAccessHelper(String progId) { _progId = progId; } private Type LateBoundType { get { if (_type == null) { try { _type = Type.GetTypeFromProgID(_progId); } catch { } if (_type == null) throw new HttpException(SR.GetString(SR.SMTP_TypeCreationError, _progId)); } return _type; } } internal Object CreateInstance() { return Activator.CreateInstance(LateBoundType); } internal Object CallMethod(Object obj, String methodName, Object[] args) { try { return CallMethod(LateBoundType, obj, methodName, args); } catch (Exception e) { throw new HttpException(GetInnerMostException(e).Message, e); } } internal static Object CallMethodStatic(Object obj, String methodName, Object[] args) { return CallMethod(obj.GetType(), obj, methodName, args); } private static Object CallMethod(Type type, Object obj, String methodName, Object[] args) { return type.InvokeMember(methodName, BindingFlags.InvokeMethod, null, obj, args, CultureInfo.InvariantCulture); } private static Exception GetInnerMostException(Exception e) { if (e.InnerException == null) return e; else return GetInnerMostException(e.InnerException); } internal Object GetProp(Object obj, String propName) { try { return GetProp(LateBoundType, obj, propName); } catch (Exception e) { throw new HttpException(GetInnerMostException(e).Message, e); } } internal static Object GetPropStatic(Object obj, String propName) { return GetProp(obj.GetType(), obj, propName); } private static Object GetProp(Type type, Object obj, String propName) { return type.InvokeMember(propName, BindingFlags.GetProperty, null, obj,new Object[0], CultureInfo.InvariantCulture); } internal void SetProp(Object obj, String propName, Object propValue) { try { SetProp(LateBoundType, obj, propName, propValue); } catch (Exception e) { throw new HttpException(GetInnerMostException(e).Message, e); } } internal static void SetPropStatic(Object obj, String propName, Object propValue) { SetProp(obj.GetType(), obj, propName, propValue); } private static void SetProp(Type type, Object obj, String propName, Object propValue) { if (propValue != null && (propValue is string) && ((string)propValue).IndexOf('\0') >= 0) throw new ArgumentException(); type.InvokeMember(propName, BindingFlags.SetProperty, null, obj, new Object[1] { propValue }, CultureInfo.InvariantCulture); } internal void SetProp(Object obj, String propName, Object propKey, Object propValue) { try { SetProp(LateBoundType, obj, propName, propKey, propValue); } catch (Exception e) { throw new HttpException(GetInnerMostException(e).Message, e); } } internal static void SetPropStatic(Object obj, String propName, Object propKey, Object propValue) { SetProp(obj.GetType(), obj, propName, propKey, propValue); } private static void SetProp(Type type, Object obj, String propName, Object propKey, Object propValue) { if (propValue != null && (propValue is string) && ((string)propValue).IndexOf('\0') >= 0) throw new ArgumentException(); type.InvokeMember(propName, BindingFlags.SetProperty, null, obj,new Object[2] { propKey, propValue }, CultureInfo.InvariantCulture); } } // // Late bound access to CDONTS // internal class CdoNtsHelper { private static LateBoundAccessHelper _helper = new LateBoundAccessHelper("CDONTS.NewMail"); private CdoNtsHelper() { } internal static void Send(MailMessage message) { // create mail object Object newMail = _helper.CreateInstance(); // set properties if (message.From != null) _helper.SetProp(newMail, "From", message.From); if (message.To != null) _helper.SetProp(newMail, "To", message.To); if (message.Cc != null) _helper.SetProp(newMail, "Cc", message.Cc); if (message.Bcc != null) _helper.SetProp(newMail, "Bcc", message.Bcc); if (message.Subject != null) _helper.SetProp(newMail, "Subject", message.Subject); if (message.Priority != MailPriority.Normal) { int p = 0; switch (message.Priority) { case MailPriority.Low: p = 0; break; case MailPriority.Normal: p = 1; break; case MailPriority.High: p = 2; break; } _helper.SetProp(newMail, "Importance", p); } if (message.BodyEncoding != null) _helper.CallMethod(newMail, "SetLocaleIDs", new Object[1] { message.BodyEncoding.CodePage }); if (message.UrlContentBase != null) _helper.SetProp(newMail, "ContentBase", message.UrlContentBase); if (message.UrlContentLocation != null) _helper.SetProp(newMail, "ContentLocation", message.UrlContentLocation); int numHeaders = message.Headers.Count; if (numHeaders > 0) { IDictionaryEnumerator e = message.Headers.GetEnumerator(); while (e.MoveNext()) { String k = (String)e.Key; String v = (String)e.Value; _helper.SetProp(newMail, "Value", k, v); } } if (message.BodyFormat == MailFormat.Html) { _helper.SetProp(newMail, "BodyFormat", 0); _helper.SetProp(newMail, "MailFormat", 0); } // always set Body (VSWhidbey 176284) _helper.SetProp(newMail, "Body", (message.Body != null) ? message.Body : String.Empty); for (IEnumerator e = message.Attachments.GetEnumerator(); e.MoveNext(); ) { MailAttachment a = (MailAttachment)e.Current; int c = 0; switch (a.Encoding) { case MailEncoding.UUEncode: c = 0; break; case MailEncoding.Base64: c = 1; break; } _helper.CallMethod(newMail, "AttachFile", new Object[3] { a.Filename, null, (Object)c }); } // send mail _helper.CallMethod(newMail, "Send", new Object[5] { null, null, null, null, null }); // close unmanaged COM classic component Marshal.ReleaseComObject(newMail); } internal static void Send(String from, String to, String subject, String messageText) { MailMessage m = new MailMessage(); m.From = from; m.To = to; m.Subject = subject; m.Body = messageText; Send(m); } } // // Late bound access to CDOSYS // internal class CdoSysHelper { private static LateBoundAccessHelper _helper = new LateBoundAccessHelper("CDO.Message"); enum CdoSysLibraryStatus { NotChecked, Exists, DoesntExist } // Variable that shows if cdosys.dll exists private static CdoSysLibraryStatus cdoSysLibraryInfo = CdoSysLibraryStatus.NotChecked; private CdoSysHelper() { } private static void SetField(Object m, String name, String value) { _helper.SetProp(m, "Fields", "urn:schemas:mailheader:" + name, value); Object fields = _helper.GetProp(m, "Fields"); LateBoundAccessHelper.CallMethodStatic(fields, "Update", new Object[0]); Marshal.ReleaseComObject(fields); } private static bool CdoSysExists() { // Check that the cdosys.dll exists if(cdoSysLibraryInfo == CdoSysLibraryStatus.NotChecked) { string fullDllPath = PathUtil.GetSystemDllFullPath("cdosys.dll"); IntPtr cdoSysModule = UnsafeNativeMethods.LoadLibrary(fullDllPath); if(cdoSysModule != IntPtr.Zero) { UnsafeNativeMethods.FreeLibrary(cdoSysModule); cdoSysLibraryInfo = CdoSysLibraryStatus.Exists; return true; } cdoSysLibraryInfo = CdoSysLibraryStatus.DoesntExist; return false; } // return cached value, found at a previous check return (cdoSysLibraryInfo == CdoSysLibraryStatus.Exists); } internal static bool OsSupportsCdoSys() { Version osVersion = Environment.OSVersion.Version; if ((osVersion.Major >= 7 || (osVersion.Major == 6 && osVersion.Minor >= 1))) { // for some OS versions higher that 6, CdoSys.dll doesn't exist return CdoSysExists(); } return true; } internal static void Send(MailMessage message) { // create message object Object m = _helper.CreateInstance(); // set properties if (message.From != null) _helper.SetProp(m, "From", message.From); if (message.To != null) _helper.SetProp(m, "To", message.To); if (message.Cc != null) _helper.SetProp(m, "Cc", message.Cc); if (message.Bcc != null) _helper.SetProp(m, "Bcc", message.Bcc); if (message.Subject != null) _helper.SetProp(m, "Subject", message.Subject); if (message.Priority != MailPriority.Normal) { String importance = null; switch (message.Priority) { case MailPriority.Low: importance = "low"; break; case MailPriority.Normal: importance = "normal"; break; case MailPriority.High: importance = "high"; break; } if (importance != null) SetField(m, "importance", importance); } if (message.BodyEncoding != null) { Object body = _helper.GetProp(m, "BodyPart"); LateBoundAccessHelper.SetPropStatic(body, "Charset", message.BodyEncoding.BodyName); Marshal.ReleaseComObject(body); } if (message.UrlContentBase != null) SetField(m, "content-base", message.UrlContentBase); if (message.UrlContentLocation != null) SetField(m, "content-location", message.UrlContentLocation); int numHeaders = message.Headers.Count; if (numHeaders > 0) { IDictionaryEnumerator e = message.Headers.GetEnumerator(); while (e.MoveNext()) { SetField(m, (String)e.Key, (String)e.Value); } } if (message.Body != null) { if (message.BodyFormat == MailFormat.Html) { _helper.SetProp(m, "HtmlBody", message.Body); } else { _helper.SetProp(m, "TextBody", message.Body); } } else { _helper.SetProp(m, "TextBody", String.Empty); } for (IEnumerator e = message.Attachments.GetEnumerator(); e.MoveNext(); ) { MailAttachment a = (MailAttachment)e.Current; Object bodyPart = _helper.CallMethod(m, "AddAttachment", new Object[3] { a.Filename, null, null }); if (a.Encoding == MailEncoding.UUEncode) _helper.SetProp(m, "MimeFormatted", false); if (bodyPart != null) Marshal.ReleaseComObject(bodyPart); } // optional SMTP server string server = SmtpMail.SmtpServer; if (!String.IsNullOrEmpty(server) || message.Fields.Count > 0) { Object config = LateBoundAccessHelper.GetPropStatic(m, "Configuration"); if (config != null) { LateBoundAccessHelper.SetPropStatic(config, "Fields", "http://schemas.microsoft.com/cdo/configuration/sendusing", (Object)2); LateBoundAccessHelper.SetPropStatic(config, "Fields", "http://schemas.microsoft.com/cdo/configuration/smtpserverport", (Object)25); if (!String.IsNullOrEmpty(server)) { LateBoundAccessHelper.SetPropStatic(config, "Fields", "http://schemas.microsoft.com/cdo/configuration/smtpserver", server); } foreach (DictionaryEntry e in message.Fields) { LateBoundAccessHelper.SetPropStatic(config, "Fields", (String)e.Key, e.Value); } Object fields = LateBoundAccessHelper.GetPropStatic(config, "Fields"); LateBoundAccessHelper.CallMethodStatic(fields, "Update", new Object[0]); Marshal.ReleaseComObject(fields); Marshal.ReleaseComObject(config); } } if (HostingEnvironment.IsHosted) { // revert to process identity while sending mail using (new ProcessImpersonationContext()) { // send mail _helper.CallMethod(m, "Send", new Object[0]); } } else { // send mail _helper.CallMethod(m, "Send", new Object[0]); } // close unmanaged COM classic component Marshal.ReleaseComObject(m); } internal static void Send(String from, String to, String subject, String messageText) { MailMessage m = new MailMessage(); m.From = from; m.To = to; m.Subject = subject; m.Body = messageText; Send(m); } } #endif // !FEATURE_PAL private static String _server; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static String SmtpServer { get { String s = _server; return (s != null) ? s : String.Empty; } set { _server = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.Medium)] [SecurityPermission(SecurityAction.Assert, UnmanagedCode=true)] public static void Send(String from, String to, String subject, String messageText) { lock (_lockObject) { #if !FEATURE_PAL // FEATURE_PAL does not enable SmtpMail if (Environment.OSVersion.Platform != PlatformID.Win32NT) { throw new PlatformNotSupportedException(SR.GetString(SR.RequiresNT)); } else if (!CdoSysHelper.OsSupportsCdoSys()) { throw new PlatformNotSupportedException(SR.GetString(SR.SmtpMail_not_supported_on_Win7_and_higher)); } else if (Environment.OSVersion.Version.Major <= 4) { CdoNtsHelper.Send(from, to, subject, messageText); } else { CdoSysHelper.Send(from, to, subject, messageText); } #else // !FEATURE_PAL throw new NotImplementedException("ROTORTODO"); #endif // !FEATURE_PAL } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.Medium)] [SecurityPermission(SecurityAction.Assert, UnmanagedCode=true)] public static void Send(MailMessage message) { lock (_lockObject) { #if !FEATURE_PAL // FEATURE_PAL does not enable SmtpMail if (Environment.OSVersion.Platform != PlatformID.Win32NT) { throw new PlatformNotSupportedException(SR.GetString(SR.RequiresNT)); } else if (!CdoSysHelper.OsSupportsCdoSys()) { throw new PlatformNotSupportedException(SR.GetString(SR.SmtpMail_not_supported_on_Win7_and_higher)); } else if (Environment.OSVersion.Version.Major <= 4) { CdoNtsHelper.Send(message); } else { CdoSysHelper.Send(message); } #else // !FEATURE_PAL throw new NotImplementedException("ROTORTODO"); #endif // !FEATURE_PAL } } } // // Enums for message elements // /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Obsolete("The recommended alternative is System.Net.Mail.MailMessage.IsBodyHtml. http://go.microsoft.com/fwlink/?linkid=14202")] public enum MailFormat { /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> Text = 0, // note - different from CDONTS.NewMail /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> Html = 1 } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Obsolete("The recommended alternative is System.Net.Mail.MailPriority. http://go.microsoft.com/fwlink/?linkid=14202")] public enum MailPriority { /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> Normal = 0, // note - different from CDONTS.NewMail /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> Low = 1, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> High = 2 } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Obsolete("The recommended alternative is System.Net.Mime.TransferEncoding. http://go.microsoft.com/fwlink/?linkid=14202")] public enum MailEncoding { /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> UUEncode = 0, // note - same as CDONTS.NewMail /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> Base64 = 1 } /* * Immutable struct that holds a single attachment */ /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Obsolete("The recommended alternative is System.Net.Mail.Attachment. http://go.microsoft.com/fwlink/?linkid=14202")] public class MailAttachment { private String _filename; private MailEncoding _encoding; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public String Filename { get { return _filename; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public MailEncoding Encoding { get { return _encoding; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public MailAttachment(String filename) { _filename = filename; _encoding = MailEncoding.Base64; VerifyFile(); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public MailAttachment(String filename, MailEncoding encoding) { _filename = filename; _encoding = encoding; VerifyFile(); } private void VerifyFile() { try { File.Open(_filename, FileMode.Open, FileAccess.Read, FileShare.Read).Close(); } catch { throw new HttpException(SR.GetString(SR.Bad_attachment, _filename)); } } } /* * Struct that holds a single message */ /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Obsolete("The recommended alternative is System.Net.Mail.MailMessage. http://go.microsoft.com/fwlink/?linkid=14202")] public class MailMessage { Hashtable _headers = new Hashtable(); Hashtable _fields = new Hashtable(); ArrayList _attachments = new ArrayList(); string from; string to; string cc; string bcc; string subject; MailPriority priority = MailPriority.Normal; string urlContentBase; string urlContentLocation; string body; MailFormat bodyFormat = MailFormat.Text; Encoding bodyEncoding = Encoding.Default; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string From { get { return from; } set { from = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string To { get { return to; } set { to = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string Cc { get { return cc; } set { cc = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string Bcc { get { return bcc; } set { bcc = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string Subject { get { return subject; } set { subject = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public MailPriority Priority { get { return priority; } set { priority = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string UrlContentBase { get { return urlContentBase; } set { urlContentBase = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string UrlContentLocation { get { return urlContentLocation; } set { urlContentLocation = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string Body { get { return body; } set { body = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public MailFormat BodyFormat { get { return bodyFormat; } set { bodyFormat = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public Encoding BodyEncoding { get { return bodyEncoding; } set { bodyEncoding = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public IDictionary Headers { get { return _headers; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public IDictionary Fields { get { return _fields; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public IList Attachments { get { return _attachments; } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="AbstractConnectionFactory.cs" company="The original author or authors."> // Copyright 2002-2012 the original author or 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. // </copyright> // -------------------------------------------------------------------------------------------------------------------- #region Using Directives using System; using System.Collections.Generic; using System.Net; using Common.Logging; using RabbitMQ.Client; using Spring.Util; #endregion namespace Spring.Messaging.Amqp.Rabbit.Connection { /// <summary> /// A <see cref="IConnectionFactory"/> implementation that returns the same Connection from all /// <see cref="IConnectionFactory.CreateConnection"/> calls, and ignores call to /// <see cref="IConnection.Close()"/> /// </summary> /// <author>Mark Pollack</author> public abstract class AbstractConnectionFactory : IConnectionFactory, IDisposable { #region Logging Definition /// <summary> /// The Logger. /// </summary> protected static readonly ILog Logger = LogManager.GetCurrentClassLogger(); #endregion /// <summary> /// The connection factory. /// </summary> private readonly ConnectionFactory rabbitConnectionFactory; /// <summary> /// The connection listener. /// </summary> private readonly CompositeConnectionListener connectionListener = new CompositeConnectionListener(); /// <summary> /// The channel listener. /// </summary> private readonly CompositeChannelListener channelListener = new CompositeChannelListener(); // private volatile IExecutorService executorService; private volatile AmqpTcpEndpoint[] addresses; /// <summary>Initializes a new instance of the <see cref="AbstractConnectionFactory"/> class.</summary> /// <param name="rabbitConnectionFactory">The rabbit connection factory.</param> public AbstractConnectionFactory(ConnectionFactory rabbitConnectionFactory) { AssertUtils.ArgumentNotNull(rabbitConnectionFactory, "Target ConnectionFactory must not be null"); this.rabbitConnectionFactory = rabbitConnectionFactory; } #region Implementation of IConnectionFactory /// <summary> /// Sets UserName. /// </summary> public string UserName { set { this.rabbitConnectionFactory.UserName = value; } } /// <summary> /// Sets Password. /// </summary> public string Password { set { this.rabbitConnectionFactory.Password = value; } } /// <summary> /// Gets or sets Host. /// </summary> public string Host { get { return this.rabbitConnectionFactory.HostName; } set { this.rabbitConnectionFactory.HostName = value; } } /// <summary> /// Gets or sets VirtualHost. /// </summary> public string VirtualHost { get { return this.rabbitConnectionFactory.VirtualHost; } set { this.rabbitConnectionFactory.VirtualHost = value; } } /// <summary> /// Gets or sets Port. /// </summary> public int Port { get { return this.rabbitConnectionFactory.Port; } set { this.rabbitConnectionFactory.Port = value; } } /// <summary>Gets the amqp tcp endpoints.</summary> public AmqpTcpEndpoint[] AmqpTcpEndpoints { get { return this.addresses; } } /// <summary>Sets the addresses.</summary> public string Addresses { set { var addressArray = AmqpTcpEndpoint.ParseMultiple(Protocols.DefaultProtocol, value); if (addressArray != null && addressArray.Length > 0) { this.addresses = addressArray; } } } /// <summary> /// Gets the channel listener. /// </summary> public virtual IChannelListener ChannelListener { get { return this.channelListener; } } /// <summary> /// Gets the connection listener. /// </summary> public virtual IConnectionListener ConnectionListener { get { return this.connectionListener; } } /// <summary> /// Sets the connection listeners. /// </summary> /// <value> /// The connection listeners. /// </value> public virtual IList<IConnectionListener> ConnectionListeners { set { this.connectionListener.Delegates = value; } } /// <summary> /// Sets the channel listeners. /// </summary> /// <value> /// The channel listeners. /// </value> public virtual IList<IChannelListener> ChannelListeners { set { this.channelListener.Delegates = value; } } /// <summary>Add a connection listener.</summary> /// <param name="connectionListener">The listener.</param> public virtual void AddConnectionListener(IConnectionListener connectionListener) { this.connectionListener.AddDelegate(connectionListener); } /// <summary>Add a connection listener.</summary> /// <param name="channelListener">The listener.</param> public virtual void AddChannelListener(IChannelListener channelListener) { this.channelListener.AddDelegate(channelListener); } /* public void IExecutor Executor { set { // Provide an Executor for // use by the Rabbit ConnectionFactory when creating connections. // Can either be an ExecutorService or a Spring // ThreadPoolTaskExecutor, as defined by a &lt;task:executor/&gt; element. // @param executor The executor. var isExecutorService = value is ExecutorService; var isThreadPoolTaskExecutor = value is ThreadPoolTaskExecutor; AssertUtils.IsTrue(isExecutorService || isThreadPoolTaskExecutor); if (isExecutorService) { this.executorService = (ExecutorService)executor; } else { this.executorService = ((ThreadPoolTaskExecutor)executor).getThreadPoolExecutor(); } } } */ /// <summary> /// Create a connection. /// </summary> /// <returns>The connection.</returns> public abstract IConnection CreateConnection(); /// <summary> /// Create a connection. /// </summary> /// <returns>The connection.</returns> public virtual IConnection CreateBareConnection() { try { if (this.addresses != null) { // TODO: Waiting on RabbitMQ.Client to catch up to the Java equivalent here. // return new SimpleConnection(this.rabbitConnectionFactory.CreateConnection(this.executorService, this.addresses)); return new SimpleConnection(this.rabbitConnectionFactory.CreateConnection()); } else { // TODO: Waiting on RabbitMQ.Client to catch up to the Java equivalent here. // return new SimpleConnection(this.rabbitConnectionFactory.CreateConnection(this.executorService)); return new SimpleConnection(this.rabbitConnectionFactory.CreateConnection()); } } catch (Exception ex) { throw RabbitUtils.ConvertRabbitAccessException(ex); } } /// <summary> /// Get the default host name. /// </summary> /// <returns>The host name.</returns> protected string GetDefaultHostName() { string temp; try { temp = Dns.GetHostName().ToUpper(); Logger.Debug("Using hostname [" + temp + "] for hostname."); } catch (Exception e) { Logger.Warn("Could not get host name, using 'localhost' as default value", e); temp = "localhost"; } return temp; } #endregion #region Implementation of IDisposable /// <summary> /// Close the underlying shared connection. /// </summary> public virtual void Dispose() { } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using Nop.Core.Domain.Common; using Nop.Core.Domain.Customers; using Nop.Core.Domain.Discounts; using Nop.Core.Domain.Payments; using Nop.Core.Domain.Shipping; using Nop.Core.Domain.Tax; namespace Nop.Core.Domain.Orders { /// <summary> /// Represents an order /// </summary> public partial class Order : BaseEntity { private ICollection<DiscountUsageHistory> _discountUsageHistory; private ICollection<GiftCardUsageHistory> _giftCardUsageHistory; private ICollection<OrderNote> _orderNotes; private ICollection<OrderItem> _orderItems; private ICollection<Shipment> _shipments; #region Utilities protected virtual SortedDictionary<decimal, decimal> ParseTaxRates(string taxRatesStr) { var taxRatesDictionary = new SortedDictionary<decimal, decimal>(); if (String.IsNullOrEmpty(taxRatesStr)) return taxRatesDictionary; string[] lines = taxRatesStr.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string line in lines) { if (String.IsNullOrEmpty(line.Trim())) continue; string[] taxes = line.Split(new [] { ':' }); if (taxes.Length == 2) { try { decimal taxRate = decimal.Parse(taxes[0].Trim(), CultureInfo.InvariantCulture); decimal taxValue = decimal.Parse(taxes[1].Trim(), CultureInfo.InvariantCulture); taxRatesDictionary.Add(taxRate, taxValue); } catch (Exception exc) { Debug.WriteLine(exc.ToString()); } } } //add at least one tax rate (0%) if (taxRatesDictionary.Count == 0) taxRatesDictionary.Add(decimal.Zero, decimal.Zero); return taxRatesDictionary; } #endregion #region Properties /// <summary> /// Gets or sets the order identifier /// </summary> public Guid OrderGuid { get; set; } /// <summary> /// Gets or sets the store identifier /// </summary> public int StoreId { get; set; } /// <summary> /// Gets or sets the customer identifier /// </summary> public int CustomerId { get; set; } /// <summary> /// Gets or sets the billing address identifier /// </summary> public int BillingAddressId { get; set; } /// <summary> /// Gets or sets the shipping address identifier /// </summary> public int? ShippingAddressId { get; set; } /// <summary> /// Gets or sets a value indicating whether a customer chose "pick up in store" shipping option /// </summary> public bool PickUpInStore { get; set; } /// <summary> /// Gets or sets an order status identifier /// </summary> public int OrderStatusId { get; set; } /// <summary> /// Gets or sets the shipping status identifier /// </summary> public int ShippingStatusId { get; set; } /// <summary> /// Gets or sets the payment status identifier /// </summary> public int PaymentStatusId { get; set; } /// <summary> /// Gets or sets the payment method system name /// </summary> public string PaymentMethodSystemName { get; set; } /// <summary> /// Gets or sets the customer currency code (at the moment of order placing) /// </summary> public string CustomerCurrencyCode { get; set; } /// <summary> /// Gets or sets the currency rate /// </summary> public decimal CurrencyRate { get; set; } /// <summary> /// Gets or sets the customer tax display type identifier /// </summary> public int CustomerTaxDisplayTypeId { get; set; } /// <summary> /// Gets or sets the VAT number (the European Union Value Added Tax) /// </summary> public string VatNumber { get; set; } /// <summary> /// Gets or sets the order subtotal (incl tax) /// </summary> public decimal OrderSubtotalInclTax { get; set; } /// <summary> /// Gets or sets the order subtotal (excl tax) /// </summary> public decimal OrderSubtotalExclTax { get; set; } /// <summary> /// Gets or sets the order subtotal discount (incl tax) /// </summary> public decimal OrderSubTotalDiscountInclTax { get; set; } /// <summary> /// Gets or sets the order subtotal discount (excl tax) /// </summary> public decimal OrderSubTotalDiscountExclTax { get; set; } /// <summary> /// Gets or sets the order shipping (incl tax) /// </summary> public decimal OrderShippingInclTax { get; set; } /// <summary> /// Gets or sets the order shipping (excl tax) /// </summary> public decimal OrderShippingExclTax { get; set; } /// <summary> /// Gets or sets the payment method additional fee (incl tax) /// </summary> public decimal PaymentMethodAdditionalFeeInclTax { get; set; } /// <summary> /// Gets or sets the payment method additional fee (excl tax) /// </summary> public decimal PaymentMethodAdditionalFeeExclTax { get; set; } /// <summary> /// Gets or sets the tax rates /// </summary> public string TaxRates { get; set; } /// <summary> /// Gets or sets the order tax /// </summary> public decimal OrderTax { get; set; } /// <summary> /// Gets or sets the order discount (applied to order total) /// </summary> public decimal OrderDiscount { get; set; } /// <summary> /// Gets or sets the order total /// </summary> public decimal OrderTotal { get; set; } /// <summary> /// Gets or sets the refunded amount /// </summary> public decimal RefundedAmount { get; set; } /// <summary> /// Gets or sets the value indicating whether reward points were earned (gained) for placing this order /// </summary> public bool RewardPointsWereAdded { get; set; } /// <summary> /// Gets or sets the checkout attribute description /// </summary> public string CheckoutAttributeDescription { get; set; } /// <summary> /// Gets or sets the checkout attributes in XML format /// </summary> public string CheckoutAttributesXml { get; set; } /// <summary> /// Gets or sets the customer language identifier /// </summary> public int CustomerLanguageId { get; set; } /// <summary> /// Gets or sets the affiliate identifier /// </summary> public int AffiliateId { get; set; } /// <summary> /// Gets or sets the customer IP address /// </summary> public string CustomerIp { get; set; } /// <summary> /// Gets or sets a value indicating whether storing of credit card number is allowed /// </summary> public bool AllowStoringCreditCardNumber { get; set; } /// <summary> /// Gets or sets the card type /// </summary> public string CardType { get; set; } /// <summary> /// Gets or sets the card name /// </summary> public string CardName { get; set; } /// <summary> /// Gets or sets the card number /// </summary> public string CardNumber { get; set; } /// <summary> /// Gets or sets the masked credit card number /// </summary> public string MaskedCreditCardNumber { get; set; } /// <summary> /// Gets or sets the card CVV2 /// </summary> public string CardCvv2 { get; set; } /// <summary> /// Gets or sets the card expiration month /// </summary> public string CardExpirationMonth { get; set; } /// <summary> /// Gets or sets the card expiration year /// </summary> public string CardExpirationYear { get; set; } /// <summary> /// Gets or sets the authorization transaction identifier /// </summary> public string AuthorizationTransactionId { get; set; } /// <summary> /// Gets or sets the authorization transaction code /// </summary> public string AuthorizationTransactionCode { get; set; } /// <summary> /// Gets or sets the authorization transaction result /// </summary> public string AuthorizationTransactionResult { get; set; } /// <summary> /// Gets or sets the capture transaction identifier /// </summary> public string CaptureTransactionId { get; set; } /// <summary> /// Gets or sets the capture transaction result /// </summary> public string CaptureTransactionResult { get; set; } /// <summary> /// Gets or sets the subscription transaction identifier /// </summary> public string SubscriptionTransactionId { get; set; } /// <summary> /// Gets or sets the paid date and time /// </summary> public DateTime? PaidDateUtc { get; set; } /// <summary> /// Gets or sets the shipping method /// </summary> public string ShippingMethod { get; set; } /// <summary> /// Gets or sets the shipping rate computation method identifier /// </summary> public string ShippingRateComputationMethodSystemName { get; set; } /// <summary> /// Gets or sets the serialized CustomValues (values from ProcessPaymentRequest) /// </summary> public string CustomValuesXml { get; set; } /// <summary> /// Gets or sets a value indicating whether the entity has been deleted /// </summary> public bool Deleted { get; set; } /// <summary> /// Gets or sets the date and time of order creation /// </summary> public DateTime CreatedOnUtc { get; set; } #endregion #region Navigation properties /// <summary> /// Gets or sets the customer /// </summary> public virtual Customer Customer { get; set; } /// <summary> /// Gets or sets the billing address /// </summary> public virtual Address BillingAddress { get; set; } /// <summary> /// Gets or sets the shipping address /// </summary> public virtual Address ShippingAddress { get; set; } /// <summary> /// Gets or sets the reward points history record (spent by a customer when placing this order) /// </summary> public virtual RewardPointsHistory RedeemedRewardPointsEntry { get; set; } /// <summary> /// Gets or sets discount usage history /// </summary> public virtual ICollection<DiscountUsageHistory> DiscountUsageHistory { get { return _discountUsageHistory ?? (_discountUsageHistory = new List<DiscountUsageHistory>()); } protected set { _discountUsageHistory = value; } } /// <summary> /// Gets or sets gift card usage history (gift card that were used with this order) /// </summary> public virtual ICollection<GiftCardUsageHistory> GiftCardUsageHistory { get { return _giftCardUsageHistory ?? (_giftCardUsageHistory = new List<GiftCardUsageHistory>()); } protected set { _giftCardUsageHistory = value; } } /// <summary> /// Gets or sets order notes /// </summary> public virtual ICollection<OrderNote> OrderNotes { get { return _orderNotes ?? (_orderNotes = new List<OrderNote>()); } protected set { _orderNotes = value; } } /// <summary> /// Gets or sets order items /// </summary> public virtual ICollection<OrderItem> OrderItems { get { return _orderItems ?? (_orderItems = new List<OrderItem>()); } protected set { _orderItems = value; } } /// <summary> /// Gets or sets shipments /// </summary> public virtual ICollection<Shipment> Shipments { get { return _shipments ?? (_shipments = new List<Shipment>()); } protected set { _shipments = value; } } #endregion #region Custom properties /// <summary> /// Gets or sets the order status /// </summary> public OrderStatus OrderStatus { get { return (OrderStatus)this.OrderStatusId; } set { this.OrderStatusId = (int)value; } } /// <summary> /// Gets or sets the payment status /// </summary> public PaymentStatus PaymentStatus { get { return (PaymentStatus)this.PaymentStatusId; } set { this.PaymentStatusId = (int)value; } } /// <summary> /// Gets or sets the shipping status /// </summary> public ShippingStatus ShippingStatus { get { return (ShippingStatus)this.ShippingStatusId; } set { this.ShippingStatusId = (int)value; } } /// <summary> /// Gets or sets the customer tax display type /// </summary> public TaxDisplayType CustomerTaxDisplayType { get { return (TaxDisplayType)this.CustomerTaxDisplayTypeId; } set { this.CustomerTaxDisplayTypeId = (int)value; } } /// <summary> /// Gets the applied tax rates /// </summary> public SortedDictionary<decimal, decimal> TaxRatesDictionary { get { return ParseTaxRates(this.TaxRates); } } #endregion } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.Runtime.Serialization { using System; using System.Diagnostics.CodeAnalysis; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Reflection; using System.Globalization; using System.Collections.Generic; #if USE_REFEMIT public class XmlReaderDelegator #else internal class XmlReaderDelegator #endif { protected XmlReader reader; protected XmlDictionaryReader dictionaryReader; protected bool isEndOfEmptyElement = false; public XmlReaderDelegator(XmlReader reader) { XmlObjectSerializer.CheckNull(reader, "reader"); this.reader = reader; this.dictionaryReader = reader as XmlDictionaryReader; } internal XmlReader UnderlyingReader { get { return reader; } } internal ExtensionDataReader UnderlyingExtensionDataReader { get { return reader as ExtensionDataReader; } } internal int AttributeCount { get { return isEndOfEmptyElement ? 0 : reader.AttributeCount; } } internal string GetAttribute(string name) { return isEndOfEmptyElement ? null : reader.GetAttribute(name); } internal string GetAttribute(string name, string namespaceUri) { return isEndOfEmptyElement ? null : reader.GetAttribute(name, namespaceUri); } internal string GetAttribute(int i) { if (isEndOfEmptyElement) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("i", SR.GetString(SR.XmlElementAttributes))); return reader.GetAttribute(i); } internal bool IsEmptyElement { get { return false; } } internal bool IsNamespaceURI(string ns) { if (dictionaryReader == null) return ns == reader.NamespaceURI; else return dictionaryReader.IsNamespaceUri(ns); } internal bool IsLocalName(string localName) { if (dictionaryReader == null) return localName == reader.LocalName; else return dictionaryReader.IsLocalName(localName); } internal bool IsNamespaceUri(XmlDictionaryString ns) { if (dictionaryReader == null) return ns.Value == reader.NamespaceURI; else return dictionaryReader.IsNamespaceUri(ns); } internal bool IsLocalName(XmlDictionaryString localName) { if (dictionaryReader == null) return localName.Value == reader.LocalName; else return dictionaryReader.IsLocalName(localName); } internal int IndexOfLocalName(XmlDictionaryString[] localNames, XmlDictionaryString ns) { if (dictionaryReader != null) return dictionaryReader.IndexOfLocalName(localNames, ns); if (reader.NamespaceURI == ns.Value) { string localName = this.LocalName; for (int i = 0; i < localNames.Length; i++) { if (localName == localNames[i].Value) { return i; } } } return -1; } public bool IsStartElement() { return !isEndOfEmptyElement && reader.IsStartElement(); } internal bool IsStartElement(string localname, string ns) { return !isEndOfEmptyElement && reader.IsStartElement(localname, ns); } public bool IsStartElement(XmlDictionaryString localname, XmlDictionaryString ns) { if (dictionaryReader == null) return !isEndOfEmptyElement && reader.IsStartElement(localname.Value, ns.Value); else return !isEndOfEmptyElement && dictionaryReader.IsStartElement(localname, ns); } internal bool MoveToAttribute(string name) { return isEndOfEmptyElement ? false : reader.MoveToAttribute(name); } internal bool MoveToAttribute(string name, string ns) { return isEndOfEmptyElement ? false : reader.MoveToAttribute(name, ns); } internal void MoveToAttribute(int i) { if (isEndOfEmptyElement) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("i", SR.GetString(SR.XmlElementAttributes))); reader.MoveToAttribute(i); } internal bool MoveToElement() { return isEndOfEmptyElement ? false : reader.MoveToElement(); } internal bool MoveToFirstAttribute() { return isEndOfEmptyElement ? false : reader.MoveToFirstAttribute(); } internal bool MoveToNextAttribute() { return isEndOfEmptyElement ? false : reader.MoveToNextAttribute(); } public XmlNodeType NodeType { get { return isEndOfEmptyElement ? XmlNodeType.EndElement : reader.NodeType; } } internal bool Read() { //reader.MoveToFirstAttribute(); //if (NodeType == XmlNodeType.Attribute) reader.MoveToElement(); if (!reader.IsEmptyElement) return reader.Read(); if (isEndOfEmptyElement) { isEndOfEmptyElement = false; return reader.Read(); } isEndOfEmptyElement = true; return true; } #if USE_REFEMIT public XmlNodeType MoveToContent() #else internal XmlNodeType MoveToContent() #endif { if (isEndOfEmptyElement) return XmlNodeType.EndElement; return reader.MoveToContent(); } internal bool ReadAttributeValue() { return isEndOfEmptyElement ? false : reader.ReadAttributeValue(); } public void ReadEndElement() { if (isEndOfEmptyElement) Read(); else reader.ReadEndElement(); } Exception CreateInvalidPrimitiveTypeException(Type type) { return new InvalidDataContractException(SR.GetString( type.IsInterface ? SR.InterfaceTypeCannotBeCreated : SR.InvalidPrimitiveType, DataContract.GetClrTypeFullName(type))); } public object ReadElementContentAsAnyType(Type valueType) { Read(); object o = ReadContentAsAnyType(valueType); ReadEndElement(); return o; } internal object ReadContentAsAnyType(Type valueType) { switch (Type.GetTypeCode(valueType)) { case TypeCode.Boolean: return ReadContentAsBoolean(); case TypeCode.Char: return ReadContentAsChar(); case TypeCode.Byte: return ReadContentAsUnsignedByte(); case TypeCode.Int16: return ReadContentAsShort(); case TypeCode.Int32: return ReadContentAsInt(); case TypeCode.Int64: return ReadContentAsLong(); case TypeCode.Single: return ReadContentAsSingle(); case TypeCode.Double: return ReadContentAsDouble(); case TypeCode.Decimal: return ReadContentAsDecimal(); case TypeCode.DateTime: return ReadContentAsDateTime(); case TypeCode.String: return ReadContentAsString(); case TypeCode.SByte: return ReadContentAsSignedByte(); case TypeCode.UInt16: return ReadContentAsUnsignedShort(); case TypeCode.UInt32: return ReadContentAsUnsignedInt(); case TypeCode.UInt64: return ReadContentAsUnsignedLong(); case TypeCode.Empty: case TypeCode.DBNull: case TypeCode.Object: default: if (valueType == Globals.TypeOfByteArray) return ReadContentAsBase64(); else if (valueType == Globals.TypeOfObject) return new object(); else if (valueType == Globals.TypeOfTimeSpan) return ReadContentAsTimeSpan(); else if (valueType == Globals.TypeOfGuid) return ReadContentAsGuid(); else if (valueType == Globals.TypeOfUri) return ReadContentAsUri(); else if (valueType == Globals.TypeOfXmlQualifiedName) return ReadContentAsQName(); break; } throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidPrimitiveTypeException(valueType)); } internal IDataNode ReadExtensionData(Type valueType) { switch (Type.GetTypeCode(valueType)) { case TypeCode.Boolean: return new DataNode<bool>(ReadContentAsBoolean()); case TypeCode.Char: return new DataNode<char>(ReadContentAsChar()); case TypeCode.Byte: return new DataNode<byte>(ReadContentAsUnsignedByte()); case TypeCode.Int16: return new DataNode<short>(ReadContentAsShort()); case TypeCode.Int32: return new DataNode<int>(ReadContentAsInt()); case TypeCode.Int64: return new DataNode<long>(ReadContentAsLong()); case TypeCode.Single: return new DataNode<float>(ReadContentAsSingle()); case TypeCode.Double: return new DataNode<double>(ReadContentAsDouble()); case TypeCode.Decimal: return new DataNode<decimal>(ReadContentAsDecimal()); case TypeCode.DateTime: return new DataNode<DateTime>(ReadContentAsDateTime()); case TypeCode.String: return new DataNode<string>(ReadContentAsString()); case TypeCode.SByte: return new DataNode<sbyte>(ReadContentAsSignedByte()); case TypeCode.UInt16: return new DataNode<ushort>(ReadContentAsUnsignedShort()); case TypeCode.UInt32: return new DataNode<uint>(ReadContentAsUnsignedInt()); case TypeCode.UInt64: return new DataNode<ulong>(ReadContentAsUnsignedLong()); case TypeCode.Empty: case TypeCode.DBNull: case TypeCode.Object: default: if (valueType == Globals.TypeOfByteArray) return new DataNode<byte[]>(ReadContentAsBase64()); else if (valueType == Globals.TypeOfObject) return new DataNode<object>(new object()); else if (valueType == Globals.TypeOfTimeSpan) return new DataNode<TimeSpan>(ReadContentAsTimeSpan()); else if (valueType == Globals.TypeOfGuid) return new DataNode<Guid>(ReadContentAsGuid()); else if (valueType == Globals.TypeOfUri) return new DataNode<Uri>(ReadContentAsUri()); else if (valueType == Globals.TypeOfXmlQualifiedName) return new DataNode<XmlQualifiedName>(ReadContentAsQName()); break; } throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidPrimitiveTypeException(valueType)); } void ThrowConversionException(string value, string type) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(XmlObjectSerializer.TryAddLineInfo(this, SR.GetString(SR.XmlInvalidConversion, value, type)))); } void ThrowNotAtElement() { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlStartElementExpected, "EndElement"))); } #if USE_REFEMIT public virtual char ReadElementContentAsChar() #else internal virtual char ReadElementContentAsChar() #endif { return ToChar(ReadElementContentAsInt()); } internal virtual char ReadContentAsChar() { return ToChar(ReadContentAsInt()); } char ToChar(int value) { if (value < char.MinValue || value > char.MaxValue) { ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "Char"); } return (char)value; } public string ReadElementContentAsString() { if (isEndOfEmptyElement) ThrowNotAtElement(); return reader.ReadElementContentAsString(); } internal string ReadContentAsString() { return isEndOfEmptyElement ? String.Empty : reader.ReadContentAsString(); } public bool ReadElementContentAsBoolean() { if (isEndOfEmptyElement) ThrowNotAtElement(); return reader.ReadElementContentAsBoolean(); } internal bool ReadContentAsBoolean() { if (isEndOfEmptyElement) ThrowConversionException(string.Empty, "Boolean"); return reader.ReadContentAsBoolean(); } public float ReadElementContentAsFloat() { if (isEndOfEmptyElement) ThrowNotAtElement(); return reader.ReadElementContentAsFloat(); } internal float ReadContentAsSingle() { if (isEndOfEmptyElement) ThrowConversionException(string.Empty, "Float"); return reader.ReadContentAsFloat(); } public double ReadElementContentAsDouble() { if (isEndOfEmptyElement) ThrowNotAtElement(); return reader.ReadElementContentAsDouble(); } internal double ReadContentAsDouble() { if (isEndOfEmptyElement) ThrowConversionException(string.Empty, "Double"); return reader.ReadContentAsDouble(); } public decimal ReadElementContentAsDecimal() { if (isEndOfEmptyElement) ThrowNotAtElement(); return reader.ReadElementContentAsDecimal(); } internal decimal ReadContentAsDecimal() { if (isEndOfEmptyElement) ThrowConversionException(string.Empty, "Decimal"); return reader.ReadContentAsDecimal(); } #if USE_REFEMIT public virtual byte[] ReadElementContentAsBase64() #else internal virtual byte[] ReadElementContentAsBase64() #endif { if (isEndOfEmptyElement) ThrowNotAtElement(); if (dictionaryReader == null) { return ReadContentAsBase64(reader.ReadElementContentAsString()); } else { return dictionaryReader.ReadElementContentAsBase64(); } } #if USE_REFEMIT public virtual byte[] ReadContentAsBase64() #else internal virtual byte[] ReadContentAsBase64() #endif { if (isEndOfEmptyElement) return new byte[0]; if (dictionaryReader == null) { return ReadContentAsBase64(reader.ReadContentAsString()); } else { return dictionaryReader.ReadContentAsBase64(); } } internal byte[] ReadContentAsBase64(string str) { if (str == null) return null; str = str.Trim(); if (str.Length == 0) return new byte[0]; try { return Convert.FromBase64String(str); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "byte[]", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "byte[]", exception)); } } #if USE_REFEMIT public virtual DateTime ReadElementContentAsDateTime() #else internal virtual DateTime ReadElementContentAsDateTime() #endif { if (isEndOfEmptyElement) ThrowNotAtElement(); return reader.ReadElementContentAsDateTime(); } internal virtual DateTime ReadContentAsDateTime() { if (isEndOfEmptyElement) ThrowConversionException(string.Empty, "DateTime"); return reader.ReadContentAsDateTime(); } public int ReadElementContentAsInt() { if (isEndOfEmptyElement) ThrowNotAtElement(); return reader.ReadElementContentAsInt(); } internal int ReadContentAsInt() { if (isEndOfEmptyElement) ThrowConversionException(string.Empty, "Int32"); return reader.ReadContentAsInt(); } public long ReadElementContentAsLong() { if (isEndOfEmptyElement) ThrowNotAtElement(); return reader.ReadElementContentAsLong(); } internal long ReadContentAsLong() { if (isEndOfEmptyElement) ThrowConversionException(string.Empty, "Int64"); return reader.ReadContentAsLong(); } public short ReadElementContentAsShort() { return ToShort(ReadElementContentAsInt()); } internal short ReadContentAsShort() { return ToShort(ReadContentAsInt()); } short ToShort(int value) { if (value < short.MinValue || value > short.MaxValue) { ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "Int16"); } return (short)value; } public byte ReadElementContentAsUnsignedByte() { return ToByte(ReadElementContentAsInt()); } internal byte ReadContentAsUnsignedByte() { return ToByte(ReadContentAsInt()); } byte ToByte(int value) { if (value < byte.MinValue || value > byte.MaxValue) { ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "Byte"); } return (byte)value; } #if USE_REFEMIT [CLSCompliant(false)] #endif public SByte ReadElementContentAsSignedByte() { return ToSByte(ReadElementContentAsInt()); } internal SByte ReadContentAsSignedByte() { return ToSByte(ReadContentAsInt()); } SByte ToSByte(int value) { if (value < SByte.MinValue || value > SByte.MaxValue) { ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "SByte"); } return (SByte)value; } #if USE_REFEMIT [CLSCompliant(false)] #endif public UInt32 ReadElementContentAsUnsignedInt() { return ToUInt32(ReadElementContentAsLong()); } internal UInt32 ReadContentAsUnsignedInt() { return ToUInt32(ReadContentAsLong()); } UInt32 ToUInt32(long value) { if (value < UInt32.MinValue || value > UInt32.MaxValue) { ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "UInt32"); } return (UInt32)value; } #if USE_REFEMIT [CLSCompliant(false)] public virtual UInt64 ReadElementContentAsUnsignedLong() #else internal virtual UInt64 ReadElementContentAsUnsignedLong() #endif { if (isEndOfEmptyElement) ThrowNotAtElement(); string str = reader.ReadElementContentAsString(); if (str == null || str.Length == 0) ThrowConversionException(string.Empty, "UInt64"); return XmlConverter.ToUInt64(str); } internal virtual UInt64 ReadContentAsUnsignedLong() { string str = reader.ReadContentAsString(); if (str == null || str.Length == 0) ThrowConversionException(string.Empty, "UInt64"); return XmlConverter.ToUInt64(str); } #if USE_REFEMIT [CLSCompliant(false)] #endif public UInt16 ReadElementContentAsUnsignedShort() { return ToUInt16(ReadElementContentAsInt()); } internal UInt16 ReadContentAsUnsignedShort() { return ToUInt16(ReadContentAsInt()); } UInt16 ToUInt16(int value) { if (value < UInt16.MinValue || value > UInt16.MaxValue) { ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "UInt16"); } return (UInt16)value; } public TimeSpan ReadElementContentAsTimeSpan() { if (isEndOfEmptyElement) ThrowNotAtElement(); string str = reader.ReadElementContentAsString(); return XmlConverter.ToTimeSpan(str); } internal TimeSpan ReadContentAsTimeSpan() { string str = reader.ReadContentAsString(); return XmlConverter.ToTimeSpan(str); } [SuppressMessage("Reliability", "Reliability113", Justification = "Catching expected exceptions inline instead of calling Fx.CreateGuid to minimize code change")] public Guid ReadElementContentAsGuid() { if (isEndOfEmptyElement) ThrowNotAtElement(); string str = reader.ReadElementContentAsString(); try { return Guid.Parse(str); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Guid", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Guid", exception)); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Guid", exception)); } } [SuppressMessage("Reliability", "Reliability113", Justification = "Catching expected exceptions inline instead of calling Fx.CreateGuid to minimize code change")] internal Guid ReadContentAsGuid() { string str = reader.ReadContentAsString(); try { return Guid.Parse(str); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Guid", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Guid", exception)); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Guid", exception)); } } public Uri ReadElementContentAsUri() { if (isEndOfEmptyElement) ThrowNotAtElement(); string str = ReadElementContentAsString(); try { return new Uri(str, UriKind.RelativeOrAbsolute); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Uri", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Uri", exception)); } } internal Uri ReadContentAsUri() { string str = ReadContentAsString(); try { return new Uri(str, UriKind.RelativeOrAbsolute); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Uri", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Uri", exception)); } } public XmlQualifiedName ReadElementContentAsQName() { Read(); XmlQualifiedName obj = ReadContentAsQName(); ReadEndElement(); return obj; } internal virtual XmlQualifiedName ReadContentAsQName() { return ParseQualifiedName(ReadContentAsString()); } XmlQualifiedName ParseQualifiedName(string str) { string name, ns, prefix; if (str == null || str.Length == 0) name = ns = String.Empty; else XmlObjectSerializerReadContext.ParseQualifiedName(str, this, out name, out ns, out prefix); return new XmlQualifiedName(name, ns); } void CheckExpectedArrayLength(XmlObjectSerializerReadContext context, int arrayLength) { #if NO int readerArrayLength; if (dictionaryReader.TryGetArrayLength(out readerArrayLength)) { if (readerArrayLength != arrayLength) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ArraySizeXmlMismatch, arrayLength, readerArrayLength))); } #endif context.IncrementItemCount(arrayLength); } protected int GetArrayLengthQuota(XmlObjectSerializerReadContext context) { if (dictionaryReader.Quotas == null) return context.RemainingItemCount; return Math.Min(context.RemainingItemCount, dictionaryReader.Quotas.MaxArrayLength); } void CheckActualArrayLength(int expectedLength, int actualLength, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { if (expectedLength != actualLength) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ArrayExceededSizeAttribute, expectedLength, itemName.Value, itemNamespace.Value))); } internal bool TryReadBooleanArray(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out bool[] array) { if (dictionaryReader == null) { array = null; return false; } if (arrayLength != -1) { CheckExpectedArrayLength(context, arrayLength); array = new bool[arrayLength]; int read = 0, offset = 0; while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0) { offset += read; } CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace); } else { array = BooleanArrayHelperWithDictionaryString.Instance.ReadArray( dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context)); context.IncrementItemCount(array.Length); } return true; } internal bool TryReadDateTimeArray(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out DateTime[] array) { if (dictionaryReader == null) { array = null; return false; } if (arrayLength != -1) { CheckExpectedArrayLength(context, arrayLength); array = new DateTime[arrayLength]; int read = 0, offset = 0; while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0) { offset += read; } CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace); } else { array = DateTimeArrayHelperWithDictionaryString.Instance.ReadArray( dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context)); context.IncrementItemCount(array.Length); } return true; } internal bool TryReadDecimalArray(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out decimal[] array) { if (dictionaryReader == null) { array = null; return false; } if (arrayLength != -1) { CheckExpectedArrayLength(context, arrayLength); array = new decimal[arrayLength]; int read = 0, offset = 0; while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0) { offset += read; } CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace); } else { array = DecimalArrayHelperWithDictionaryString.Instance.ReadArray( dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context)); context.IncrementItemCount(array.Length); } return true; } internal bool TryReadInt32Array(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out int[] array) { if (dictionaryReader == null) { array = null; return false; } if (arrayLength != -1) { CheckExpectedArrayLength(context, arrayLength); array = new int[arrayLength]; int read = 0, offset = 0; while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0) { offset += read; } CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace); } else { array = Int32ArrayHelperWithDictionaryString.Instance.ReadArray( dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context)); context.IncrementItemCount(array.Length); } return true; } internal bool TryReadInt64Array(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out long[] array) { if (dictionaryReader == null) { array = null; return false; } if (arrayLength != -1) { CheckExpectedArrayLength(context, arrayLength); array = new long[arrayLength]; int read = 0, offset = 0; while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0) { offset += read; } CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace); } else { array = Int64ArrayHelperWithDictionaryString.Instance.ReadArray( dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context)); context.IncrementItemCount(array.Length); } return true; } internal bool TryReadSingleArray(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out float[] array) { if (dictionaryReader == null) { array = null; return false; } if (arrayLength != -1) { CheckExpectedArrayLength(context, arrayLength); array = new float[arrayLength]; int read = 0, offset = 0; while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0) { offset += read; } CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace); } else { array = SingleArrayHelperWithDictionaryString.Instance.ReadArray( dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context)); context.IncrementItemCount(array.Length); } return true; } internal bool TryReadDoubleArray(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out double[] array) { if (dictionaryReader == null) { array = null; return false; } if (arrayLength != -1) { CheckExpectedArrayLength(context, arrayLength); array = new double[arrayLength]; int read = 0, offset = 0; while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0) { offset += read; } CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace); } else { array = DoubleArrayHelperWithDictionaryString.Instance.ReadArray( dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context)); context.IncrementItemCount(array.Length); } return true; } internal IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope) { return (reader is IXmlNamespaceResolver) ? ((IXmlNamespaceResolver)reader).GetNamespacesInScope(scope) : null; } // IXmlLineInfo members internal bool HasLineInfo() { IXmlLineInfo iXmlLineInfo = reader as IXmlLineInfo; return (iXmlLineInfo == null) ? false : iXmlLineInfo.HasLineInfo(); } internal int LineNumber { get { IXmlLineInfo iXmlLineInfo = reader as IXmlLineInfo; return (iXmlLineInfo == null) ? 0 : iXmlLineInfo.LineNumber; } } internal int LinePosition { get { IXmlLineInfo iXmlLineInfo = reader as IXmlLineInfo; return (iXmlLineInfo == null) ? 0 : iXmlLineInfo.LinePosition; } } // IXmlTextParser members internal bool Normalized { get { XmlTextReader xmlTextReader = reader as XmlTextReader; if (xmlTextReader == null) { IXmlTextParser xmlTextParser = reader as IXmlTextParser; return (xmlTextParser == null) ? false : xmlTextParser.Normalized; } else return xmlTextReader.Normalization; } set { XmlTextReader xmlTextReader = reader as XmlTextReader; if (xmlTextReader == null) { IXmlTextParser xmlTextParser = reader as IXmlTextParser; if (xmlTextParser != null) xmlTextParser.Normalized = value; } else xmlTextReader.Normalization = value; } } internal WhitespaceHandling WhitespaceHandling { get { XmlTextReader xmlTextReader = reader as XmlTextReader; if (xmlTextReader == null) { IXmlTextParser xmlTextParser = reader as IXmlTextParser; return (xmlTextParser == null) ? WhitespaceHandling.None : xmlTextParser.WhitespaceHandling; } else return xmlTextReader.WhitespaceHandling; } set { XmlTextReader xmlTextReader = reader as XmlTextReader; if (xmlTextReader == null) { IXmlTextParser xmlTextParser = reader as IXmlTextParser; if (xmlTextParser != null) xmlTextParser.WhitespaceHandling = value; } else xmlTextReader.WhitespaceHandling = value; } } // delegating properties and methods internal string Name { get { return reader.Name; } } #if USE_REFEMIT internal string LocalName #else public string LocalName #endif { get { return reader.LocalName; } } internal string NamespaceURI { get { return reader.NamespaceURI; } } internal string Value { get { return reader.Value; } } internal Type ValueType { get { return reader.ValueType; } } internal int Depth { get { return reader.Depth; } } internal string LookupNamespace(string prefix) { return reader.LookupNamespace(prefix); } internal bool EOF { get { return reader.EOF; } } internal void Skip() { reader.Skip(); isEndOfEmptyElement = false; } #if NotUsed internal XmlReaderSettings Settings { get { return reader.Settings; } } internal string Prefix { get { return reader.Prefix; } } internal bool HasValue { get { return reader.HasValue; } } internal string BaseURI { get { return reader.BaseURI; } } internal bool IsDefault { get { return reader.IsDefault; } } internal char QuoteChar { get { return reader.QuoteChar; } } internal XmlSpace XmlSpace { get { return reader.XmlSpace; } } internal string XmlLang { get { return reader.XmlLang; } } internal IXmlSchemaInfo SchemaInfo { get { return reader.SchemaInfo; } } internal string this[int i] { get { return reader[i]; } } internal string this[string name] { get { return reader[name]; } } internal string this[string name, string namespaceURI] { get { return reader[name, namespaceURI]; } } internal ReadState ReadState { get { return reader.ReadState; } } internal XmlNameTable NameTable { get { return reader.NameTable; } } internal bool CanResolveEntity { get { return reader.CanResolveEntity; } } internal bool CanReadBinaryContent { get { return reader.CanReadBinaryContent; } } internal bool CanReadValueChunk { get { return reader.CanReadValueChunk; } } internal bool HasAttributes { get { return reader.HasAttributes; } } internal bool IsStartElement(string name) { return reader.IsStartElement(name); } internal void ResolveEntity() { reader.ResolveEntity(); } internal string ReadInnerXml() { return reader.ReadInnerXml(); } internal string ReadOuterXml() { return reader.ReadOuterXml(); } internal object ReadContentAsObject() { return reader.ReadContentAsObject(); } internal object ReadContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver) { return reader.ReadContentAs(returnType, namespaceResolver); } internal object ReadElementContentAsObject() { return reader.ReadElementContentAsObject(); } internal object ReadElementContentAsObject(string localName, string namespaceURI) { return reader.ReadElementContentAsObject(localName, namespaceURI); } internal bool ReadElementContentAsBoolean(string localName, string namespaceURI) { return reader.ReadElementContentAsBoolean(localName, namespaceURI); } internal DateTime ReadElementContentAsDateTime(string localName, string namespaceURI) { return reader.ReadElementContentAsDateTime(localName, namespaceURI); } internal double ReadElementContentAsDouble(string localName, string namespaceURI) { return reader.ReadElementContentAsDouble(localName, namespaceURI); } internal int ReadElementContentAsInt(string localName, string namespaceURI) { return reader.ReadElementContentAsInt(localName, namespaceURI); } internal long ReadElementContentAsLong(string localName, string namespaceURI) { return reader.ReadElementContentAsLong(localName, namespaceURI); } internal string ReadElementContentAsString(string localName, string namespaceURI) { return reader.ReadElementContentAsString(localName, namespaceURI); } internal object ReadElementContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver) { return reader.ReadElementContentAs(returnType, namespaceResolver); } internal object ReadElementContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver, string localName, string namespaceURI) { return reader.ReadElementContentAs(returnType, namespaceResolver, localName, namespaceURI); } internal int ReadContentAsBase64(byte[] buffer, int index, int count) { return reader.ReadContentAsBase64(buffer, index, count); } internal int ReadElementContentAsBase64(byte[] buffer, int index, int count) { return reader.ReadElementContentAsBase64(buffer, index, count); } internal int ReadContentAsBinHex(byte[] buffer, int index, int count) { return reader.ReadContentAsBinHex(buffer, index, count); } internal int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { return reader.ReadElementContentAsBinHex(buffer, index, count); } internal int ReadValueChunk(char[] buffer, int index, int count) { return reader.ReadValueChunk(buffer, index, count); } internal string ReadString() { return reader.ReadString(); } internal string ReadElementString() { return reader.ReadElementString(); } internal string ReadElementString(string name) { return reader.ReadElementString(name); } internal string ReadElementString(string localname, string ns) { return reader.ReadElementString(localname, ns); } internal bool ReadToFollowing(string name) { return ReadToFollowing(name); } internal bool ReadToFollowing(string localName, string namespaceURI) { return reader.ReadToFollowing(localName, namespaceURI); } internal bool ReadToDescendant(string name) { return reader.ReadToDescendant(name); } internal bool ReadToDescendant(string localName, string namespaceURI) { return reader.ReadToDescendant(localName, namespaceURI); } internal bool ReadToNextSibling(string name) { return reader.ReadToNextSibling(name); } internal bool ReadToNextSibling(string localName, string namespaceURI) { return reader.ReadToNextSibling(localName, namespaceURI); } internal void ReadStartElement() { if (isEndOfEmptyElement) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.InvalidNodeType, this.NodeType.ToString()))); if (reader.IsEmptyElement) isEndOfEmptyElement = true; else reader.ReadStartElement(); } internal void ReadStartElement(String localname, String ns) { if (isEndOfEmptyElement) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.InvalidNodeType, this.NodeType.ToString()))); if (reader.IsEmptyElement) isEndOfEmptyElement = true; else reader.ReadStartElement(localname, ns); } internal void ReadStartElement(string name) { if (isEndOfEmptyElement) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.InvalidNodeType, this.NodeType.ToString()))); if (reader.IsEmptyElement) isEndOfEmptyElement = true; else reader.ReadStartElement(name); } internal XmlReader ReadSubtree() { if (this.NodeType == XmlNodeType.Element) return reader.ReadSubtree(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlFunctionRequiredNodeType, "ReadSubtree", "Element"))); } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using System.Collections.Generic; using Xunit; namespace System.Net.Http.Tests { public class HttpRuleParserTest { private const string ValidTokenChars = "!#$%&'*+-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz^_`|~"; public static IEnumerable<object[]> ValidTokenCharsArguments { get { foreach (var c in ValidTokenChars) { yield return new object[] { c }; } } } public static IEnumerable<object[]> InvalidTokenCharsArguments { get { // All octets not in 'ValidTokenChars' must be considered invalid characters. for (int i = 0; i < 256; i++) { if (ValidTokenChars.IndexOf((char)i) == -1) { yield return new object[] { (char)i }; } } } } [Theory] [MemberData(nameof(ValidTokenCharsArguments))] public void IsTokenChar_ValidTokenChars_ConsideredValid(char token) { Assert.True(HttpRuleParser.IsTokenChar(token)); } [Theory] [MemberData(nameof(InvalidTokenCharsArguments))] public void IsTokenChar_InvalidTokenChars_ConsideredInvalid(char token) { Assert.False(HttpRuleParser.IsTokenChar(token)); } [Fact] public void GetTokenLength_SetOfValidTokens_AllConsideredValid() { AssertGetTokenLength("token", 0, 5); AssertGetTokenLength(" token ", 1, 5); AssertGetTokenLength(" token token", 1, 5); AssertGetTokenLength("x, y", 0, 1); AssertGetTokenLength("x,y", 0, 1); AssertGetTokenLength(":x:y", 1, 1); AssertGetTokenLength("(comment)token(comment)", 9, 5); } [Fact] public void GetTokenLength_SetOfInvalidTokens_TokenLengthIsZero() { AssertGetTokenLength(" token", 0, 0); AssertGetTokenLength("\token", 0, 0); AssertGetTokenLength("token token ", 5, 0); AssertGetTokenLength(" ", 0, 0); } [Fact] public void GetHostLength_SetOfValidHostStrings_MatchExpectation() { // Allow token or URI host: AssertGetHostLength("", 0, 0, true, null); AssertGetHostLength(" ", 2, 0, true, null); AssertGetHostLength("host", 0, 4, true, "host"); AssertGetHostLength("host:80", 0, 7, true, "host:80"); AssertGetHostLength("host:80 ", 0, 7, true, "host:80"); AssertGetHostLength("host:80,nexthost", 0, 7, true, "host:80"); AssertGetHostLength("host.com:80,nexthost", 0, 11, true, "host.com:80"); AssertGetHostLength(".token ,nexthost", 0, 6, true, ".token"); AssertGetHostLength(".token nexthost", 0, 6, true, ".token"); AssertGetHostLength(".token", 0, 6, true, ".token"); AssertGetHostLength("[::1]:80", 0, 8, true, "[::1]:80"); AssertGetHostLength("[::1],host", 0, 5, true, "[::1]"); AssertGetHostLength("192.168.0.1,", 0, 11, true, "192.168.0.1"); AssertGetHostLength("192.168.0.1:8080 ", 0, 16, true, "192.168.0.1:8080"); // Allow URI host only (no token): AssertGetHostLength("", 0, 0, false, null); AssertGetHostLength(" ", 2, 0, false, null); AssertGetHostLength("host", 0, 4, false, "host"); AssertGetHostLength("host:80", 0, 7, false, "host:80"); AssertGetHostLength("host:80 ", 0, 7, false, "host:80"); AssertGetHostLength("host:80,nexthost", 0, 7, false, "host:80"); AssertGetHostLength("host.com:80,nexthost", 0, 11, false, "host.com:80"); AssertGetHostLength("[::1]:80", 0, 8, false, "[::1]:80"); AssertGetHostLength("[::1],host", 0, 5, false, "[::1]"); AssertGetHostLength("192.168.0.1,", 0, 11, false, "192.168.0.1"); AssertGetHostLength("192.168.0.1:8080 ", 0, 16, false, "192.168.0.1:8080"); } [Fact] public void GetHostLength_SetOfInvalidHostStrings_MatchExpectation() { // Allow token or URI host: AssertGetHostLength("host:80invalid", 0, 0, true, null); AssertGetHostLength("host:80:nexthost", 0, 0, true, null); AssertGetHostLength(" ", 0, 0, true, null); AssertGetHostLength("token@:80", 0, 0, true, null); AssertGetHostLength("token@host:80", 0, 0, true, null); AssertGetHostLength("token@host", 0, 0, true, null); AssertGetHostLength("token@", 0, 0, true, null); AssertGetHostLength("token<", 0, 0, true, null); AssertGetHostLength("192.168.0.1:8080!", 0, 0, true, null); AssertGetHostLength(".token/", 0, 0, true, null); AssertGetHostLength("host:80/", 0, 0, true, null); AssertGetHostLength("host:80/path", 0, 0, true, null); AssertGetHostLength("@host:80", 0, 0, true, null); AssertGetHostLength("u:p@host:80", 0, 0, true, null); // Allow URI host only (no token): AssertGetHostLength("host:80invalid", 0, 0, false, null); AssertGetHostLength("host:80:nexthost", 0, 0, false, null); AssertGetHostLength(" ", 0, 0, false, null); AssertGetHostLength("token@:80", 0, 0, false, null); AssertGetHostLength("token@host:80", 0, 0, false, null); AssertGetHostLength("token@host", 0, 0, false, null); AssertGetHostLength("token@", 0, 0, false, null); AssertGetHostLength("token<", 0, 0, false, null); AssertGetHostLength("192.168.0.1:8080!", 0, 0, false, null); AssertGetHostLength(".token/", 0, 0, false, null); AssertGetHostLength("host:80/", 0, 0, false, null); AssertGetHostLength("host:80/path", 0, 0, false, null); AssertGetHostLength("@host:80", 0, 0, false, null); AssertGetHostLength("u:p@host:80", 0, 0, false, null); AssertGetHostLength(".token", 0, 0, false, null); AssertGetHostLength("to~ken", 0, 0, false, null); } [Fact] public void GetQuotedPairLength_SetOfValidQuotedPairs_AllConsideredValid() { AssertGetQuotedPairLength("\\x", 0, 2, HttpParseResult.Parsed); AssertGetQuotedPairLength(" \\x ", 1, 2, HttpParseResult.Parsed); AssertGetQuotedPairLength("\\x ", 0, 2, HttpParseResult.Parsed); AssertGetQuotedPairLength("\\\t", 0, 2, HttpParseResult.Parsed); } [Fact] public void GetQuotedPairLength_SetOfInvalidQuotedPairs_AllConsideredInvalid() { // only ASCII chars allowed in quoted-pair AssertGetQuotedPairLength("\\\u00FC", 0, 0, HttpParseResult.InvalidFormat); // a quoted-pair needs 1 char after '\' AssertGetQuotedPairLength("\\", 0, 0, HttpParseResult.InvalidFormat); } [Fact] public void GetQuotedPairLength_SetOfNonQuotedPairs_NothingParsed() { AssertGetQuotedPairLength("token\\x", 0, 0, HttpParseResult.NotParsed); } [Fact] public void GetQuotedStringLength_SetOfValidQuotedStrings_AllConsideredValid() { AssertGetQuotedStringLength("\"x\"", 0, 3, HttpParseResult.Parsed); AssertGetQuotedStringLength("token \"quoted string\" token", 6, 15, HttpParseResult.Parsed); AssertGetQuotedStringLength("\"\\x\"", 0, 4, HttpParseResult.Parsed); // "\x" AssertGetQuotedStringLength("\"\\\"\"", 0, 4, HttpParseResult.Parsed); // "\"" AssertGetQuotedStringLength("\"before \\\" after\"", 0, 17, HttpParseResult.Parsed); // "before \" after" AssertGetQuotedStringLength("\"\\\u00FC\"", 0, 4, HttpParseResult.Parsed); // "\\u00FC" AssertGetQuotedStringLength("\"a\\\u00FC\\\"b\"", 0, 8, HttpParseResult.Parsed); // "a\\u00FC\"b" AssertGetQuotedStringLength("\"\\\"", 0, 3, HttpParseResult.Parsed); // "\" AssertGetQuotedStringLength("\"\\\"\"", 0, 4, HttpParseResult.Parsed); // "\"" AssertGetQuotedStringLength(" \"\\\"", 1, 3, HttpParseResult.Parsed); // "\" AssertGetQuotedStringLength(" \"\\\"\"", 1, 4, HttpParseResult.Parsed); // "\"" AssertGetQuotedStringLength("\"a \\\" b\"", 0, 8, HttpParseResult.Parsed); // "a \" b" AssertGetQuotedStringLength("\"s\\x\"", 0, 5, HttpParseResult.Parsed); // "s\x" AssertGetQuotedStringLength("\"\\xx\"", 0, 5, HttpParseResult.Parsed); // "\xx" AssertGetQuotedStringLength("\"(x)\"", 0, 5, HttpParseResult.Parsed); // "(x)" AssertGetQuotedStringLength(" \" (x) \" ", 1, 7, HttpParseResult.Parsed); // " (x) " AssertGetQuotedStringLength("\"text\r\n new line\"", 0, 17, HttpParseResult.Parsed); // "text<crlf> new line" AssertGetQuotedStringLength("\"a\\\u00FC\\\"b\\\"c\\\"\\\"d\\\"\"", 0, 18, HttpParseResult.Parsed); // "a\\u00FC\"b\"c\"\"d\"" AssertGetQuotedStringLength("\"\\\" \"", 0, 5, HttpParseResult.Parsed); // "\" " } [Fact] public void GetQuotedStringLength_SetOfInvalidQuotedStrings_AllConsideredInvalid() { AssertGetQuotedStringLength("\"x", 0, 0, HttpParseResult.InvalidFormat); // "x AssertGetQuotedStringLength(" \"x ", 1, 0, HttpParseResult.InvalidFormat); // ' "x ' } [Fact] public void GetQuotedStringLength_SetOfNonQuotedStrings_NothingParsed() { AssertGetQuotedStringLength("a\"x", 0, 0, HttpParseResult.NotParsed); // a"x" AssertGetQuotedStringLength("(\"x", 0, 0, HttpParseResult.NotParsed); // ("x" AssertGetQuotedStringLength("\\\"x", 0, 0, HttpParseResult.NotParsed); // \"x" } [Fact] public void GetCommentLength_SetOfValidComments_AllConsideredValid() { AssertGetCommentLength("()", 0, 2, HttpParseResult.Parsed); AssertGetCommentLength("(x)", 0, 3, HttpParseResult.Parsed); AssertGetCommentLength("token (comment) token", 6, 9, HttpParseResult.Parsed); AssertGetCommentLength("(\\x)", 0, 4, HttpParseResult.Parsed); // (\x) AssertGetCommentLength("(\\))", 0, 4, HttpParseResult.Parsed); // (\)) AssertGetCommentLength("(\\()", 0, 4, HttpParseResult.Parsed); // (\() AssertGetCommentLength("(\\\u00FC)", 0, 4, HttpParseResult.Parsed); // (\\u00FC) AssertGetCommentLength("(\\)", 0, 3, HttpParseResult.Parsed); // (\) AssertGetCommentLength("(s\\x)", 0, 5, HttpParseResult.Parsed); // (s\x) AssertGetCommentLength("(\\xx)", 0, 5, HttpParseResult.Parsed); // (\xx) AssertGetCommentLength("(\"x\")", 0, 5, HttpParseResult.Parsed); // ("x") AssertGetCommentLength(" ( \"x\" ) ", 1, 7, HttpParseResult.Parsed); // ( "x" ) AssertGetCommentLength("(text\r\n new line)", 0, 17, HttpParseResult.Parsed); // (text<crlf> new line) AssertGetCommentLength("(\\) )", 0, 5, HttpParseResult.Parsed); // (\)) AssertGetCommentLength("(\\( )", 0, 5, HttpParseResult.Parsed); // (\() // Nested comments AssertGetCommentLength("((x))", 0, 5, HttpParseResult.Parsed); AssertGetCommentLength("( (x) )", 0, 7, HttpParseResult.Parsed); AssertGetCommentLength("( (\\(x) )", 0, 9, HttpParseResult.Parsed); AssertGetCommentLength("( (\\)x) )", 0, 9, HttpParseResult.Parsed); AssertGetCommentLength("(\\) (\\(x) )", 0, 11, HttpParseResult.Parsed); AssertGetCommentLength("((((((x))))))", 0, 13, HttpParseResult.Parsed); AssertGetCommentLength("((x) (x) ((x)x) ((((x)x)x)x(x(x))))", 0, 35, HttpParseResult.Parsed); AssertGetCommentLength("((x) (\\(x\\())", 0, 13, HttpParseResult.Parsed); // ((x) (\(x\())) AssertGetCommentLength("((\\)))", 0, 6, HttpParseResult.Parsed); // ((\))) -> quoted-pair ) AssertGetCommentLength("((\\())", 0, 6, HttpParseResult.Parsed); // ((\()) -> quoted-pair ( AssertGetCommentLength("((x)))", 0, 5, HttpParseResult.Parsed); // final ) ignored AssertGetCommentLength("(x (y)(z))", 0, 10, HttpParseResult.Parsed); AssertGetCommentLength("(x(y)\\()", 0, 8, HttpParseResult.Parsed); } [Fact] public void GetCommentLength_SetOfInvalidQuotedStrings_AllConsideredInvalid() { AssertGetCommentLength("(x", 0, 0, HttpParseResult.InvalidFormat); AssertGetCommentLength(" (x ", 1, 0, HttpParseResult.InvalidFormat); AssertGetCommentLength("((x) ", 0, 0, HttpParseResult.InvalidFormat); AssertGetCommentLength("((x ", 0, 0, HttpParseResult.InvalidFormat); AssertGetCommentLength("(x(x ", 0, 0, HttpParseResult.InvalidFormat); AssertGetCommentLength("(x(((((((((x ", 0, 0, HttpParseResult.InvalidFormat); // To prevent attacker from sending comments resulting in stack overflow exceptions, we limit the depth // of nested comments. I.e. the following comment is considered invalid since it is considered a // "malicious" comment. AssertGetCommentLength("((((((((((x))))))))))", 0, 0, HttpParseResult.InvalidFormat); AssertGetCommentLength("(x(x)", 0, 0, HttpParseResult.InvalidFormat); AssertGetCommentLength("(x(x(", 0, 0, HttpParseResult.InvalidFormat); AssertGetCommentLength("(x(()", 0, 0, HttpParseResult.InvalidFormat); AssertGetCommentLength("(()", 0, 0, HttpParseResult.InvalidFormat); AssertGetCommentLength("(", 0, 0, HttpParseResult.InvalidFormat); AssertGetCommentLength("((x)", 0, 0, HttpParseResult.InvalidFormat); } [Fact] public void GetCommentLength_SetOfNonQuotedStrings_NothingParsed() { AssertGetCommentLength("a(x", 0, 0, HttpParseResult.NotParsed); // a"x" AssertGetCommentLength("\"(x", 0, 0, HttpParseResult.NotParsed); // ("x" AssertGetCommentLength("\\(x", 0, 0, HttpParseResult.NotParsed); // \"x" } [Fact] public void GetWhitespaceLength_SetOfValidWhitespaces_ParsedCorrectly() { Assert.Equal(1, HttpRuleParser.GetWhitespaceLength(" ", 0)); Assert.Equal(0, HttpRuleParser.GetWhitespaceLength("a b", 0)); Assert.Equal(1, HttpRuleParser.GetWhitespaceLength("a b", 1)); Assert.Equal(1, HttpRuleParser.GetWhitespaceLength("a\tb", 1)); Assert.Equal(1, HttpRuleParser.GetWhitespaceLength("a\t", 1)); Assert.Equal(3, HttpRuleParser.GetWhitespaceLength("a\t ", 1)); Assert.Equal(2, HttpRuleParser.GetWhitespaceLength("\t b", 0)); // Newlines Assert.Equal(3, HttpRuleParser.GetWhitespaceLength("a\r\n b", 1)); Assert.Equal(3, HttpRuleParser.GetWhitespaceLength("\r\n ", 0)); Assert.Equal(3, HttpRuleParser.GetWhitespaceLength("\r\n\t", 0)); Assert.Equal(13, HttpRuleParser.GetWhitespaceLength(" \r\n\t\t \r\n ", 0)); Assert.Equal(1, HttpRuleParser.GetWhitespaceLength(" \r\n", 0)); // first char considered valid whitespace Assert.Equal(1, HttpRuleParser.GetWhitespaceLength(" \r\n\r\n ", 0)); Assert.Equal(3, HttpRuleParser.GetWhitespaceLength(" \r\n\r\n ", 3)); } [Fact] public void GetWhitespaceLength_SetOfInvalidWhitespaces_ReturnsZero() { // Newlines: SP/HT required after #13#10 Assert.Equal(0, HttpRuleParser.GetWhitespaceLength("\r\n", 0)); Assert.Equal(0, HttpRuleParser.GetWhitespaceLength(" \r\n\r\n", 1)); Assert.Equal(0, HttpRuleParser.GetWhitespaceLength("a\r\nb", 1)); } [Fact] public void GetNumberLength_SetOfValidNumbers_ParsedCorrectly() { Assert.Equal(3, HttpRuleParser.GetNumberLength("123", 0, false)); Assert.Equal(4, HttpRuleParser.GetNumberLength("123.", 0, true)); Assert.Equal(7, HttpRuleParser.GetNumberLength("123.456", 0, true)); Assert.Equal(1, HttpRuleParser.GetNumberLength("1a", 0, false)); Assert.Equal(2, HttpRuleParser.GetNumberLength("1.a", 0, true)); Assert.Equal(2, HttpRuleParser.GetNumberLength("1..", 0, true)); Assert.Equal(3, HttpRuleParser.GetNumberLength("1.2.", 0, true)); Assert.Equal(1, HttpRuleParser.GetNumberLength("1.2.", 0, false)); Assert.Equal(5, HttpRuleParser.GetNumberLength("123456", 1, false)); Assert.Equal(1, HttpRuleParser.GetNumberLength("1.5", 0, false)); // parse until '.' Assert.Equal(1, HttpRuleParser.GetNumberLength("1 2 3", 2, true)); // GetNumberLength doesn't have any size restrictions. The caller needs to decide whether a value is // outside the valid range or not. Assert.Equal(30, HttpRuleParser.GetNumberLength("123456789012345678901234567890", 0, false)); Assert.Equal(61, HttpRuleParser.GetNumberLength( "123456789012345678901234567890.123456789012345678901234567890", 0, true)); } [Fact] public void GetNumberLength_SetOfInvalidNumbers_ReturnsZero() { Assert.Equal(0, HttpRuleParser.GetNumberLength(".456", 0, true)); Assert.Equal(0, HttpRuleParser.GetNumberLength("-1", 0, true)); Assert.Equal(0, HttpRuleParser.GetNumberLength("a", 0, true)); } #region Helper methods private static void AssertGetTokenLength(string input, int startIndex, int expectedLength) { Assert.Equal(expectedLength, HttpRuleParser.GetTokenLength(input, startIndex)); } private static void AssertGetQuotedPairLength(string input, int startIndex, int expectedLength, HttpParseResult expectedResult) { int length = 0; HttpParseResult result = HttpRuleParser.GetQuotedPairLength(input, startIndex, out length); Assert.Equal(expectedResult, result); Assert.Equal(expectedLength, length); } private static void AssertGetQuotedStringLength(string input, int startIndex, int expectedLength, HttpParseResult expectedResult) { int length = 0; HttpParseResult result = HttpRuleParser.GetQuotedStringLength(input, startIndex, out length); Assert.Equal(expectedResult, result); Assert.Equal(expectedLength, length); } private static void AssertGetCommentLength(string input, int startIndex, int expectedLength, HttpParseResult expectedResult) { int length = 0; HttpParseResult result = HttpRuleParser.GetCommentLength(input, startIndex, out length); Assert.Equal(expectedResult, result); Assert.Equal(expectedLength, length); } private static void AssertGetHostLength(string input, int startIndex, int expectedLength, bool allowToken, string expectedResult) { string result = null; Assert.Equal(expectedLength, HttpRuleParser.GetHostLength(input, startIndex, allowToken, out result)); Assert.Equal(expectedResult, result); } #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.Buffers; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.Net.Sockets { // Provides the underlying stream of data for network access. public class NetworkStream : Stream { // Used by the class to hold the underlying socket the stream uses. private Socket _streamSocket; // Used by the class to indicate that the stream is m_Readable. private bool _readable; // Used by the class to indicate that the stream is writable. private bool _writeable; private bool _ownsSocket; // Creates a new instance of the System.Net.Sockets.NetworkStream without initialization. internal NetworkStream() { _ownsSocket = true; } // Creates a new instance of the System.Net.Sockets.NetworkStream class for the specified System.Net.Sockets.Socket. public NetworkStream(Socket socket) : this(socket, FileAccess.ReadWrite, ownsSocket: false) { } public NetworkStream(Socket socket, bool ownsSocket) : this(socket, FileAccess.ReadWrite, ownsSocket) { } public NetworkStream(Socket socket, FileAccess access) : this(socket, access, ownsSocket: false) { } public NetworkStream(Socket socket, FileAccess access, bool ownsSocket) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User)) { #endif if (socket == null) { throw new ArgumentNullException(nameof(socket)); } if (!socket.Blocking) { throw new IOException(SR.net_sockets_blocking); } if (!socket.Connected) { throw new IOException(SR.net_notconnected); } if (socket.SocketType != SocketType.Stream) { throw new IOException(SR.net_notstream); } _streamSocket = socket; _ownsSocket = ownsSocket; switch (access) { case FileAccess.Read: _readable = true; break; case FileAccess.Write: _writeable = true; break; case FileAccess.ReadWrite: default: // assume FileAccess.ReadWrite _readable = true; _writeable = true; break; } #if DEBUG } #endif } // Socket - provides access to socket for stream closing protected Socket Socket { get { return _streamSocket; } } internal Socket InternalSocket { get { Socket chkSocket = _streamSocket; if (_cleanedUp || chkSocket == null) { throw new ObjectDisposedException(this.GetType().FullName); } return chkSocket; } } internal void InternalAbortSocket() { if (!_ownsSocket) { throw new InvalidOperationException(); } Socket chkSocket = _streamSocket; if (_cleanedUp || chkSocket == null) { return; } try { chkSocket.Dispose(); } catch (ObjectDisposedException) { } } internal void ConvertToNotSocketOwner() { _ownsSocket = false; // Suppress for finialization still allow proceed the requests GC.SuppressFinalize(this); } // Used by the class to indicate that the stream is m_Readable. protected bool Readable { get { return _readable; } set { _readable = value; } } // Used by the class to indicate that the stream is writable. protected bool Writeable { get { return _writeable; } set { _writeable = value; } } // Indicates that data can be read from the stream. // We return the readability of this stream. This is a read only property. public override bool CanRead { get { return _readable; } } // Indicates that the stream can seek a specific location // in the stream. This property always returns false. public override bool CanSeek { get { return false; } } // Indicates that data can be written to the stream. public override bool CanWrite { get { return _writeable; } } // Indicates whether we can timeout public override bool CanTimeout { get { return true; // should we check for Connected state? } } // Set/Get ReadTimeout, note of a strange behavior, 0 timeout == infinite for sockets, // so we map this to -1, and if you set 0, we cannot support it public override int ReadTimeout { get { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout); if (timeout == 0) { return -1; } return timeout; #if DEBUG } #endif } set { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif if (value <= 0 && value != System.Threading.Timeout.Infinite) { throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_gt_zero); } SetSocketTimeoutOption(SocketShutdown.Receive, value, false); #if DEBUG } #endif } } // Set/Get WriteTimeout, note of a strange behavior, 0 timeout == infinite for sockets, // so we map this to -1, and if you set 0, we cannot support it public override int WriteTimeout { get { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout); if (timeout == 0) { return -1; } return timeout; #if DEBUG } #endif } set { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif if (value <= 0 && value != System.Threading.Timeout.Infinite) { throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_gt_zero); } SetSocketTimeoutOption(SocketShutdown.Send, value, false); #if DEBUG } #endif } } // Indicates data is available on the stream to be read. // This property checks to see if at least one byte of data is currently available public virtual bool DataAvailable { get { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } // Ask the socket how many bytes are available. If it's // not zero, return true. return chkStreamSocket.Available != 0; #if DEBUG } #endif } } // The length of data available on the stream. Always throws NotSupportedException. public override long Length { get { throw new NotSupportedException(SR.net_noseek); } } // Gets or sets the position in the stream. Always throws NotSupportedException. public override long Position { get { throw new NotSupportedException(SR.net_noseek); } set { throw new NotSupportedException(SR.net_noseek); } } // Seeks a specific position in the stream. This method is not supported by the // NetworkStream class. public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(SR.net_noseek); } internal bool PollRead() { if (_cleanedUp) { return false; } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { return false; } return chkStreamSocket.Poll(0, SelectMode.SelectRead); } internal bool Poll(int microSeconds, SelectMode mode) { if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } return chkStreamSocket.Poll(microSeconds, mode); } // Read - provide core Read functionality. // // Provide core read functionality. All we do is call through to the // socket Receive functionality. // // Input: // // Buffer - Buffer to read into. // Offset - Offset into the buffer where we're to read. // Count - Number of bytes to read. // // Returns: // // Number of bytes we read, or 0 if the socket is closed. public override int Read(byte[] buffer, int offset, int size) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) { #endif bool canRead = CanRead; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canRead) { throw new InvalidOperationException(SR.net_writeonlystream); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException(nameof(size)); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } try { int bytesTransferred = chkStreamSocket.Receive(buffer, offset, size, 0); return bytesTransferred; } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception); } #if DEBUG } #endif } // Write - provide core Write functionality. // // Provide core write functionality. All we do is call through to the // socket Send method.. // // Input: // // Buffer - Buffer to write from. // Offset - Offset into the buffer from where we'll start writing. // Count - Number of bytes to write. // // Returns: // // Number of bytes written. We'll throw an exception if we // can't write everything. It's brutal, but there's no other // way to indicate an error. public override void Write(byte[] buffer, int offset, int size) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) { #endif bool canWrite = CanWrite; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canWrite) { throw new InvalidOperationException(SR.net_readonlystream); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException(nameof(size)); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_writefailure, SR.net_io_connectionclosed)); } try { // Since the socket is in blocking mode this will always complete // after ALL the requested number of bytes was transferred. chkStreamSocket.Send(buffer, offset, size, SocketFlags.None); } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception); } #if DEBUG } #endif } private int _closeTimeout = Socket.DefaultCloseTimeout; // -1 = respect linger options public void Close(int timeout) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) { #endif if (timeout < -1) { throw new ArgumentOutOfRangeException(nameof(timeout)); } _closeTimeout = timeout; Dispose(); #if DEBUG } #endif } private volatile bool _cleanedUp = false; protected override void Dispose(bool disposing) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User)) { #endif // Mark this as disposed before changing anything else. bool cleanedUp = _cleanedUp; _cleanedUp = true; if (!cleanedUp && disposing) { // The only resource we need to free is the network stream, since this // is based on the client socket, closing the stream will cause us // to flush the data to the network, close the stream and (in the // NetoworkStream code) close the socket as well. if (_streamSocket != null) { _readable = false; _writeable = false; if (_ownsSocket) { // If we own the Socket (false by default), close it // ignoring possible exceptions (eg: the user told us // that we own the Socket but it closed at some point of time, // here we would get an ObjectDisposedException) Socket chkStreamSocket = _streamSocket; if (chkStreamSocket != null) { chkStreamSocket.InternalShutdown(SocketShutdown.Both); chkStreamSocket.Close(_closeTimeout); } } } } #if DEBUG } #endif base.Dispose(disposing); } ~NetworkStream() { #if DEBUG DebugThreadTracking.SetThreadSource(ThreadKinds.Finalization); #endif Dispose(false); } // Indicates whether the stream is still connected internal bool Connected { get { Socket socket = _streamSocket; if (!_cleanedUp && socket != null && socket.Connected) { return true; } else { return false; } } } // BeginRead - provide async read functionality. // // This method provides async read functionality. All we do is // call through to the underlying socket async read. // // Input: // // buffer - Buffer to read into. // offset - Offset into the buffer where we're to read. // size - Number of bytes to read. // // Returns: // // An IASyncResult, representing the read. #if !netcore50 override #endif public IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif bool canRead = CanRead; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canRead) { throw new InvalidOperationException(SR.net_writeonlystream); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException(nameof(size)); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } try { IAsyncResult asyncResult = chkStreamSocket.BeginReceive( buffer, offset, size, SocketFlags.None, callback, state); return asyncResult; } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception); } #if DEBUG } #endif } internal virtual IAsyncResult UnsafeBeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { bool canRead = CanRead; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(GetType().FullName); } if (!canRead) { throw new InvalidOperationException(SR.net_writeonlystream); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } try { IAsyncResult asyncResult = chkStreamSocket.UnsafeBeginReceive( buffer, offset, size, SocketFlags.None, callback, state); return asyncResult; } catch (Exception exception) { if (ExceptionCheck.IsFatal(exception)) throw; // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception); } } // EndRead - handle the end of an async read. // // This method is called when an async read is completed. All we // do is call through to the core socket EndReceive functionality. // // Returns: // // The number of bytes read. May throw an exception. #if !netcore50 override #endif public int EndRead(IAsyncResult asyncResult) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User)) { #endif if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } // Validate input parameters. if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } try { int bytesTransferred = chkStreamSocket.EndReceive(asyncResult); return bytesTransferred; } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception); } #if DEBUG } #endif } // BeginWrite - provide async write functionality. // // This method provides async write functionality. All we do is // call through to the underlying socket async send. // // Input: // // buffer - Buffer to write into. // offset - Offset into the buffer where we're to write. // size - Number of bytes to written. // // Returns: // // An IASyncResult, representing the write. #if !netcore50 override #endif public IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif bool canWrite = CanWrite; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canWrite) { throw new InvalidOperationException(SR.net_readonlystream); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException(nameof(size)); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_writefailure, SR.net_io_connectionclosed)); } try { // Call BeginSend on the Socket. IAsyncResult asyncResult = chkStreamSocket.BeginSend( buffer, offset, size, SocketFlags.None, callback, state); return asyncResult; } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception); } #if DEBUG } #endif } internal virtual IAsyncResult UnsafeBeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif bool canWrite = CanWrite; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canWrite) { throw new InvalidOperationException(SR.net_readonlystream); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_writefailure, SR.net_io_connectionclosed)); } try { // Call BeginSend on the Socket. IAsyncResult asyncResult = chkStreamSocket.UnsafeBeginSend( buffer, offset, size, SocketFlags.None, callback, state); return asyncResult; } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception); } #if DEBUG } #endif } // Handle the end of an asynchronous write. // This method is called when an async write is completed. All we // do is call through to the core socket EndSend functionality. // Returns: The number of bytes read. May throw an exception. #if !netcore50 override #endif public void EndWrite(IAsyncResult asyncResult) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User)) { #endif if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } // Validate input parameters. if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_writefailure, SR.net_io_connectionclosed)); } try { chkStreamSocket.EndSend(asyncResult); } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception); } #if DEBUG } #endif } // ReadAsync - provide async read functionality. // // This method provides async read functionality. All we do is // call through to the Begin/EndRead methods. // // Input: // // buffer - Buffer to read into. // offset - Offset into the buffer where we're to read. // size - Number of bytes to read. // cancellationToken - Token used to request cancellation of the operation // // Returns: // // A Task<int> representing the read. public override Task<int> ReadAsync(byte[] buffer, int offset, int size, CancellationToken cancellationToken) { #if netcore50 if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<int>(cancellationToken); } return Task.Factory.FromAsync( (bufferArg, offsetArg, sizeArg, callback, state) => ((NetworkStream)state).BeginRead(bufferArg, offsetArg, sizeArg, callback, state), iar => ((NetworkStream)iar.AsyncState).EndRead(iar), buffer, offset, size, this); #else // Use optimized Stream.ReadAsync that's more efficient than // Task.Factory.FromAsync when NetworkStream overrides Begin/EndRead. return base.ReadAsync(buffer, offset, size, cancellationToken); #endif } // WriteAsync - provide async write functionality. // // This method provides async write functionality. All we do is // call through to the Begin/EndWrite methods. // // Input: // // buffer - Buffer to write into. // offset - Offset into the buffer where we're to write. // size - Number of bytes to write. // cancellationToken - Token used to request cancellation of the operation // // Returns: // // A Task representing the write. public override Task WriteAsync(byte[] buffer, int offset, int size, CancellationToken cancellationToken) { #if netcore50 if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<int>(cancellationToken); } return Task.Factory.FromAsync( (bufferArg, offsetArg, sizeArg, callback, state) => ((NetworkStream)state).BeginWrite(bufferArg, offsetArg, sizeArg, callback, state), iar => ((NetworkStream)iar.AsyncState).EndWrite(iar), buffer, offset, size, this); #else // Use optimized Stream.WriteAsync that's more efficient than // Task.Factory.FromAsync when NetworkStream overrides Begin/EndWrite. return base.WriteAsync(buffer, offset, size, cancellationToken); #endif } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { // Validate arguments as would the base CopyToAsync StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); // And bail early if cancellation has already been requested if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } // Then do additional checks as ReadAsync would. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } Socket streamSocket = _streamSocket; if (streamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } // Do the copy. We get a copy buffer from the shared pool, and we pass both it and the // socket into the copy as part of the event args so as to avoid additional fields in // the async method's state machine. return CopyToAsyncCore( destination, new AwaitableSocketAsyncEventArgs(streamSocket, ArrayPool<byte>.Shared.Rent(bufferSize)), cancellationToken); } private static async Task CopyToAsyncCore(Stream destination, AwaitableSocketAsyncEventArgs ea, CancellationToken cancellationToken) { try { while (true) { cancellationToken.ThrowIfCancellationRequested(); int bytesRead = await ea.ReceiveAsync(); if (bytesRead == 0) { break; } await destination.WriteAsync(ea.Buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); } } finally { ArrayPool<byte>.Shared.Return(ea.Buffer, clearArray: true); ea.Dispose(); } } // Flushes data from the stream. This is meaningless for us, so it does nothing. public override void Flush() { } public override Task FlushAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } // Sets the length of the stream. Always throws NotSupportedException public override void SetLength(long value) { throw new NotSupportedException(SR.net_noseek); } private int _currentReadTimeout = -1; private int _currentWriteTimeout = -1; internal void SetSocketTimeoutOption(SocketShutdown mode, int timeout, bool silent) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, mode, timeout, silent); DebugThreadTracking.ThreadContract(ThreadKinds.Unknown, $"NetworkStream#{NetEventSource.IdOf(this)}"); if (timeout < 0) { timeout = 0; // -1 becomes 0 for the winsock stack } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { return; } if (mode == SocketShutdown.Send || mode == SocketShutdown.Both) { if (timeout != _currentWriteTimeout) { chkStreamSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout, silent); _currentWriteTimeout = timeout; } } if (mode == SocketShutdown.Receive || mode == SocketShutdown.Both) { if (timeout != _currentReadTimeout) { chkStreamSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout, silent); _currentReadTimeout = timeout; } } } [System.Diagnostics.Conditional("TRACE_VERBOSE")] internal void DebugMembers() { if (_streamSocket != null) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, _streamSocket); _streamSocket.DebugMembers(); } } /// <summary>A SocketAsyncEventArgs that can be awaited to get the result of an operation.</summary> internal sealed class AwaitableSocketAsyncEventArgs : SocketAsyncEventArgs, ICriticalNotifyCompletion { /// <summary>Sentinel object used to indicate that the operation has completed prior to OnCompleted being called.</summary> private static readonly Action s_completedSentinel = () => { }; /// <summary> /// null if the operation has not completed, <see cref="s_completedSentinel"/> if it has, and another object /// if OnCompleted was called before the operation could complete, in which case it's the delegate to invoke /// when the operation does complete. /// </summary> private Action _continuation; /// <summary>Initializes the event args.</summary> /// <param name="socket">The associated socket.</param> /// <param name="buffer">The buffer to use for all operations.</param> public AwaitableSocketAsyncEventArgs(Socket socket, byte[] buffer) { Debug.Assert(socket != null); Debug.Assert(buffer != null && buffer.Length > 0); // Store the socket into the base's UserToken. This avoids the need for an extra field, at the expense // of an object=>Socket cast when we need to access it, which is only once per operation. UserToken = socket; // Store the buffer for use by all operations with this instance. SetBuffer(buffer, 0, buffer.Length); // Hook up the completed event. Completed += delegate { // When the operation completes, see if OnCompleted was already called to hook up a continuation. // If it was, invoke the continuation. Action c = _continuation; if (c != null) { c(); } else { // We may be racing with OnCompleted, so check with synchronization, trying to swap in our // completion sentinel. If we lose the race and OnCompleted did hook up a continuation, // invoke it. Otherwise, there's nothing more to be done. Interlocked.CompareExchange(ref _continuation, s_completedSentinel, null)?.Invoke(); } }; } /// <summary>Initiates a receive operation on the associated socket.</summary> /// <returns>This instance.</returns> public AwaitableSocketAsyncEventArgs ReceiveAsync() { if (!Socket.ReceiveAsync(this)) { _continuation = s_completedSentinel; } return this; } /// <summary>Gets this instance.</summary> public AwaitableSocketAsyncEventArgs GetAwaiter() => this; /// <summary>Gets whether the operation has already completed.</summary> /// <remarks> /// This is not a generically usable IsCompleted operation that suggests the whole operation has completed. /// Rather, it's specifically used as part of the await pattern, and is only usable to determine whether the /// operation has completed by the time the instance is awaited. /// </remarks> public bool IsCompleted => _continuation != null; /// <summary>Same as <see cref="OnCompleted(Action)"/> </summary> public void UnsafeOnCompleted(Action continuation) => OnCompleted(continuation); /// <summary>Queues the provided continuation to be executed once the operation has completed.</summary> public void OnCompleted(Action continuation) { if (_continuation == s_completedSentinel || Interlocked.CompareExchange(ref _continuation, continuation, null) == s_completedSentinel) { Task.Run(continuation); } } /// <summary>Gets the result of the completion operation.</summary> /// <returns>Number of bytes transferred.</returns> /// <remarks> /// Unlike Task's awaiter's GetResult, this does not block until the operation completes: it must only /// be used once the operation has completed. This is handled implicitly by await. /// </remarks> public int GetResult() { _continuation = null; if (SocketError != SocketError.Success) { ThrowIOSocketException(); } return BytesTransferred; } /// <summary>Gets the associated socket.</summary> internal Socket Socket => (Socket)UserToken; // stored in the base's UserToken to avoid an extra field in the object /// <summary>Throws an IOException wrapping a SocketException using the current <see cref="SocketError"/>.</summary> [MethodImpl(MethodImplOptions.NoInlining)] private void ThrowIOSocketException() { var se = new SocketException((int)SocketError); throw new IOException(SR.Format(SR.net_io_readfailure, se.Message), se); } } } }
/* * 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 OpenMetaverse; using OpenMetaverse.Imaging; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; using log4net; using System.Reflection; namespace OpenSim.Region.ClientStack.LindenUDP { /// <summary> /// Stores information about a current texture download and a reference to the texture asset /// </summary> public class J2KImage { private const int IMAGE_PACKET_SIZE = 1000; private const int FIRST_PACKET_SIZE = 600; /// <summary> /// If we've requested an asset but not received it in this ticks timeframe, then allow a duplicate /// request from the client to trigger a fresh asset request. /// </summary> /// <remarks> /// There are 10,000 ticks in a millisecond /// </remarks> private const int ASSET_REQUEST_TIMEOUT = 100000000; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public uint LastSequence; public float Priority; public uint StartPacket; public sbyte DiscardLevel; public UUID TextureID; public IJ2KDecoder J2KDecoder; public IAssetService AssetService; public UUID AgentID; public IInventoryAccessModule InventoryAccessModule; private OpenJPEG.J2KLayerInfo[] m_layers; /// <summary> /// Has this request decoded the asset data? /// </summary> public bool IsDecoded { get; private set; } /// <summary> /// Has this request received the required asset data? /// </summary> public bool HasAsset { get; private set; } /// <summary> /// Time in milliseconds at which the asset was requested. /// </summary> public long AssetRequestTime { get; private set; } public C5.IPriorityQueueHandle<J2KImage> PriorityQueueHandle; private uint m_currentPacket; private bool m_decodeRequested; private bool m_assetRequested; private bool m_sentInfo; private uint m_stopPacket; private byte[] m_asset; private LLImageManager m_imageManager; public J2KImage(LLImageManager imageManager) { m_imageManager = imageManager; } /// <summary> /// Sends packets for this texture to a client until packetsToSend is /// hit or the transfer completes /// </summary> /// <param name="client">Reference to the client that the packets are destined for</param> /// <param name="packetsToSend">Maximum number of packets to send during this call</param> /// <param name="packetsSent">Number of packets sent during this call</param> /// <returns>True if the transfer completes at the current discard level, otherwise false</returns> public bool SendPackets(IClientAPI client, int packetsToSend, out int packetsSent) { packetsSent = 0; if (m_currentPacket <= m_stopPacket) { bool sendMore = true; if (!m_sentInfo || (m_currentPacket == 0)) { sendMore = !SendFirstPacket(client); m_sentInfo = true; ++m_currentPacket; ++packetsSent; } if (m_currentPacket < 2) { m_currentPacket = 2; } while (sendMore && packetsSent < packetsToSend && m_currentPacket <= m_stopPacket) { sendMore = SendPacket(client); ++m_currentPacket; ++packetsSent; } } return (m_currentPacket > m_stopPacket); } /// <summary> /// This is where we decide what we need to update /// and assign the real discardLevel and packetNumber /// assuming of course that the connected client might be bonkers /// </summary> public void RunUpdate() { if (!HasAsset) { if (!m_assetRequested || DateTime.UtcNow.Ticks > AssetRequestTime + ASSET_REQUEST_TIMEOUT) { // m_log.DebugFormat( // "[J2KIMAGE]: Requesting asset {0} from request in packet {1}, already requested? {2}, due to timeout? {3}", // TextureID, LastSequence, m_assetRequested, DateTime.UtcNow.Ticks > AssetRequestTime + ASSET_REQUEST_TIMEOUT); m_assetRequested = true; AssetRequestTime = DateTime.UtcNow.Ticks; AssetService.Get(TextureID.ToString(), this, AssetReceived); } } else { if (!IsDecoded) { //We need to decode the requested image first if (!m_decodeRequested) { //Request decode m_decodeRequested = true; // m_log.DebugFormat("[J2KIMAGE]: Requesting decode of asset {0}", TextureID); // Do we have a jpeg decoder? if (J2KDecoder != null) { if (m_asset == null) { J2KDecodedCallback(TextureID, new OpenJPEG.J2KLayerInfo[0]); } else { // Send it off to the jpeg decoder J2KDecoder.BeginDecode(TextureID, m_asset, J2KDecodedCallback); } } else { J2KDecodedCallback(TextureID, new OpenJPEG.J2KLayerInfo[0]); } } } else { // Check for missing image asset data if (m_asset == null) { m_log.Warn("[J2KIMAGE]: RunUpdate() called with missing asset data (no missing image texture?). Canceling texture transfer"); m_currentPacket = m_stopPacket; return; } if (DiscardLevel >= 0 || m_stopPacket == 0) { // This shouldn't happen, but if it does, we really can't proceed if (m_layers == null) { m_log.Warn("[J2KIMAGE]: RunUpdate() called with missing Layers. Canceling texture transfer"); m_currentPacket = m_stopPacket; return; } int maxDiscardLevel = Math.Max(0, m_layers.Length - 1); // Treat initial texture downloads with a DiscardLevel of -1 a request for the highest DiscardLevel if (DiscardLevel < 0 && m_stopPacket == 0) DiscardLevel = (sbyte)maxDiscardLevel; // Clamp at the highest discard level DiscardLevel = (sbyte)Math.Min(DiscardLevel, maxDiscardLevel); //Calculate the m_stopPacket if (m_layers.Length > 0) { m_stopPacket = (uint)GetPacketForBytePosition(m_layers[(m_layers.Length - 1) - DiscardLevel].End); //I don't know why, but the viewer seems to expect the final packet if the file //is just one packet bigger. if (TexturePacketCount() == m_stopPacket + 1) { m_stopPacket = TexturePacketCount(); } } else { m_stopPacket = TexturePacketCount(); } m_currentPacket = StartPacket; } } } } private bool SendFirstPacket(IClientAPI client) { if (client == null) return false; if (m_asset == null) { m_log.Warn("[J2KIMAGE]: Sending ImageNotInDatabase for texture " + TextureID); client.SendImageNotFound(TextureID); return true; } else if (m_asset.Length <= FIRST_PACKET_SIZE) { // We have less then one packet's worth of data client.SendImageFirstPart(1, TextureID, (uint)m_asset.Length, m_asset, 2); m_stopPacket = 0; return true; } else { // This is going to be a multi-packet texture download byte[] firstImageData = new byte[FIRST_PACKET_SIZE]; try { Buffer.BlockCopy(m_asset, 0, firstImageData, 0, FIRST_PACKET_SIZE); } catch (Exception) { m_log.ErrorFormat("[J2KIMAGE]: Texture block copy for the first packet failed. textureid={0}, assetlength={1}", TextureID, m_asset.Length); return true; } client.SendImageFirstPart(TexturePacketCount(), TextureID, (uint)m_asset.Length, firstImageData, (byte)ImageCodec.J2C); } return false; } private bool SendPacket(IClientAPI client) { if (client == null) return false; bool complete = false; int imagePacketSize = ((int)m_currentPacket == (TexturePacketCount())) ? LastPacketSize() : IMAGE_PACKET_SIZE; try { if ((CurrentBytePosition() + IMAGE_PACKET_SIZE) > m_asset.Length) { imagePacketSize = LastPacketSize(); complete = true; if ((CurrentBytePosition() + imagePacketSize) > m_asset.Length) { imagePacketSize = m_asset.Length - CurrentBytePosition(); complete = true; } } // It's concievable that the client might request packet one // from a one packet image, which is really packet 0, // which would leave us with a negative imagePacketSize.. if (imagePacketSize > 0) { byte[] imageData = new byte[imagePacketSize]; int currentPosition = CurrentBytePosition(); try { Buffer.BlockCopy(m_asset, currentPosition, imageData, 0, imagePacketSize); } catch (Exception e) { m_log.ErrorFormat("[J2KIMAGE]: Texture block copy for the first packet failed. textureid={0}, assetlength={1}, currentposition={2}, imagepacketsize={3}, exception={4}", TextureID, m_asset.Length, currentPosition, imagePacketSize, e.Message); return false; } //Send the packet client.SendImageNextPart((ushort)(m_currentPacket - 1), TextureID, imageData); } return !complete; } catch (Exception) { return false; } } private ushort TexturePacketCount() { if (!IsDecoded) return 0; if (m_asset == null) return 0; if (m_asset.Length <= FIRST_PACKET_SIZE) return 1; return (ushort)(((m_asset.Length - FIRST_PACKET_SIZE + IMAGE_PACKET_SIZE - 1) / IMAGE_PACKET_SIZE) + 1); } private int GetPacketForBytePosition(int bytePosition) { return ((bytePosition - FIRST_PACKET_SIZE + IMAGE_PACKET_SIZE - 1) / IMAGE_PACKET_SIZE) + 1; } private int LastPacketSize() { if (m_currentPacket == 1) return m_asset.Length; int lastsize = (m_asset.Length - FIRST_PACKET_SIZE) % IMAGE_PACKET_SIZE; //If the last packet size is zero, it's really cImagePacketSize, it sits on the boundary if (lastsize == 0) { lastsize = IMAGE_PACKET_SIZE; } return lastsize; } private int CurrentBytePosition() { if (m_currentPacket == 0) return 0; if (m_currentPacket == 1) return FIRST_PACKET_SIZE; int result = FIRST_PACKET_SIZE + ((int)m_currentPacket - 2) * IMAGE_PACKET_SIZE; if (result < 0) result = FIRST_PACKET_SIZE; return result; } private void J2KDecodedCallback(UUID AssetId, OpenJPEG.J2KLayerInfo[] layers) { m_layers = layers; IsDecoded = true; RunUpdate(); } private void AssetDataCallback(UUID AssetID, AssetBase asset) { HasAsset = true; if (asset == null || asset.Data == null) { if (m_imageManager.MissingImage != null) { m_asset = m_imageManager.MissingImage.Data; } else { m_asset = null; IsDecoded = true; } } else { m_asset = asset.Data; } RunUpdate(); } private void AssetReceived(string id, Object sender, AssetBase asset) { // m_log.DebugFormat( // "[J2KIMAGE]: Received asset {0} ({1} bytes)", id, asset != null ? asset.Data.Length.ToString() : "n/a"); UUID assetID = UUID.Zero; if (asset != null) { assetID = asset.FullID; } else if ((InventoryAccessModule != null) && (sender != InventoryAccessModule)) { // Unfortunately we need this here, there's no other way. // This is due to the fact that textures opened directly from the agent's inventory // don't have any distinguishing feature. As such, in order to serve those when the // foreign user is visiting, we need to try again after the first fail to the local // asset service. string assetServerURL = string.Empty; if (InventoryAccessModule.IsForeignUser(AgentID, out assetServerURL) && !string.IsNullOrEmpty(assetServerURL)) { if (!assetServerURL.EndsWith("/") && !assetServerURL.EndsWith("=")) assetServerURL = assetServerURL + "/"; // m_log.DebugFormat("[J2KIMAGE]: texture {0} not found in local asset storage. Trying user's storage.", assetServerURL + id); AssetService.Get(assetServerURL + id, InventoryAccessModule, AssetReceived); return; } } AssetDataCallback(assetID, asset); } } }
using System; using System.Collections.Generic; using UnityEngine.UI; namespace UnityEngine.EventSystems { public static class ExecuteEvents { public delegate void EventFunction<T1>(T1 handler, BaseEventData eventData); public static T ValidateEventData<T>(BaseEventData data) where T: class { if ((data as T) == null) throw new ArgumentException(String.Format("Invalid type: {0} passed to event expecting {1}", data.GetType(), typeof(T))); return data as T; } #region Execution Handlers private static readonly EventFunction<IPointerEnterHandler> s_PointerEnterHandler = Execute; private static void Execute(IPointerEnterHandler handler, BaseEventData eventData) { handler.OnPointerEnter(ValidateEventData<PointerEventData>(eventData)); } private static readonly EventFunction<IPointerExitHandler> s_PointerExitHandler = Execute; private static void Execute(IPointerExitHandler handler, BaseEventData eventData) { handler.OnPointerExit(ValidateEventData<PointerEventData>(eventData)); } private static readonly EventFunction<IPointerDownHandler> s_PointerDownHandler = Execute; private static void Execute(IPointerDownHandler handler, BaseEventData eventData) { handler.OnPointerDown(ValidateEventData<PointerEventData>(eventData)); } private static readonly EventFunction<IPointerUpHandler> s_PointerUpHandler = Execute; private static void Execute(IPointerUpHandler handler, BaseEventData eventData) { handler.OnPointerUp(ValidateEventData<PointerEventData>(eventData)); } private static readonly EventFunction<IPointerClickHandler> s_PointerClickHandler = Execute; private static void Execute(IPointerClickHandler handler, BaseEventData eventData) { handler.OnPointerClick(ValidateEventData<PointerEventData>(eventData)); } private static readonly EventFunction<IInitializePotentialDragHandler> s_InitializePotentialDragHandler = Execute; private static void Execute(IInitializePotentialDragHandler handler, BaseEventData eventData) { handler.OnInitializePotentialDrag(ValidateEventData<PointerEventData>(eventData)); } private static readonly EventFunction<IBeginDragHandler> s_BeginDragHandler = Execute; private static void Execute(IBeginDragHandler handler, BaseEventData eventData) { handler.OnBeginDrag(ValidateEventData<PointerEventData>(eventData)); } private static readonly EventFunction<IDragHandler> s_DragHandler = Execute; private static void Execute(IDragHandler handler, BaseEventData eventData) { handler.OnDrag(ValidateEventData<PointerEventData>(eventData)); } private static readonly EventFunction<IEndDragHandler> s_EndDragHandler = Execute; private static void Execute(IEndDragHandler handler, BaseEventData eventData) { handler.OnEndDrag(ValidateEventData<PointerEventData>(eventData)); } private static readonly EventFunction<IDropHandler> s_DropHandler = Execute; private static void Execute(IDropHandler handler, BaseEventData eventData) { handler.OnDrop(ValidateEventData<PointerEventData>(eventData)); } private static readonly EventFunction<IScrollHandler> s_ScrollHandler = Execute; private static void Execute(IScrollHandler handler, BaseEventData eventData) { handler.OnScroll(ValidateEventData<PointerEventData>(eventData)); } private static readonly EventFunction<IUpdateSelectedHandler> s_UpdateSelectedHandler = Execute; private static void Execute(IUpdateSelectedHandler handler, BaseEventData eventData) { handler.OnUpdateSelected(eventData); } private static readonly EventFunction<ISelectHandler> s_SelectHandler = Execute; private static void Execute(ISelectHandler handler, BaseEventData eventData) { handler.OnSelect(eventData); } private static readonly EventFunction<IDeselectHandler> s_DeselectHandler = Execute; private static void Execute(IDeselectHandler handler, BaseEventData eventData) { handler.OnDeselect(eventData); } private static readonly EventFunction<IMoveHandler> s_MoveHandler = Execute; private static void Execute(IMoveHandler handler, BaseEventData eventData) { handler.OnMove(ValidateEventData<AxisEventData>(eventData)); } private static readonly EventFunction<ISubmitHandler> s_SubmitHandler = Execute; private static void Execute(ISubmitHandler handler, BaseEventData eventData) { handler.OnSubmit(eventData); } private static readonly EventFunction<ICancelHandler> s_CancelHandler = Execute; private static void Execute(ICancelHandler handler, BaseEventData eventData) { handler.OnCancel(eventData); } #endregion #region Execution Accessors public static EventFunction<IPointerEnterHandler> pointerEnterHandler { get { return s_PointerEnterHandler; } } public static EventFunction<IPointerExitHandler> pointerExitHandler { get { return s_PointerExitHandler; } } public static EventFunction<IPointerDownHandler> pointerDownHandler { get { return s_PointerDownHandler; } } public static EventFunction<IPointerUpHandler> pointerUpHandler { get { return s_PointerUpHandler; } } public static EventFunction<IPointerClickHandler> pointerClickHandler { get { return s_PointerClickHandler; } } public static EventFunction<IInitializePotentialDragHandler> initializePotentialDrag { get { return s_InitializePotentialDragHandler; } } public static EventFunction<IBeginDragHandler> beginDragHandler { get { return s_BeginDragHandler; } } public static EventFunction<IDragHandler> dragHandler { get { return s_DragHandler; } } public static EventFunction<IEndDragHandler> endDragHandler { get { return s_EndDragHandler; } } public static EventFunction<IDropHandler> dropHandler { get { return s_DropHandler; } } public static EventFunction<IScrollHandler> scrollHandler { get { return s_ScrollHandler; } } public static EventFunction<IUpdateSelectedHandler> updateSelectedHandler { get { return s_UpdateSelectedHandler; } } public static EventFunction<ISelectHandler> selectHandler { get { return s_SelectHandler; } } public static EventFunction<IDeselectHandler> deselectHandler { get { return s_DeselectHandler; } } public static EventFunction<IMoveHandler> moveHandler { get { return s_MoveHandler; } } public static EventFunction<ISubmitHandler> submitHandler { get { return s_SubmitHandler; } } public static EventFunction<ICancelHandler> cancelHandler { get { return s_CancelHandler; } } #endregion private static void GetEventChain(GameObject root, IList<Transform> eventChain) { eventChain.Clear(); if (root == null) return; var t = root.transform; while (t != null) { eventChain.Add(t); t = t.parent; } } private static readonly ObjectPool<List<IEventSystemHandler>> s_HandlerListPool = new ObjectPool<List<IEventSystemHandler>>(null, l => l.Clear()); public static bool Execute<T>(GameObject target, BaseEventData eventData, EventFunction<T> functor) where T: IEventSystemHandler { var internalHandlers = s_HandlerListPool.Get(); GetEventList<T>(target, internalHandlers); // if (s_InternalHandlers.Count > 0) // Debug.Log("Executinng " + typeof (T) + " on " + target); for (var i = 0; i < internalHandlers.Count; i++) { T arg; try { arg = (T)internalHandlers[i]; } catch (Exception e) { var temp = internalHandlers[i]; Debug.LogException(new Exception(string.Format("Type {0} expected {1} received.", typeof(T).Name, temp.GetType().Name), e)); continue; } try { functor(arg, eventData); } catch (Exception e) { Debug.LogException(e); } } var handlerCount = internalHandlers.Count; s_HandlerListPool.Release(internalHandlers); return handlerCount > 0; } /// <summary> /// Execute the specified event on the first game object underneath the current touch. /// </summary> private static readonly List<Transform> s_InternalTransformList = new List<Transform>(30); public static GameObject ExecuteHierarchy<T>(GameObject root, BaseEventData eventData, EventFunction<T> callbackFunction) where T: IEventSystemHandler { GetEventChain(root, s_InternalTransformList); for (var i = 0; i < s_InternalTransformList.Count; i++) { var transform = s_InternalTransformList[i]; if (Execute(transform.gameObject, eventData, callbackFunction)) return transform.gameObject; } return null; } private static bool ShouldSendToComponent<T>(Component component) where T: IEventSystemHandler { var valid = component is T; if (!valid) return false; var behaviour = component as Behaviour; if (behaviour != null) return behaviour.enabled && behaviour.isActiveAndEnabled; return true; } /// <summary> /// Get the specified object's event event. /// </summary> private static void GetEventList<T>(GameObject go, IList<IEventSystemHandler> results) where T: IEventSystemHandler { // Debug.LogWarning("GetEventList<" + typeof(T).Name + ">"); if (results == null) throw new ArgumentException("Results array is null", "results"); if (go == null || !go.activeInHierarchy) return; var components = ComponentListPool.Get(); go.GetComponents(components); for (var i = 0; i < components.Count; i++) { if (!ShouldSendToComponent<T>(components[i])) continue; // Debug.Log(string.Format("{2} found! On {0}.{1}", go, s_GetComponentsScratch[i].GetType(), typeof(T))); results.Add(components[i] as IEventSystemHandler); } ComponentListPool.Release(components); // Debug.LogWarning("end GetEventList<" + typeof(T).Name + ">"); } /// <summary> /// Whether the specified game object will be able to handle the specified event. /// </summary> public static bool CanHandleEvent<T>(GameObject go) where T: IEventSystemHandler { var internalHandlers = s_HandlerListPool.Get(); GetEventList<T>(go, internalHandlers); var handlerCount = internalHandlers.Count; s_HandlerListPool.Release(internalHandlers); return handlerCount != 0; } /// <summary> /// Bubble the specified event on the game object, figuring out which object will actually receive the event. /// </summary> public static GameObject GetEventHandler<T>(GameObject root) where T: IEventSystemHandler { if (root == null) return null; Transform t = root.transform; while (t != null) { if (CanHandleEvent<T>(t.gameObject)) return t.gameObject; t = t.parent; } return null; } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Common.Strategies; using Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Commands.Compute.Properties; using Microsoft.Azure.Commands.Compute.Strategies; using Microsoft.Azure.Commands.Compute.Strategies.ComputeRp; using Microsoft.Azure.Commands.Compute.Strategies.Network; using Microsoft.Azure.Commands.Compute.Strategies.ResourceManager; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.Compute.Models; using Microsoft.Azure.Management.Internal.Network.Version2017_10_01.Models; using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Net; using System.Threading; using System.Threading.Tasks; namespace Microsoft.Azure.Commands.Compute.Automation { public partial class NewAzureRmVmss : ComputeAutomationBaseCmdlet { // SimpleParameterSet [Parameter(ParameterSetName = SimpleParameterSet, Mandatory = false)] [PSArgumentCompleter( "CentOS", "CoreOS", "Debian", "openSUSE-Leap", "RHEL", "SLES", "UbuntuLTS", "Win2016Datacenter", "Win2012R2Datacenter", "Win2012Datacenter", "Win2008R2SP1", "Win10")] public string ImageName { get; set; } = "Win2016Datacenter"; [Parameter(ParameterSetName = SimpleParameterSet, Mandatory = true)] public PSCredential Credential { get; set; } [Parameter(ParameterSetName = SimpleParameterSet, Mandatory = false)] public int InstanceCount { get; set; } = 2; [Parameter(ParameterSetName = SimpleParameterSet, Mandatory = false)] public string VirtualNetworkName { get; set; } [Parameter(ParameterSetName = SimpleParameterSet, Mandatory = false)] public string SubnetName { get; set; } [Parameter(ParameterSetName = SimpleParameterSet, Mandatory = false)] public string PublicIpAddressName { get; set; } [Parameter(ParameterSetName = SimpleParameterSet, Mandatory = false)] public string DomainNameLabel { get; set; } [Parameter(ParameterSetName = SimpleParameterSet, Mandatory = false)] public string SecurityGroupName { get; set; } [Parameter(ParameterSetName = SimpleParameterSet, Mandatory = false)] public string LoadBalancerName { get; set; } [Parameter(ParameterSetName = SimpleParameterSet, Mandatory = false)] public int[] BackendPort { get; set; } = new[] { 80 }; [Parameter(ParameterSetName = SimpleParameterSet, Mandatory = false)] [LocationCompleter("Microsoft.Compute/virtualMachineScaleSets")] public string Location { get; set; } // this corresponds to VmSku in the Azure CLI [Parameter(ParameterSetName = SimpleParameterSet, Mandatory = false)] public string VmSize { get; set; } = "Standard_DS1_v2"; [Parameter(ParameterSetName = SimpleParameterSet, Mandatory = false)] public UpgradeMode UpgradePolicyMode { get; set; } [Parameter(ParameterSetName = SimpleParameterSet, Mandatory = false)] [ValidateSet("Static", "Dynamic")] public string AllocationMethod { get; set; } = "Static"; [Parameter(ParameterSetName = SimpleParameterSet, Mandatory = false)] public string VnetAddressPrefix { get; set; } = "192.168.0.0/16"; [Parameter(ParameterSetName = SimpleParameterSet, Mandatory = false)] public string SubnetAddressPrefix { get; set; } = "192.168.1.0/24"; [Parameter(ParameterSetName = SimpleParameterSet, Mandatory = false)] public string FrontendPoolName { get; set; } [Parameter(ParameterSetName = SimpleParameterSet, Mandatory = false)] public string BackendPoolName { get; set; } [Parameter(ParameterSetName = SimpleParameterSet, Mandatory = false, HelpMessage = "Use this to add system assigned identity (MSI) to the vm")] public SwitchParameter SystemAssignedIdentity { get; set; } [Parameter(ParameterSetName = SimpleParameterSet, Mandatory = false, HelpMessage = "Use this to add the assign user specified identity (MSI) to the VM")] [ValidateNotNullOrEmpty] public string UserAssignedIdentity { get; set; } [Parameter( ParameterSetName = SimpleParameterSet, Mandatory = false, HelpMessage = "A list of availability zones denoting the IP allocated for the resource needs to come from.", ValueFromPipelineByPropertyName = true)] public List<string> Zone { get; set; } [Parameter(ParameterSetName = SimpleParameterSet, Mandatory = false)] public int[] NatBackendPort { get; set; } [Parameter(ParameterSetName = SimpleParameterSet, Mandatory = false)] public int[] DataDiskSizeInGb { get; set; } [Parameter(ParameterSetName = SimpleParameterSet, Mandatory = false, HelpMessage ="Use this to create the Scale set in a single placement group, default is multiple groups")] public SwitchParameter SinglePlacementGroup; const int FirstPortRangeStart = 50000; sealed class Parameters : IParameters<VirtualMachineScaleSet> { NewAzureRmVmss _cmdlet { get; } Client _client { get; } public Parameters(NewAzureRmVmss cmdlet, Client client) { _cmdlet = cmdlet; _client = client; } public string Location { get { return _cmdlet.Location; } set { _cmdlet.Location = value; } } public ImageAndOsType ImageAndOsType { get; set; } public string DefaultLocation => "eastus"; public async Task<ResourceConfig<VirtualMachineScaleSet>> CreateConfigAsync() { ImageAndOsType = await _client.UpdateImageAndOsTypeAsync( ImageAndOsType, _cmdlet.ResourceGroupName, _cmdlet.ImageName, Location); // generate a domain name label if it's not specified. _cmdlet.DomainNameLabel = await PublicIPAddressStrategy.UpdateDomainNameLabelAsync( domainNameLabel: _cmdlet.DomainNameLabel, name: _cmdlet.VMScaleSetName, location: Location, client: _client); var resourceGroup = ResourceGroupStrategy.CreateResourceGroupConfig(_cmdlet.ResourceGroupName); var noZones = _cmdlet.Zone == null || _cmdlet.Zone.Count == 0; var publicIpAddress = resourceGroup.CreatePublicIPAddressConfig( name: _cmdlet.PublicIpAddressName, domainNameLabel: _cmdlet.DomainNameLabel, allocationMethod: _cmdlet.AllocationMethod, //sku.Basic is not compatible with multiple placement groups sku: (noZones && _cmdlet.SinglePlacementGroup.IsPresent) ? PublicIPAddressStrategy.Sku.Basic : PublicIPAddressStrategy.Sku.Standard, zones: null); var virtualNetwork = resourceGroup.CreateVirtualNetworkConfig( name: _cmdlet.VirtualNetworkName, addressPrefix: _cmdlet.VnetAddressPrefix); var subnet = virtualNetwork.CreateSubnet( _cmdlet.SubnetName, _cmdlet.SubnetAddressPrefix); var loadBalancer = resourceGroup.CreateLoadBalancerConfig( name: _cmdlet.LoadBalancerName, //sku.Basic is not compatible with multiple placement groups sku: (noZones && _cmdlet.SinglePlacementGroup.IsPresent) ? LoadBalancerStrategy.Sku.Basic : LoadBalancerStrategy.Sku.Standard); var frontendIpConfiguration = loadBalancer.CreateFrontendIPConfiguration( name: _cmdlet.FrontendPoolName, publicIpAddress: publicIpAddress); var backendAddressPool = loadBalancer.CreateBackendAddressPool( name: _cmdlet.BackendPoolName); if (_cmdlet.BackendPort != null) { var loadBalancingRuleName = _cmdlet.LoadBalancerName; foreach (var backendPort in _cmdlet.BackendPort) { loadBalancer.CreateLoadBalancingRule( name: loadBalancingRuleName + backendPort.ToString(), fronendIpConfiguration: frontendIpConfiguration, backendAddressPool: backendAddressPool, frontendPort: backendPort, backendPort: backendPort); } } _cmdlet.NatBackendPort = ImageAndOsType.UpdatePorts(_cmdlet.NatBackendPort); var inboundNatPoolName = _cmdlet.VMScaleSetName; var PortRangeSize = _cmdlet.InstanceCount * 2; var ports = _cmdlet .NatBackendPort ?.Select((port, i) => Tuple.Create( port, FirstPortRangeStart + i * 2000)) .ToList(); var inboundNatPools = ports ?.Select(p => loadBalancer.CreateInboundNatPool( name: inboundNatPoolName + p.Item1.ToString(), frontendIpConfiguration: frontendIpConfiguration, frontendPortRangeStart: p.Item2, frontendPortRangeEnd: p.Item2 + PortRangeSize, backendPort: p.Item1)) .ToList(); var networkSecurityGroup = noZones ? null : resourceGroup.CreateNetworkSecurityGroupConfig( _cmdlet.VMScaleSetName, _cmdlet.NatBackendPort.Concat(_cmdlet.BackendPort).ToList()); return resourceGroup.CreateVirtualMachineScaleSetConfig( name: _cmdlet.VMScaleSetName, subnet: subnet, backendAdressPool: backendAddressPool, inboundNatPools: inboundNatPools, networkSecurityGroup: networkSecurityGroup, imageAndOsType: ImageAndOsType, adminUsername: _cmdlet.Credential.UserName, adminPassword: new NetworkCredential(string.Empty, _cmdlet.Credential.Password).Password, vmSize: _cmdlet.VmSize, instanceCount: _cmdlet.InstanceCount, upgradeMode: _cmdlet.MyInvocation.BoundParameters.ContainsKey(nameof(UpgradePolicyMode)) ? _cmdlet.UpgradePolicyMode : (UpgradeMode?)null, dataDisks: _cmdlet.DataDiskSizeInGb, zones: _cmdlet.Zone, identity: _cmdlet.GetVmssIdentityFromArgs(), singlePlacementGroup : _cmdlet.SinglePlacementGroup.IsPresent); } } async Task SimpleParameterSetExecuteCmdlet(IAsyncCmdlet asyncCmdlet) { bool loadBalancerNamePassedIn = !String.IsNullOrWhiteSpace(LoadBalancerName); ResourceGroupName = ResourceGroupName ?? VMScaleSetName; VirtualNetworkName = VirtualNetworkName ?? VMScaleSetName; SubnetName = SubnetName ?? VMScaleSetName; PublicIpAddressName = PublicIpAddressName ?? VMScaleSetName; SecurityGroupName = SecurityGroupName ?? VMScaleSetName; LoadBalancerName = LoadBalancerName ?? VMScaleSetName; FrontendPoolName = FrontendPoolName ?? VMScaleSetName; BackendPoolName = BackendPoolName ?? VMScaleSetName; var client = new Client(DefaultProfile.DefaultContext); var parameters = new Parameters(this, client); // If the user did not specify a load balancer name, mark the LB setting to ignore // preexisting check. The most common scenario is users will let the cmdlet create and name the LB for them with the default // config. We do not want to block that scenario in case the cmdlet failed mid operation and tthe user kicks it off again. if (!loadBalancerNamePassedIn) { LoadBalancerStrategy.IgnorePreExistingConfigCheck = true; } else { LoadBalancerStrategy.IgnorePreExistingConfigCheck = false; } var result = await client.RunAsync(client.SubscriptionId, parameters, asyncCmdlet); if (result != null) { var fqdn = PublicIPAddressStrategy.Fqdn(DomainNameLabel, Location); var psObject = new PSVirtualMachineScaleSet(); ComputeAutomationAutoMapperProfile.Mapper.Map(result, psObject); psObject.FullyQualifiedDomainName = fqdn; var port = "<port>"; var connectionString = parameters.ImageAndOsType.GetConnectionString( fqdn, Credential.UserName, port); var range = FirstPortRangeStart.ToString() + ".." + (FirstPortRangeStart + InstanceCount * 2 - 1).ToString(); asyncCmdlet.WriteVerbose( Resources.VmssUseConnectionString, connectionString); asyncCmdlet.WriteVerbose( Resources.VmssPortRange, port, range); asyncCmdlet.WriteObject(psObject); } } /// <summary> /// Heres whats happening here : /// If "SystemAssignedIdentity" and "UserAssignedIdentity" are both present we set the type of identity to be SystemAssignedUsrAssigned and set the user /// defined identity in the VMSS identity object. /// If only "SystemAssignedIdentity" is present, we just set the type of the Identity to "SystemAssigned" and no identity ids are set as its created by Azure /// If only "UserAssignedIdentity" is present, we set the type of the Identity to be "UserAssigned" and set the Identity in the VMSS identity object. /// If neither is present, we return a null. /// </summary> /// <returns>Returning the Identity generated form the cmdlet parameters "SystemAssignedIdentity" and "UserAssignedIdentity"</returns> private VirtualMachineScaleSetIdentity GetVmssIdentityFromArgs() { var isUserAssignedEnabled = !string.IsNullOrWhiteSpace(UserAssignedIdentity); return (SystemAssignedIdentity.IsPresent || isUserAssignedEnabled) ? new VirtualMachineScaleSetIdentity { Type = !isUserAssignedEnabled ? ResourceIdentityType.SystemAssigned : (SystemAssignedIdentity.IsPresent ? ResourceIdentityType.SystemAssignedUserAssigned : ResourceIdentityType.UserAssigned), UserAssignedIdentities = isUserAssignedEnabled ? new Dictionary<string, VirtualMachineScaleSetIdentityUserAssignedIdentitiesValue>() { { UserAssignedIdentity, new VirtualMachineScaleSetIdentityUserAssignedIdentitiesValue()} } : null, } : null; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Text; using System.Xml; namespace NUnit.Gui { public class Xml2RtfConverter { public enum ColorKinds { Element = 1, Value, Attribute, String, Tag, Comment, CData } private Dictionary<ColorKinds, Color> _colorTable = new Dictionary<ColorKinds, Color>(); private readonly int indentationSize; public Xml2RtfConverter(int indentationSize, Dictionary<ColorKinds, Color> colorTable = null ) { this.indentationSize = indentationSize; if (colorTable != null) _colorTable = colorTable; else { _colorTable.Add(ColorKinds.Element, Color.Purple); _colorTable.Add(ColorKinds.Value, Color.Black); _colorTable.Add(ColorKinds.Attribute, Color.DarkGoldenrod); _colorTable.Add(ColorKinds.String, Color.DarkBlue); _colorTable.Add(ColorKinds.Tag, Color.Purple); _colorTable.Add(ColorKinds.Comment, Color.Gray); _colorTable.Add(ColorKinds.CData, Color.DarkBlue); } } public string Convert(XmlNode node) { var sb = new StringBuilder(); CreateHeader(sb); AddXmlNode(sb, node, 0); return sb.ToString(); } private void AddXmlNode(StringBuilder sb, XmlNode node, int indentationLevel) { var element = node as XmlElement; if (element != null) { AddXmlElement(sb, element, indentationLevel); return; } var xmlText = node as XmlText; if (xmlText != null) { AddXmlText(sb, indentationLevel, xmlText); return; } var xmlComment = node as XmlComment; if (xmlComment != null) { AddXmlComment(sb, indentationLevel, xmlComment); return; } var cdata = node as XmlCDataSection; if (cdata != null) { AddXmlCDataSection(sb, cdata); return; } } private static void AddXmlCDataSection(StringBuilder sb, XmlCDataSection cdata) { sb.Append(string.Format(@"\cf{0}<![CDATA[\par ", (int)ColorKinds.CData)); var cdataLines = cdata.Value.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); var res = new List<string>(cdataLines.Length); foreach (var cdataLine in cdataLines) { res.Add(XmlEncode(cdataLine)); } sb.Append(string.Join(@"\par", res.ToArray())); sb.Append(@"\par]]>\par"); } private void AddXmlComment(StringBuilder sb, int indentationLevel, XmlComment xmlComment) { Indent(sb, indentationLevel); sb.Append(string.Format(@"\cf{0}<!--{1}-->\par", (int)ColorKinds.Comment, XmlEncode(xmlComment.Value))); } private void AddXmlText(StringBuilder sb, int indentationLevel, XmlText xmlText) { Indent(sb, indentationLevel); sb.Append(string.Format(@"\cf{0}{1}\par", (int)ColorKinds.Value, XmlEncode(xmlText.Value))); } private void AddXmlElement(StringBuilder sb, XmlElement element, int indentationLevel) { Indent(sb, indentationLevel); if (AddStartElement(sb, element)) return; AddElementContent(sb, element, indentationLevel); AddEndElement(sb, element); } private bool AddStartElement(StringBuilder sb, XmlElement element) { sb.Append(string.Format(@"\cf{0}<\cf{1}{2}", (int)ColorKinds.Tag, (int)ColorKinds.Element, element.Name)); AddXmlAttributes(sb, element); //If Element has no content we can end the element now. if (!element.HasChildNodes) { sb.Append(string.Format(@" \cf{0}/>\par", (int)ColorKinds.Tag)); return true; } //otherwise just end the start fo the element. sb.Append(string.Format(@"\cf{0}>", (int)ColorKinds.Tag)); return false; } private static void AddXmlAttributes(StringBuilder sb, XmlElement element) { if (element.HasAttributes) { foreach (XmlAttribute attribute in element.Attributes) { sb.Append(string.Format(@" \cf{0}{1}=\cf{2}'{3}'", (int)ColorKinds.Attribute, attribute.Name, (int)ColorKinds.String, XmlEncode(attribute.Value))); } } } private void AddElementContent(StringBuilder sb, XmlElement element, int indentationLevel) { if (HasSingleTextNode(element)) { sb.Append(string.Format(@"\cf{0}{1}", (int)ColorKinds.Value, XmlEncode(element.FirstChild.Value))); } else if (element.HasChildNodes) { sb.Append(@"\par"); foreach (XmlNode childNode in element.ChildNodes) { AddXmlNode(sb, childNode, indentationLevel + 1); } Indent(sb, indentationLevel); } } private static void AddEndElement(StringBuilder sb, XmlElement element) { sb.Append(string.Format(@"\cf{0}</\cf{1}{2}\cf{0}>\par", (int)ColorKinds.Tag, (int)ColorKinds.Element, element.Name)); } private void Indent(StringBuilder sb, int indentationLevel) { sb.Append(new string(' ', indentationSize * indentationLevel)); } private bool HasSingleTextNode(XmlElement element) { return (element.ChildNodes.Count == 1) && (element.FirstChild is XmlText); } private static string XmlEncode(string value) { var sb = new StringBuilder(); foreach (char c in value) { switch (c) { //xml case '\'': sb.Append(@"&apos;"); break; case '"': sb.Append("&quot;"); break; case '&': sb.Append(@"&amp;"); break; case '<': sb.Append(@"&lt;"); break; case '>': sb.Append(@"&gt;"); break; //these are for rtf-support case '\\': sb.Append(@"\\"); break; case '{': sb.Append(@"\{"); break; case '}': sb.Append(@"\}"); break; default: sb.Append(c); break; } } return sb.ToString(); } private void CreateHeader(StringBuilder sb) { sb.AppendLine(@"{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Courier New;}}"); sb.Append(@"{{\colortbl ;"); foreach (ColorKinds colorKind in Enum.GetValues(typeof(ColorKinds))) { Color color; if (_colorTable.TryGetValue(colorKind, out color)) sb.Append(string.Format(@"\red{0}\green{1}\blue{2};", color.R, color.G, color.B)); else sb.Append(string.Format(@"\red{0}\green{1}\blue{2};", 0, 0, 0)); } sb.AppendLine("}}"); sb.AppendLine(@"\viewkind4\uc1\pard\f0\fs20"); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using HUX.Utility; using HoloToolkit.Unity.SpatialMapping; #if UNITY_WSA using UnityEngine.VR.WSA; #endif #if UNITY_WSA && !UNITY_EDITOR using System.Threading; using System.Threading.Tasks; #endif #if UNITY_EDITOR using UnityEditor; #endif namespace HUX.Spatial { /// <summary> /// SurfaceMeshesToPlanes will find and create planes based on the meshes returned by the SpatialMappingManager's Observer. /// </summary> public class SurfacePlaneManager : HoloToolkit.Unity.Singleton<SurfacePlaneManager> { #region Editor Variables [Header("Plane Generation")] /// <summary> /// Minimum area required for a plane to be created. /// </summary> [SerializeField, Tooltip("Minimum area required for a plane to be created.")] private float m_MinArea = 0.025f; /// <summary> /// Threshold for acceptable normals (the closer to 1, the stricter the standard). Used when determining plane type. /// </summary> [SerializeField, Range(0.0f, 1.0f), Tooltip("Threshold for acceptable normals (the closer to 1, the stricter the standard). Used when determining plane type.")] private float m_UpNormalThreshold = 0.9f; /// <summary> /// The thickness to create the planes at. /// </summary> [SerializeField, Range(0.0f, 1.0f), Tooltip("Thickness to make each plane.")] private float m_PlaneThickness = 0.01f; /// <summary> /// Buffer to use when determining if a horizontal plane near the floor should be considered part of the floor. /// </summary> [SerializeField, Range(0.0f, 1.0f), Tooltip("Buffer to use when determining if a horizontal plane near the floor should be considered part of the floor.")] private float m_FloorBuffer = 0.1f; /// <summary> /// Buffer to use when determining if a horizontal plane near the ceiling should be considered part of the ceiling. /// </summary> [SerializeField, Range(0.0f, 1.0f), Tooltip("Buffer to use when determining if a horizontal plane near the ceiling should be considered part of the ceiling.")] private float m_CeilingBuffer = 0.1f; /// <summary> /// The maximum percentage different a plane can have before it will no longer be considered as possibly the same plane. /// </summary> [SerializeField, Range(0.0f, 1.0f), Tooltip("The maximum percentage different a surface can have before it will no longer be considered as possibly the same plane.")] private float m_MaxAreaDiffPercent = 0.2f; /// <summary> /// The maximum distance a plane can be from another surface before it will no longer be considered as possibly the same plane. /// </summary> [SerializeField, Tooltip("The maximum distance a plane can be from another surface before it will no longer be considered as possibly the same plane.")] private float m_MaxDistChange = 0.15f; /// <summary> /// Determines which plane types should be discarded. /// Use this when the spatial mapping mesh is a better fit for the surface (ex: round tables). /// </summary> [SerializeField, HideInInspector] private PlaneTypes m_DestroyPlanesMask = PlaneTypes.Unknown; [Header("Plane Rendering")] /// <summary> /// Toggle for turn the drawing of the planes on and off. /// </summary> [SerializeField] private bool m_ShowPlanes = true; /// <summary> /// Determines which plane types should be rendered. /// </summary> [SerializeField, HideInInspector] private PlaneTypes m_DrawPlanesMask = (PlaneTypes.Wall | PlaneTypes.Floor | PlaneTypes.Ceiling | PlaneTypes.Table); /// <summary> /// The Material to use for Wall Planes. /// </summary> [SerializeField] private Material m_WallMaterial; /// <summary> /// The Material to use for Floor planes. /// </summary> [SerializeField] private Material m_FloorMaterial; /// <summary> /// The Material to use for Ceiling planes. /// </summary> [SerializeField] private Material m_CeilingMaterial; /// <summary> /// The Material to use for Table planes. /// </summary> [SerializeField] private Material m_TableMaterial; #endregion //----------------------------------------------------------------------------------------------- #region Event Handlers /// <summary> /// Delegate which is called when the MakePlanesCompleted event is triggered. /// </summary> /// <param name="source"></param> /// <param name="args"></param> public delegate void EventHandler(object source, EventArgs args); /// <summary> /// EventHandler which is triggered when the MakePlanesRoutine is finished. /// </summary> public event EventHandler MakePlanesComplete; #endregion //----------------------------------------------------------------------------------------------- #region Private Variables /// <summary> /// All of the currently active planes. /// </summary> private List<SurfacePlane> m_ActivePlanes = new List<SurfacePlane>(); /// <summary> /// Searchable tree of the current wall planes. /// </summary> private BoundedPlaneKDTree<SurfacePlane> m_WallPlanes = new BoundedPlaneKDTree<SurfacePlane>(); /// <summary> /// Searchable tree of the current floor planes. /// </summary> private BoundedPlaneKDTree<SurfacePlane> m_FloorPlanes = new BoundedPlaneKDTree<SurfacePlane>(); /// <summary> /// Searchable tree of the current table planes. /// </summary> private BoundedPlaneKDTree<SurfacePlane> m_TablePlanes = new BoundedPlaneKDTree<SurfacePlane>(); /// <summary> /// Searchable tree of the current ceiling planes. /// </summary> private BoundedPlaneKDTree<SurfacePlane> m_CeilingPlanes = new BoundedPlaneKDTree<SurfacePlane>(); /// <summary> /// Empty game object used to contain all planes created by the SurfaceToPlanes class. /// </summary> private GameObject planesParent; /// <summary> /// Used to align planes with gravity so that they appear more level. /// </summary> private float snapToGravityThreshold = 5.0f; /// <summary> /// The current plane id to assign to the next created plane. /// </summary> private int m_PlaneId = 1; private SpatialMappingObserver m_MappingObserver = null; #if UNITY_EDITOR /// <summary> /// How much time (in sec), while running in the Unity Editor, to allow RemoveSurfaceVertices to consume before returning control to the main program. /// </summary> private static readonly float FrameTime = .016f; #else /// <summary> /// How much time (in sec) to allow RemoveSurfaceVertices to consume before returning control to the main program. /// </summary> private static readonly float FrameTime = .008f; #endif #endregion //----------------------------------------------------------------------------------------------- #region Accessors /// <summary> /// Floor y value, which corresponds to the maximum horizontal area found below the user's head position. /// This value is reset by SurfaceMeshesToPlanes when the max floor plane has been found. /// </summary> public float FloorYPosition { get; private set; } /// <summary> /// Ceiling y value, which corresponds to the maximum horizontal area found above the user's head position. /// This value is reset by SurfaceMeshesToPlanes when the max ceiling plane has been found. /// </summary> public float CeilingYPosition { get; private set; } /// <summary> /// The minimum threshold for being considered pointing up. /// </summary> public float UpNormalThreshold { get { return m_UpNormalThreshold; } } /// <summary> /// If true the planes set to draw will be shown, otherwise no plane will be shown. /// </summary> public bool ShowPlanes { get { return m_ShowPlanes; } set { m_ShowPlanes = value; foreach (SurfacePlane plane in m_ActivePlanes) { SetPlaneVisibility(plane); } } } /// <summary> /// Indicates if SurfaceToPlanes is currently creating planes based on the Spatial Mapping Mesh. /// </summary> public bool MakingPlanes { get; set; } #endregion //----------------------------------------------------------------------------------------------- #region MonoBehaviour Functions /// <summary> /// Standard Start function. /// </summary> private void Start() { MakingPlanes = false; planesParent = new GameObject("SurfacePlanes"); planesParent.transform.position = Vector3.zero; planesParent.transform.rotation = Quaternion.identity; m_MappingObserver = SpatialMappingManager.Instance.Source as SpatialMappingObserver; } private void OnEnable() { StartCoroutine(RebuildPlanesFromMeshCoroutine()); } #endregion //----------------------------------------------------------------------------------------------- #region Public Static Functions /// <summary> /// Gets the possible types a plane might be. This does not take into account the current floor or ceiling height. /// </summary> /// <param name="bounds"></param> /// <param name="upNormalThreshold"></param> /// <returns></returns> public static PlaneTypes GetPossibleType(BoundedPlane bounds, float upNormalThreshold = 0.9f) { PlaneTypes type; Vector3 surfaceNormal = bounds.Plane.normal; // Determine what type of plane this is. // Use the upNormalThreshold to help determine if we have a horizontal or vertical surface. if (surfaceNormal.y >= upNormalThreshold) { type = PlaneTypes.Floor | PlaneTypes.Table; } else if (surfaceNormal.y <= -(upNormalThreshold)) { type = PlaneTypes.Ceiling | PlaneTypes.Table; } else if (Mathf.Abs(surfaceNormal.y) <= (1 - upNormalThreshold)) { // If the plane is vertical, then classify it as a wall. type = PlaneTypes.Wall; } else { // The plane has a strange angle, classify it as 'unknown'. type = PlaneTypes.Unknown; } return type; } #endregion //----------------------------------------------------------------------------------------------- #region Public Functions /// <summary> /// Coroutine for RebuildPlanesFromMesh. /// </summary> /// <param name="meshes">List of meshes to use to build planes.</param> public IEnumerator RebuildPlanesFromMeshCoroutine() { yield return new WaitForSeconds(1.0f); while (isActiveAndEnabled) { if (m_MappingObserver != null) { List<MeshFilter> meshFilters = m_MappingObserver.GetMeshFilters(); var convertedMeshes = new List<PlaneFinding.MeshData>(meshFilters.Count); for (int i = 0; i < meshFilters.Count; i++) { convertedMeshes.Add(new PlaneFinding.MeshData(meshFilters[i])); } if (convertedMeshes.Count > 0) { yield return MakePlanesRoutine(convertedMeshes); } yield return new WaitForSeconds(2.0f); } } } /// <summary> /// Returns all currently active planes. /// </summary> /// <returns></returns> public List<SurfacePlane> GetActivePlanes() { return new List<SurfacePlane>(m_ActivePlanes); } /// <summary> /// Gets all active planes of the specified type(s). /// </summary> /// <param name="planeTypes">A flag which includes all plane type(s) that should be returned.</param> /// <returns>A collection of planes that match the expected type(s).</returns> public List<SurfacePlane> GetActivePlanes(PlaneTypes planeTypes) { List<SurfacePlane> typePlanes = new List<SurfacePlane>(); foreach (SurfacePlane plane in m_ActivePlanes) { if ((planeTypes & plane.PlaneType) == plane.PlaneType) { typePlanes.Add(plane); } } return typePlanes; } /// <summary> /// Gets the closest plane to a provided world position of one of the types defined by validTypes /// </summary> /// <param name="pos"></param> /// <param name="validTypes"></param> /// <returns></returns> public SurfacePlane GetClosestPlane(Vector3 pos, PlaneTypes validTypes) { SurfacePlane closestPlane = null; List<SurfacePlane> possiblePlanes = new List<SurfacePlane>(); if ((validTypes & PlaneTypes.Ceiling) == PlaneTypes.Ceiling) { SurfacePlane possiblePlane = null; BoundedPlane possibleBounds = new BoundedPlane(); if (m_CeilingPlanes.FindClosestBoundedPlane(pos, out possibleBounds, out possiblePlane)) { possiblePlanes.Add(possiblePlane); } } if ((validTypes & PlaneTypes.Floor) == PlaneTypes.Floor) { SurfacePlane possiblePlane = null; BoundedPlane possibleBounds = new BoundedPlane(); if (m_FloorPlanes.FindClosestBoundedPlane(pos, out possibleBounds, out possiblePlane)) { possiblePlanes.Add(possiblePlane); } } if ((validTypes & PlaneTypes.Table) == PlaneTypes.Table) { SurfacePlane possiblePlane = null; BoundedPlane possibleBounds = new BoundedPlane(); if (m_TablePlanes.FindClosestBoundedPlane(pos, out possibleBounds, out possiblePlane)) { possiblePlanes.Add(possiblePlane); } } if ((validTypes & PlaneTypes.Wall) == PlaneTypes.Wall) { SurfacePlane possiblePlane = null; BoundedPlane possibleBounds = new BoundedPlane(); if (m_WallPlanes.FindClosestBoundedPlane(pos, out possibleBounds, out possiblePlane)) { possiblePlanes.Add(possiblePlane); } } float closestDist = float.MaxValue; //Of the possible planes figure out which is closest. foreach (SurfacePlane possiblePlane in possiblePlanes) { if ((possiblePlane.PlaneType & validTypes) == possiblePlane.PlaneType) { float dist = possiblePlane.Plane.GetSqrDistance(pos); if (closestPlane == null || dist < closestDist) { closestDist = dist; closestPlane = possiblePlane; } } } if (closestPlane != null) { float distanceToPlane = closestPlane.Plane.Plane.GetDistanceToPoint(pos); Vector3 worldPosOnPlane = pos - closestPlane.Plane.Plane.normal * distanceToPlane; Debug.DrawLine(pos, worldPosOnPlane, Color.red, 15); Debug.DrawLine(pos, closestPlane.Plane.GetClosestWorldPoint(pos), Color.green, 15); } return closestPlane; } /// <summary> /// Classifies the surface as a floor, wall, ceiling, table, etc. /// </summary> public PlaneTypes GetPlaneType(BoundedPlane plane) { Vector3 surfaceNormal = plane.Plane.normal; PlaneTypes planeType = PlaneTypes.Unknown; // Determine what type of plane this is. // Use the upNormalThreshold to help determine if we have a horizontal or vertical surface. if (surfaceNormal.y >= UpNormalThreshold) { // If we have a horizontal surface with a normal pointing up, classify it as a floor. planeType = PlaneTypes.Floor; if (plane.Bounds.Center.y > (FloorYPosition + m_FloorBuffer)) { // If the plane is too high to be considered part of the floor, classify it as a table. planeType = PlaneTypes.Table; } } else if (surfaceNormal.y <= -(UpNormalThreshold)) { // If we have a horizontal surface with a normal pointing down, classify it as a ceiling. planeType = PlaneTypes.Ceiling; if (plane.Bounds.Center.y < (CeilingYPosition - m_CeilingBuffer)) { // If the plane is not high enough to be considered part of the ceiling, classify it as a table. planeType = PlaneTypes.Table; } } else if (Mathf.Abs(surfaceNormal.y) <= (1 - UpNormalThreshold)) { // If the plane is vertical, then classify it as a wall. planeType = PlaneTypes.Wall; } else { // The plane has a strange angle, classify it as 'unknown'. planeType = PlaneTypes.Unknown; } return planeType; } #endregion //----------------------------------------------------------------------------------------------- #region Private Functions /// <summary> /// Iterator block, analyzes surface meshes to find planes and create new 3D cubes to represent each plane. /// </summary> /// <returns>Yield result.</returns> private IEnumerator MakePlanesRoutine(List<HoloToolkit.Unity.SpatialMapping.PlaneFinding.MeshData> meshData) { MakingPlanes = true; #if UNITY_WSA && !UNITY_EDITOR // When not in the unity editor we can use a cool background task to help manage FindPlanes(). Task<BoundedPlane[]> planeTask = Task.Run(() => PlaneFinding.FindPlanes(meshData, snapToGravityThreshold, m_MinArea)); while (planeTask.IsCompleted == false) { yield return null; } BoundedPlane[] planes = planeTask.Result; #else // In the unity editor, the task class isn't available, but perf is usually good, so we'll just wait for FindPlanes to complete. BoundedPlane[] planes = PlaneFinding.FindPlanes(meshData, snapToGravityThreshold, m_MinArea); #endif // Pause our work here, and continue on the next frame. yield return null; float start = Time.realtimeSinceStartup; float maxFloorArea = 0.0f; float maxCeilingArea = 0.0f; FloorYPosition = 0.0f; CeilingYPosition = 0.0f; // Find the floor and ceiling. // We classify the floor as the maximum horizontal surface below the user's head. // We classify the ceiling as the maximum horizontal surface above the user's head. for (int i = 0; i < planes.Length; i++) { BoundedPlane boundedPlane = planes[i]; if (boundedPlane.Bounds.Center.y < 0 && boundedPlane.Plane.normal.y >= m_UpNormalThreshold) { maxFloorArea = Mathf.Max(maxFloorArea, boundedPlane.Area); if (maxFloorArea == boundedPlane.Area) { FloorYPosition = boundedPlane.Bounds.Center.y; } } else if (boundedPlane.Bounds.Center.y > 0 && boundedPlane.Plane.normal.y <= -(m_UpNormalThreshold)) { maxCeilingArea = Mathf.Max(maxCeilingArea, boundedPlane.Area); if (maxCeilingArea == boundedPlane.Area) { CeilingYPosition = boundedPlane.Bounds.Center.y; } } } int newPlanes = 0; List<SurfacePlane> oldPlanes = new List<SurfacePlane>(m_ActivePlanes); // Create SurfacePlane objects to represent each plane found in the Spatial Mapping mesh. for (int index = 0; index < planes.Length; index++) { BoundedPlane boundedPlane = planes[index]; boundedPlane.Bounds.Extents.z = m_PlaneThickness /2.0f; SurfacePlane plane = CheckForExistingPlane(oldPlanes, boundedPlane); bool planeExisted = plane != null; if (plane == null) { newPlanes++; // This is a new plane. GameObject newPlaneObj = GameObject.CreatePrimitive(PrimitiveType.Cube); plane = newPlaneObj.AddComponent<SurfacePlane>(); newPlaneObj.GetComponent<Renderer>().shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; newPlaneObj.transform.parent = planesParent.transform; newPlaneObj.name = "Plane " + m_PlaneId; m_PlaneId++; plane.PlaneType = GetPlaneType(boundedPlane); SetPlaneMaterial(plane); } else { oldPlanes.Remove(plane); } // Set the Plane property to adjust transform position/scale/rotation and determine plane type. plane.PlaneThickness = m_PlaneThickness; plane.Plane = boundedPlane; // Set the plane to use the same layer as the SpatialMapping mesh. Do this every time incase the layer has changed. plane.gameObject.layer = SpatialMappingManager.Instance.PhysicsLayer; SetPlaneVisibility(plane); if ((m_DestroyPlanesMask & plane.PlaneType) == plane.PlaneType) { DestroyImmediate(plane.gameObject); } else if (!planeExisted) { AddPlane(plane); } // If too much time has passed, we need to return control to the main game loop. if ((Time.realtimeSinceStartup - start) > FrameTime) { // Pause our work here, and continue making additional planes on the next frame. yield return null; start = Time.realtimeSinceStartup; } } for (int index = 0; index < oldPlanes.Count; index++) { RemovePlane(oldPlanes[index]); Destroy(oldPlanes[index].gameObject); } // We are done creating planes, trigger an event. EventHandler handler = MakePlanesComplete; if (handler != null) { handler(this, EventArgs.Empty); } MakingPlanes = false; } /// <summary> /// Adds the plane to tracking. /// </summary> /// <param name="plane"></param> private void AddPlane(SurfacePlane plane) { m_ActivePlanes.Add(plane); switch (plane.PlaneType) { case PlaneTypes.Ceiling: { m_CeilingPlanes.Add(plane.Plane, plane); break; } case PlaneTypes.Floor: { m_FloorPlanes.Add(plane.Plane, plane); break; } case PlaneTypes.Table: { m_TablePlanes.Add(plane.Plane, plane); break; } case PlaneTypes.Wall: { m_WallPlanes.Add(plane.Plane, plane); break; } } } /// <summary> /// Removes the plane from tracking. /// </summary> /// <param name="plane"></param> private void RemovePlane(SurfacePlane plane) { m_ActivePlanes.Remove(plane); switch (plane.PlaneType) { case PlaneTypes.Ceiling: { m_CeilingPlanes.Remove(plane); break; } case PlaneTypes.Floor: { m_FloorPlanes.Remove(plane); break; } case PlaneTypes.Table: { m_TablePlanes.Remove(plane); break; } case PlaneTypes.Wall: { m_WallPlanes.Remove(plane); break; } } } /// <summary> /// Checks the list of passed in planes for one that might match the passed in bounding plane. /// </summary> /// <param name="planes"></param> /// <param name="plane"></param> /// <returns></returns> private SurfacePlane CheckForExistingPlane(List<SurfacePlane> planes, BoundedPlane plane) { SurfacePlane bestMatch = null; float bestAreaDiff = float.MaxValue; float bestDistance = float.MaxValue; float bestDistPercent = float.MaxValue; PlaneTypes type = GetPossibleType(plane, m_UpNormalThreshold); foreach (SurfacePlane possiblePlane in planes) { if ((possiblePlane.PlaneType & type) == 0) { //Skip this one. continue; } //What is the area difference? float areaDiff = Mathf.Abs(possiblePlane.Plane.Area - plane.Area); float areaDiffPercent = areaDiff / ((possiblePlane.Plane.Area + plane.Area ) / 2); //What is the distance difference? float distDiff = (possiblePlane.Plane.Bounds.Center - plane.Bounds.Center).sqrMagnitude; float distChangePercent = distDiff /(possiblePlane.Plane.Bounds.Center.sqrMagnitude + plane.Bounds.Center.sqrMagnitude) / 2; if (areaDiffPercent >= m_MaxAreaDiffPercent || distDiff > m_MaxDistChange) { //The difference in these planes are to different so we can ignore this one. continue; } else if (areaDiffPercent < bestAreaDiff && distDiff < bestDistance) { bestMatch = possiblePlane; bestAreaDiff = areaDiffPercent; bestDistPercent = distChangePercent; distDiff = bestDistance; } else if (areaDiffPercent < bestAreaDiff && areaDiffPercent <= bestDistPercent) { bestMatch = possiblePlane; bestAreaDiff = areaDiffPercent; bestDistPercent = distChangePercent; distDiff = bestDistance; } else if (distDiff < bestDistance && distChangePercent <= areaDiffPercent) { bestMatch = possiblePlane; bestAreaDiff = areaDiffPercent; bestDistPercent = distChangePercent; distDiff = bestDistance; } } return bestMatch; } /// <summary> /// Sets the material on the renderer based on the type of plane it is. /// </summary> /// <param name="plane"></param> private void SetPlaneMaterial(SurfacePlane plane) { Material mat = null; switch (plane.PlaneType) { case PlaneTypes.Ceiling: { mat = m_CeilingMaterial; break; } case PlaneTypes.Floor: { mat = m_FloorMaterial; break; } case PlaneTypes.Table: { mat = m_TableMaterial; break; } case PlaneTypes.Wall: { mat = m_WallMaterial; break; } } plane.SetPlaneMaterial(mat); } /// <summary> /// Sets visibility of planes based on their type. /// </summary> /// <param name="surfacePlane"></param> private void SetPlaneVisibility(SurfacePlane surfacePlane) { surfacePlane.IsVisible = m_ShowPlanes && ((m_DrawPlanesMask & surfacePlane.PlaneType) == surfacePlane.PlaneType); } #endregion } #region Inspector #if UNITY_EDITOR /// <summary> /// Editor extension class to enable multi-selection of the 'Draw Planes' and 'Destroy Planes' options in the Inspector. /// </summary> [CustomEditor(typeof(SurfacePlaneManager))] public class PlaneTypesEnumEditor : Editor { public SerializedProperty drawPlanesMask; public SerializedProperty destroyPlanesMask; void OnEnable() { drawPlanesMask = serializedObject.FindProperty("m_DrawPlanesMask"); destroyPlanesMask = serializedObject.FindProperty("m_DestroyPlanesMask"); } public override void OnInspectorGUI() { base.OnInspectorGUI(); serializedObject.Update(); drawPlanesMask.intValue = (int)((PlaneTypes)EditorGUILayout.EnumMaskField ("Draw Planes", (PlaneTypes)drawPlanesMask.intValue)); destroyPlanesMask.intValue = (int)((PlaneTypes)EditorGUILayout.EnumMaskField ("Destroy Planes", (PlaneTypes)destroyPlanesMask.intValue)); serializedObject.ApplyModifiedProperties(); } } #endif #endregion }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel.Dispatcher { using System; using System.Diagnostics; using System.Reflection; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Diagnostics; using System.ServiceModel.Diagnostics.Application; class InstanceBehavior { const BindingFlags DefaultBindingFlags = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public; bool useSession; ServiceHostBase host; IInstanceContextInitializer[] initializers; IInstanceContextProvider instanceContextProvider; IInstanceProvider provider; InstanceContext singleton; bool transactionAutoCompleteOnSessionClose; bool releaseServiceInstanceOnTransactionComplete = true; bool isSynchronized; ImmutableDispatchRuntime immutableRuntime; internal InstanceBehavior(DispatchRuntime dispatch, ImmutableDispatchRuntime immutableRuntime) { this.useSession = dispatch.ChannelDispatcher.Session; this.immutableRuntime = immutableRuntime; this.host = (dispatch.ChannelDispatcher == null) ? null : dispatch.ChannelDispatcher.Host; this.initializers = EmptyArray<IInstanceContextInitializer>.ToArray(dispatch.InstanceContextInitializers); this.provider = dispatch.InstanceProvider; this.singleton = dispatch.SingletonInstanceContext; this.transactionAutoCompleteOnSessionClose = dispatch.TransactionAutoCompleteOnSessionClose; this.releaseServiceInstanceOnTransactionComplete = dispatch.ReleaseServiceInstanceOnTransactionComplete; this.isSynchronized = (dispatch.ConcurrencyMode != ConcurrencyMode.Multiple); this.instanceContextProvider = dispatch.InstanceContextProvider; if (this.provider == null) { ConstructorInfo constructor = null; if (dispatch.Type != null) { constructor = InstanceBehavior.GetConstructor(dispatch.Type); } if (this.singleton == null) { if (dispatch.Type != null && (dispatch.Type.IsAbstract || dispatch.Type.IsInterface)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxServiceTypeNotCreatable))); } if (constructor == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxNoDefaultConstructor))); } } if (constructor != null) { if (this.singleton == null || !this.singleton.IsWellKnown) { InvokerUtil util = new InvokerUtil(); CreateInstanceDelegate creator = util.GenerateCreateInstanceDelegate(dispatch.Type, constructor); this.provider = new InstanceProvider(creator); } } } if (this.singleton != null) { this.singleton.Behavior = this; } } internal bool TransactionAutoCompleteOnSessionClose { get { return this.transactionAutoCompleteOnSessionClose; } } internal bool ReleaseServiceInstanceOnTransactionComplete { get { return this.releaseServiceInstanceOnTransactionComplete; } } internal IInstanceContextProvider InstanceContextProvider { get { return this.instanceContextProvider; } } internal void AfterReply(ref MessageRpc rpc, ErrorBehavior error) { InstanceContext context = rpc.InstanceContext; if (context != null) { try { if (rpc.Operation.ReleaseInstanceAfterCall) { if (context.State == CommunicationState.Opened) { context.ReleaseServiceInstance(); } } else if (releaseServiceInstanceOnTransactionComplete && this.isSynchronized && rpc.transaction != null && (rpc.transaction.IsCompleted || (rpc.Error != null))) { if (context.State == CommunicationState.Opened) { context.ReleaseServiceInstance(); } if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.TxReleaseServiceInstanceOnCompletion, SR.GetString(SR.TraceCodeTxReleaseServiceInstanceOnCompletion, "*")); } } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } error.HandleError(e); } try { context.UnbindRpc(ref rpc); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } error.HandleError(e); } } } internal bool CanUnload(InstanceContext instanceContext) { if (InstanceContextProviderBase.IsProviderSingleton(this.instanceContextProvider)) return false; if (InstanceContextProviderBase.IsProviderPerCall(this.instanceContextProvider) || InstanceContextProviderBase.IsProviderSessionful(this.instanceContextProvider)) return true; //User provided InstanceContextProvider. Call the provider to check for idle. if (!this.instanceContextProvider.IsIdle(instanceContext)) { this.instanceContextProvider.NotifyIdle(InstanceContext.NotifyIdleCallback, instanceContext); return false; } return true; } internal void EnsureInstanceContext(ref MessageRpc rpc) { if (rpc.InstanceContext == null) { rpc.InstanceContext = new InstanceContext(rpc.Host, false); rpc.InstanceContext.ServiceThrottle = rpc.channelHandler.InstanceContextServiceThrottle; rpc.MessageRpcOwnsInstanceContextThrottle = false; } rpc.OperationContext.SetInstanceContext(rpc.InstanceContext); rpc.InstanceContext.Behavior = this; if (rpc.InstanceContext.State == CommunicationState.Created) { lock (rpc.InstanceContext.ThisLock) { if (rpc.InstanceContext.State == CommunicationState.Created) { rpc.InstanceContext.Open(rpc.Channel.CloseTimeout); } } } rpc.InstanceContext.BindRpc(ref rpc); } static ConstructorInfo GetConstructor(Type type) { return type.GetConstructor(DefaultBindingFlags, null, Type.EmptyTypes, null); } internal object GetInstance(InstanceContext instanceContext) { if (this.provider == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxNoDefaultConstructor))); } return this.provider.GetInstance(instanceContext); } internal object GetInstance(InstanceContext instanceContext, Message request) { if (this.provider == null) { throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxNoDefaultConstructor)), request); } return this.provider.GetInstance(instanceContext, request); } internal void Initialize(InstanceContext instanceContext) { OperationContext current = OperationContext.Current; Message message = (current != null) ? current.IncomingMessage : null; if (current != null && current.InternalServiceChannel != null) { IContextChannel transparentProxy = (IContextChannel)current.InternalServiceChannel.Proxy; this.instanceContextProvider.InitializeInstanceContext(instanceContext, message, transparentProxy); } for (int i = 0; i < this.initializers.Length; i++) this.initializers[i].Initialize(instanceContext, message); } internal void EnsureServiceInstance(ref MessageRpc rpc) { if (rpc.Operation.ReleaseInstanceBeforeCall) { rpc.InstanceContext.ReleaseServiceInstance(); } if (TD.GetServiceInstanceStartIsEnabled()) { TD.GetServiceInstanceStart(rpc.EventTraceActivity); } rpc.Instance = rpc.InstanceContext.GetServiceInstance(rpc.Request); if (TD.GetServiceInstanceStopIsEnabled()) { TD.GetServiceInstanceStop(rpc.EventTraceActivity); } } internal void ReleaseInstance(InstanceContext instanceContext, object instance) { if (this.provider != null) { try { this.provider.ReleaseInstance(instanceContext, instance); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.immutableRuntime.ErrorBehavior.HandleError(e); } } } } class InstanceProvider : IInstanceProvider { CreateInstanceDelegate creator; internal InstanceProvider(CreateInstanceDelegate creator) { if (creator == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("creator"); this.creator = creator; } public object GetInstance(InstanceContext instanceContext) { return this.creator(); } public object GetInstance(InstanceContext instanceContext, Message message) { return this.creator(); } public void ReleaseInstance(InstanceContext instanceContext, object instance) { IDisposable dispose = instance as IDisposable; if (dispose != null) dispose.Dispose(); } } }
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Text.RegularExpressions; using Boo.Lang.Compiler.Ast; using Boo.Lang.Compiler.Util; using Boo.Lang.Compiler.TypeSystem; using Boo.Lang.Compiler.TypeSystem.Reflection; using Boo.Lang.Environments; using Boo.Lang.Resources; namespace Boo.Lang.Compiler { /// <summary> /// Compiler parameters. /// </summary> public class CompilerParameters { public static IReflectionTypeSystemProvider SharedTypeSystemProvider = new ReflectionTypeSystemProvider(); private TextWriter _outputWriter; private readonly CompilerInputCollection _input; private readonly CompilerResourceCollection _resources; private CompilerReferenceCollection _compilerReferences; private string _outputAssembly; private bool _strict; private readonly List<string> _libPaths; private readonly string _systemDir; private Assembly _booAssembly; private readonly Dictionary<string, string> _defines = new Dictionary<string, string>(StringComparer.Ordinal); private TypeMemberModifiers _defaultTypeVisibility = TypeMemberModifiers.Public; private TypeMemberModifiers _defaultMethodVisibility = TypeMemberModifiers.Public; private TypeMemberModifiers _defaultPropertyVisibility = TypeMemberModifiers.Public; private TypeMemberModifiers _defaultEventVisibility = TypeMemberModifiers.Public; private TypeMemberModifiers _defaultFieldVisibility = TypeMemberModifiers.Protected; private bool _defaultVisibilitySettingsRead; public CompilerParameters() : this(true) { } public CompilerParameters(bool loadDefaultReferences) : this(SharedTypeSystemProvider, loadDefaultReferences) { } public CompilerParameters(IReflectionTypeSystemProvider reflectionProvider) : this(reflectionProvider, true) { } public CompilerParameters(IReflectionTypeSystemProvider reflectionProvider, bool loadDefaultReferences) { _libPaths = new List<string>(); _systemDir = Permissions.WithDiscoveryPermission(() => GetSystemDir()); if (_systemDir != null) { _libPaths.Add(_systemDir); _libPaths.Add(Directory.GetCurrentDirectory()); } _input = new CompilerInputCollection(); _resources = new CompilerResourceCollection(); _compilerReferences = new CompilerReferenceCollection(reflectionProvider); MaxExpansionIterations = 12; _outputAssembly = String.Empty; OutputType = CompilerOutputType.Auto; _outputWriter = Console.Out; Debug = true; Checked = true; GenerateInMemory = true; StdLib = true; DelaySign = false; Strict = false; TraceLevel = DefaultTraceLevel(); if (loadDefaultReferences) LoadDefaultReferences(); } private static TraceLevel DefaultTraceLevel() { var booTraceLevel = Permissions.WithEnvironmentPermission(() => System.Environment.GetEnvironmentVariable("BOO_TRACE_LEVEL")); return string.IsNullOrEmpty(booTraceLevel) ? TraceLevel.Off : (TraceLevel)Enum.Parse(typeof(TraceLevel), booTraceLevel); } public void LoadDefaultReferences() { //boo.lang.dll _booAssembly = typeof(Builtins).Assembly; _compilerReferences.Add(_booAssembly); //boo.lang.extensions.dll //try loading extensions next to Boo.Lang (in the same directory) var extensionsAssembly = TryToLoadExtensionsAssembly(); if (extensionsAssembly != null) _compilerReferences.Add(extensionsAssembly); //boo.lang.compiler.dll _compilerReferences.Add(GetType().Assembly); //mscorlib _compilerReferences.Add(LoadAssembly("mscorlib", true)); //System _compilerReferences.Add(LoadAssembly("System", true)); //System.Core _compilerReferences.Add(LoadAssembly("System.Core", true)); Permissions.WithDiscoveryPermission<object>(() => { WriteTraceInfo("BOO LANG DLL: " + _booAssembly.Location); WriteTraceInfo("BOO COMPILER EXTENSIONS DLL: " + (extensionsAssembly != null ? extensionsAssembly.ToString() : "NOT FOUND!")); return null; }); } private IAssemblyReference TryToLoadExtensionsAssembly() { const string booLangExtensionsDll = "Boo.Lang.Extensions.dll"; return Permissions.WithDiscoveryPermission(() => { var path = Path.Combine(Path.GetDirectoryName(_booAssembly.Location), booLangExtensionsDll); return File.Exists(path) ? AssemblyReferenceFor(Assembly.LoadFrom(path)) : null; }) ?? LoadAssembly(booLangExtensionsDll, false); } public Assembly BooAssembly { get { return _booAssembly; } set { if (null == value) throw new ArgumentNullException("value"); if (value != _booAssembly) { _compilerReferences.Remove(_booAssembly); _booAssembly = value; _compilerReferences.Add(value); } } } public ICompileUnit FindAssembly(string name) { return _compilerReferences.Find(name); } public void AddAssembly(Assembly asm) { if (null == asm) throw new ArgumentNullException(); _compilerReferences.Add(asm); } public IAssemblyReference LoadAssembly(string assembly) { return LoadAssembly(assembly, true); } public IAssemblyReference LoadAssembly(string assemblyName, bool throwOnError) { var assembly = ForName(assemblyName, throwOnError); return assembly != null ? AssemblyReferenceFor(assembly) : null; } private IAssemblyReference AssemblyReferenceFor(Assembly assembly) { return _compilerReferences.Provider.ForAssembly(assembly); } protected virtual Assembly ForName(string assembly, bool throwOnError) { Assembly a = null; try { if (assembly.IndexOfAny(new char[] {'/', '\\'}) != -1) a = Assembly.LoadFrom(assembly); else a = LoadAssemblyFromGac(assembly); } catch (FileNotFoundException /*ignored*/) { return LoadAssemblyFromLibPaths(assembly, throwOnError); } catch (BadImageFormatException e) { if (throwOnError) throw new ApplicationException(string.Format(Boo.Lang.Resources.StringResources.BooC_BadFormat, e.FusionLog), e); } catch (FileLoadException e) { if (throwOnError) throw new ApplicationException(string.Format(Boo.Lang.Resources.StringResources.BooC_UnableToLoadAssembly, e.FusionLog), e); } catch (ArgumentNullException e) { if (throwOnError) throw new ApplicationException(Boo.Lang.Resources.StringResources.BooC_NullAssembly, e); } return a ?? LoadAssemblyFromLibPaths(assembly, false); } private Assembly LoadAssemblyFromLibPaths(string assembly, bool throwOnError) { Assembly a = null; string fullLog = ""; foreach (string dir in _libPaths) { string full_path = Path.Combine(dir, assembly); FileInfo file = new FileInfo(full_path); if (!IsAssemblyExtension(file.Extension)) full_path += ".dll"; try { a = Assembly.LoadFrom(full_path); if (a != null) { return a; } } catch (FileNotFoundException ff) { fullLog += ff.FusionLog; continue; } } if (throwOnError) { throw new ApplicationException(string.Format(Boo.Lang.Resources.StringResources.BooC_CannotFindAssembly, assembly)); //assembly, total_log)); //total_log contains the fusion log } return a; } private static bool IsAssemblyExtension(string extension) { switch (extension.ToLower()) { case ".dll": case ".exe": return true; } return false; } private static Assembly LoadAssemblyFromGac(string assemblyName) { assemblyName = NormalizeAssemblyName(assemblyName); // This is an intentional attempt to load an assembly with partial name // so ignore the compiler warning #pragma warning disable 618 var assembly = Permissions.WithDiscoveryPermission(()=> Assembly.LoadWithPartialName(assemblyName)); #pragma warning restore 618 return assembly ?? Assembly.Load(assemblyName); } private static string NormalizeAssemblyName(string assembly) { var extension = Path.GetExtension(assembly).ToLower(); if (extension == ".dll" || extension == ".exe") return assembly.Substring(0, assembly.Length - 4); return assembly; } public void LoadReferencesFromPackage(string package) { string[] libs = Regex.Split(pkgconfig(package), @"\-r\:", RegexOptions.CultureInvariant); foreach (string r in libs) { string reference = r.Trim(); if (reference.Length == 0) continue; WriteTraceInfo("LOADING REFERENCE FROM PKGCONFIG '" + package + "' : " + reference); References.Add(LoadAssembly(reference)); } } [Conditional("TRACE")] private void WriteTraceInfo(string message) { if (TraceInfo) Console.Error.WriteLine(message); } private static string pkgconfig(string package) { #if NO_SYSTEM_PROCESS throw new System.NotSupportedException(); #else Process process; try { process = Builtins.shellp("pkg-config", String.Format("--libs {0}", package)); } catch (Exception e) { throw new ApplicationException(StringResources.BooC_PkgConfigNotFound, e); } process.WaitForExit(); if (process.ExitCode != 0) { throw new ApplicationException(string.Format(StringResources.BooC_PkgConfigReportedErrors, process.StandardError.ReadToEnd())); } return process.StandardOutput.ReadToEnd(); #endif } private static string GetSystemDir() { return Path.GetDirectoryName(typeof(string).Assembly.Location); } /// <summary> /// Max number of iterations for the application of AST attributes and the /// expansion of macros. /// </summary> public int MaxExpansionIterations { get; set; } public CompilerInputCollection Input { get { return _input; } } public List<string> LibPaths { get { return _libPaths; } } public CompilerResourceCollection Resources { get { return _resources; } } public CompilerReferenceCollection References { get { return _compilerReferences; } set { if (null == value) throw new ArgumentNullException("References"); _compilerReferences = value; } } /// <summary> /// The compilation pipeline. /// </summary> public CompilerPipeline Pipeline { get; set; } /// <summary> /// The name (full or partial) for the file /// that should receive the resulting assembly. /// </summary> public string OutputAssembly { get { return _outputAssembly; } set { if (String.IsNullOrEmpty(value)) throw new ArgumentNullException("OutputAssembly"); _outputAssembly = value; } } /// <summary> /// Type and execution subsystem for the generated portable /// executable file. /// </summary> public CompilerOutputType OutputType { get; set; } public bool GenerateInMemory { get; set; } public bool StdLib { get; set; } public TextWriter OutputWriter { get { return _outputWriter; } set { if (null == value) throw new ArgumentNullException("OutputWriter"); _outputWriter = value; } } public bool Debug { get; set; } /// <summary> /// Treat System.Object as duck /// </summary> public virtual bool Ducky { get; set; } public bool Checked { get; set; } public string KeyFile { get; set; } public string KeyContainer { get; set; } public bool DelaySign { get; set; } public bool WhiteSpaceAgnostic { get; set; } public Dictionary<string, string> Defines { get { return _defines; } } public TypeMemberModifiers DefaultTypeVisibility { get { if (!_defaultVisibilitySettingsRead) ReadDefaultVisibilitySettings(); return _defaultTypeVisibility; } set { _defaultTypeVisibility = value & TypeMemberModifiers.VisibilityMask; } } public TypeMemberModifiers DefaultMethodVisibility { get { if (!_defaultVisibilitySettingsRead) ReadDefaultVisibilitySettings(); return _defaultMethodVisibility; } set { _defaultMethodVisibility = value & TypeMemberModifiers.VisibilityMask; } } public TypeMemberModifiers DefaultPropertyVisibility { get { if (!_defaultVisibilitySettingsRead) ReadDefaultVisibilitySettings(); return _defaultPropertyVisibility; } set { _defaultPropertyVisibility = value & TypeMemberModifiers.VisibilityMask; } } public TypeMemberModifiers DefaultEventVisibility { get { if (!_defaultVisibilitySettingsRead) ReadDefaultVisibilitySettings(); return _defaultEventVisibility; } set { _defaultEventVisibility = value & TypeMemberModifiers.VisibilityMask; } } public TypeMemberModifiers DefaultFieldVisibility { get { if (!_defaultVisibilitySettingsRead) ReadDefaultVisibilitySettings(); return _defaultFieldVisibility; } set { _defaultFieldVisibility = value & TypeMemberModifiers.VisibilityMask; } } public bool TraceInfo { get { return TraceLevel >= TraceLevel.Info; } } public bool TraceWarning { get { return TraceLevel >= TraceLevel.Warning; } } public bool TraceError { get { return TraceLevel >= TraceLevel.Error; } } public bool TraceVerbose { get { return TraceLevel >= TraceLevel.Verbose; } } public TraceLevel TraceLevel { get; set; } private void ReadDefaultVisibilitySettings() { string visibility; if (_defines.TryGetValue("DEFAULT_TYPE_VISIBILITY", out visibility)) DefaultTypeVisibility = ParseVisibility(visibility); if (_defines.TryGetValue("DEFAULT_METHOD_VISIBILITY", out visibility)) DefaultMethodVisibility = ParseVisibility(visibility); if (_defines.TryGetValue("DEFAULT_PROPERTY_VISIBILITY", out visibility)) DefaultPropertyVisibility = ParseVisibility(visibility); if (_defines.TryGetValue("DEFAULT_EVENT_VISIBILITY", out visibility)) DefaultEventVisibility = ParseVisibility(visibility); if (_defines.TryGetValue("DEFAULT_FIELD_VISIBILITY", out visibility)) DefaultFieldVisibility = ParseVisibility(visibility); _defaultVisibilitySettingsRead = true; } private static TypeMemberModifiers ParseVisibility(string visibility) { if (String.IsNullOrEmpty(visibility)) throw new ArgumentNullException("visibility"); visibility = visibility.ToLower(); switch (visibility) { case "public": return TypeMemberModifiers.Public; case "protected": return TypeMemberModifiers.Protected; case "internal": return TypeMemberModifiers.Internal; case "private": return TypeMemberModifiers.Private; } throw new ArgumentException("visibility", String.Format("Invalid visibility: '{0}'", visibility)); } Util.Set<string> _disabledWarnings = new Util.Set<string>(); Util.Set<string> _promotedWarnings = new Util.Set<string>(); public bool NoWarn { get; set; } public bool WarnAsError { get; set; } public ICollection<string> DisabledWarnings { get { return _disabledWarnings; } } public ICollection<string> WarningsAsErrors { get { return _promotedWarnings; } } public void EnableWarning(string code) { if (_disabledWarnings.Contains(code)) _disabledWarnings.Remove(code); } public void DisableWarning(string code) { _disabledWarnings.Add(code); } public void ResetWarnings() { NoWarn = false; _disabledWarnings.Clear(); Strict = _strict; } public void EnableWarningAsError(string code) { _promotedWarnings.Add(code); } public void DisableWarningAsError(string code) { if (_promotedWarnings.Contains(code)) _promotedWarnings.Remove(code); } public void ResetWarningsAsErrors() { WarnAsError = false; _promotedWarnings.Clear(); } public bool Strict { get { return _strict; } set { _strict = value; if (_strict) OnStrictMode(); else OnNonStrictMode(); } } protected virtual void OnNonStrictMode() { _defaultTypeVisibility = TypeMemberModifiers.Public; _defaultMethodVisibility = TypeMemberModifiers.Public; _defaultPropertyVisibility = TypeMemberModifiers.Public; _defaultEventVisibility = TypeMemberModifiers.Public; _defaultFieldVisibility = TypeMemberModifiers.Protected; DisableWarning(CompilerWarningFactory.Codes.ImplicitReturn); DisableWarning(CompilerWarningFactory.Codes.VisibleMemberDoesNotDeclareTypeExplicitely); DisableWarning(CompilerWarningFactory.Codes.ImplicitDowncast); } protected virtual void OnStrictMode() { _defaultTypeVisibility = TypeMemberModifiers.Private; _defaultMethodVisibility = TypeMemberModifiers.Private; _defaultPropertyVisibility = TypeMemberModifiers.Private; _defaultEventVisibility = TypeMemberModifiers.Private; _defaultFieldVisibility = TypeMemberModifiers.Private; EnableWarning(CompilerWarningFactory.Codes.ImplicitReturn); EnableWarning(CompilerWarningFactory.Codes.VisibleMemberDoesNotDeclareTypeExplicitely); //by default strict mode forbids implicit downcasts //disable warning so we get only the regular incompatible type error DisableWarning(CompilerWarningFactory.Codes.ImplicitDowncast); } public bool Unsafe { get; set; } public string Platform { get; set; } public IEnvironment Environment { get; set; } } }
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * Generated by: https://openapi-generator.tech */ using System; using System.Linq; using System.Text; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; using Newtonsoft.Json; using Org.OpenAPITools.Converters; namespace Org.OpenAPITools.Models { /// <summary> /// /// </summary> [DataContract] public partial class PipelineBranchesitemlatestRun : IEquatable<PipelineBranchesitemlatestRun> { /// <summary> /// Gets or Sets DurationInMillis /// </summary> [DataMember(Name="durationInMillis", EmitDefaultValue=false)] public int DurationInMillis { get; set; } /// <summary> /// Gets or Sets EstimatedDurationInMillis /// </summary> [DataMember(Name="estimatedDurationInMillis", EmitDefaultValue=false)] public int EstimatedDurationInMillis { get; set; } /// <summary> /// Gets or Sets EnQueueTime /// </summary> [DataMember(Name="enQueueTime", EmitDefaultValue=false)] public string EnQueueTime { get; set; } /// <summary> /// Gets or Sets EndTime /// </summary> [DataMember(Name="endTime", EmitDefaultValue=false)] public string EndTime { get; set; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// Gets or Sets Organization /// </summary> [DataMember(Name="organization", EmitDefaultValue=false)] public string Organization { get; set; } /// <summary> /// Gets or Sets Pipeline /// </summary> [DataMember(Name="pipeline", EmitDefaultValue=false)] public string Pipeline { get; set; } /// <summary> /// Gets or Sets Result /// </summary> [DataMember(Name="result", EmitDefaultValue=false)] public string Result { get; set; } /// <summary> /// Gets or Sets RunSummary /// </summary> [DataMember(Name="runSummary", EmitDefaultValue=false)] public string RunSummary { get; set; } /// <summary> /// Gets or Sets StartTime /// </summary> [DataMember(Name="startTime", EmitDefaultValue=false)] public string StartTime { get; set; } /// <summary> /// Gets or Sets State /// </summary> [DataMember(Name="state", EmitDefaultValue=false)] public string State { get; set; } /// <summary> /// Gets or Sets Type /// </summary> [DataMember(Name="type", EmitDefaultValue=false)] public string Type { get; set; } /// <summary> /// Gets or Sets CommitId /// </summary> [DataMember(Name="commitId", EmitDefaultValue=false)] public string CommitId { get; set; } /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name="_class", EmitDefaultValue=false)] public string Class { 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 PipelineBranchesitemlatestRun {\n"); sb.Append(" DurationInMillis: ").Append(DurationInMillis).Append("\n"); sb.Append(" EstimatedDurationInMillis: ").Append(EstimatedDurationInMillis).Append("\n"); sb.Append(" EnQueueTime: ").Append(EnQueueTime).Append("\n"); sb.Append(" EndTime: ").Append(EndTime).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Organization: ").Append(Organization).Append("\n"); sb.Append(" Pipeline: ").Append(Pipeline).Append("\n"); sb.Append(" Result: ").Append(Result).Append("\n"); sb.Append(" RunSummary: ").Append(RunSummary).Append("\n"); sb.Append(" StartTime: ").Append(StartTime).Append("\n"); sb.Append(" State: ").Append(State).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" CommitId: ").Append(CommitId).Append("\n"); sb.Append(" Class: ").Append(Class).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 Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (obj is null) return false; if (ReferenceEquals(this, obj)) return true; return obj.GetType() == GetType() && Equals((PipelineBranchesitemlatestRun)obj); } /// <summary> /// Returns true if PipelineBranchesitemlatestRun instances are equal /// </summary> /// <param name="other">Instance of PipelineBranchesitemlatestRun to be compared</param> /// <returns>Boolean</returns> public bool Equals(PipelineBranchesitemlatestRun other) { if (other is null) return false; if (ReferenceEquals(this, other)) return true; return ( DurationInMillis == other.DurationInMillis || DurationInMillis.Equals(other.DurationInMillis) ) && ( EstimatedDurationInMillis == other.EstimatedDurationInMillis || EstimatedDurationInMillis.Equals(other.EstimatedDurationInMillis) ) && ( EnQueueTime == other.EnQueueTime || EnQueueTime != null && EnQueueTime.Equals(other.EnQueueTime) ) && ( EndTime == other.EndTime || EndTime != null && EndTime.Equals(other.EndTime) ) && ( Id == other.Id || Id != null && Id.Equals(other.Id) ) && ( Organization == other.Organization || Organization != null && Organization.Equals(other.Organization) ) && ( Pipeline == other.Pipeline || Pipeline != null && Pipeline.Equals(other.Pipeline) ) && ( Result == other.Result || Result != null && Result.Equals(other.Result) ) && ( RunSummary == other.RunSummary || RunSummary != null && RunSummary.Equals(other.RunSummary) ) && ( StartTime == other.StartTime || StartTime != null && StartTime.Equals(other.StartTime) ) && ( State == other.State || State != null && State.Equals(other.State) ) && ( Type == other.Type || Type != null && Type.Equals(other.Type) ) && ( CommitId == other.CommitId || CommitId != null && CommitId.Equals(other.CommitId) ) && ( Class == other.Class || Class != null && Class.Equals(other.Class) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) hashCode = hashCode * 59 + DurationInMillis.GetHashCode(); hashCode = hashCode * 59 + EstimatedDurationInMillis.GetHashCode(); if (EnQueueTime != null) hashCode = hashCode * 59 + EnQueueTime.GetHashCode(); if (EndTime != null) hashCode = hashCode * 59 + EndTime.GetHashCode(); if (Id != null) hashCode = hashCode * 59 + Id.GetHashCode(); if (Organization != null) hashCode = hashCode * 59 + Organization.GetHashCode(); if (Pipeline != null) hashCode = hashCode * 59 + Pipeline.GetHashCode(); if (Result != null) hashCode = hashCode * 59 + Result.GetHashCode(); if (RunSummary != null) hashCode = hashCode * 59 + RunSummary.GetHashCode(); if (StartTime != null) hashCode = hashCode * 59 + StartTime.GetHashCode(); if (State != null) hashCode = hashCode * 59 + State.GetHashCode(); if (Type != null) hashCode = hashCode * 59 + Type.GetHashCode(); if (CommitId != null) hashCode = hashCode * 59 + CommitId.GetHashCode(); if (Class != null) hashCode = hashCode * 59 + Class.GetHashCode(); return hashCode; } } #region Operators #pragma warning disable 1591 public static bool operator ==(PipelineBranchesitemlatestRun left, PipelineBranchesitemlatestRun right) { return Equals(left, right); } public static bool operator !=(PipelineBranchesitemlatestRun left, PipelineBranchesitemlatestRun right) { return !Equals(left, right); } #pragma warning restore 1591 #endregion Operators } }
using System; using System.Collections.Generic; using System.Text; using gView.Framework.Carto.Rendering; using gView.Framework.UI; using gView.Framework.IO; using System.Reflection; using gView.Framework.Data; using gView.Framework.Symbology; using gView.Framework.system; using gView.Framework.Carto.Rendering.UI; namespace gView.Framework.Carto.Rendering { [gView.Framework.system.RegisterPlugIn("4221EF57-E89E-4035-84EB-D3FA163FDE0C")] public class ScaleDependentLabelRenderer : ILabelRenderer, ILabelGroupRenderer, ILegendGroup, IPropertyPage { private RendererList _renderers; public ScaleDependentLabelRenderer() { _renderers = new RendererList(); } #region IGroupRenderer Member public ILabelRendererGroup Renderers { get { return _renderers; } } #endregion #region ILabelRenderer Member public void PrepareQueryFilter(IDisplay display, gView.Framework.Data.IFeatureLayer layer, gView.Framework.Data.IQueryFilter filter) { foreach (ILabelRenderer renderer in _renderers) { if (renderer == null) continue; renderer.PrepareQueryFilter(display, layer, filter); } } public bool CanRender(gView.Framework.Data.IFeatureLayer layer, IMap map) { return true; } public string Name { get { return "Scale Dependent/Group Labelrenderer"; } } public LabelRenderMode RenderMode { get { return LabelRenderMode.UseRenderPriority; } } public int RenderPriority { get { return 0; } } public void Draw(IDisplay disp, gView.Framework.Data.IFeature feature) { foreach (ILabelRenderer renderer in _renderers) { if (renderer == null) continue; renderer.Draw(disp, feature); } } #endregion #region IPersistable Member public void Load(IPersistStream stream) { ScaleRendererPersist persist; while ((persist = stream.Load("ScaleRenderer", null, new ScaleRendererPersist(new ScaleRenderer(null))) as ScaleRendererPersist) != null) { _renderers.Add(persist.ScaleRenderer); } } public void Save(IPersistStream stream) { foreach (ILabelRenderer renderer in _renderers) { if (renderer == null) continue; stream.Save("ScaleRenderer", new ScaleRendererPersist(renderer as ScaleRenderer)); } } #endregion #region IClone Member public object Clone() { ScaleDependentLabelRenderer scaleDependentRenderer = new ScaleDependentLabelRenderer(); foreach (ILabelRenderer renderer in this.Renderers) { scaleDependentRenderer.Renderers.Add(renderer.Clone() as ILabelRenderer); } return scaleDependentRenderer; } #endregion #region IClone2 Member public object Clone(IDisplay display) { ScaleDependentLabelRenderer scaledependentRenderer = new ScaleDependentLabelRenderer(); foreach (ILabelRenderer renderer in _renderers) { if (renderer == null) continue; scaledependentRenderer._renderers.Add(renderer.Clone(display) as ILabelRenderer); } return scaledependentRenderer; } public void Release() { foreach (ILabelRenderer renderer in _renderers) { if (renderer == null) continue; renderer.Release(); } _renderers.Clear(); } #endregion #region IPropertyPage Member public object PropertyPage(object initObject) { if (!(initObject is IFeatureLayer)) return null; try { string appPath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); Assembly uiAssembly = Assembly.LoadFrom(appPath + @"\gView.Carto.Rendering.UI.dll"); IPropertyPanel2 p = uiAssembly.CreateInstance("gView.Framework.Carto.Rendering.UI.PropertyForm_LabelGroupRenderer") as IPropertyPanel2; if (p != null) { return p.PropertyPanel(this, (IFeatureLayer)initObject); } } catch (Exception ex) { } return null; } public object PropertyPageObject() { return this; } #endregion #region ILegendGroup Member public int LegendItemCount { get { int count = 0; foreach (ILabelRenderer renderer in _renderers) { if (!(renderer is ILegendGroup)) continue; count += ((ILegendGroup)renderer).LegendItemCount; } return count; } } public ILegendItem LegendItem(int index) { int count = 0; foreach (ILabelRenderer renderer in _renderers) { if (!(renderer is ILegendGroup)) continue; if (count + ((ILegendGroup)renderer).LegendItemCount > index) { return ((ILegendGroup)renderer).LegendItem(index - count); } count += ((ILegendGroup)renderer).LegendItemCount; } return null; } public void SetSymbol(ILegendItem item, ISymbol symbol) { foreach (ILabelRenderer renderer in _renderers) { if (!(renderer is ILegendGroup)) continue; int count = ((ILegendGroup)renderer).LegendItemCount; for (int i = 0; i < count; i++) { if (((ILegendGroup)renderer).LegendItem(i) == item) { ((ILegendGroup)renderer).SetSymbol(item, symbol); return; } } } } #endregion private class RendererList : List<ILabelRenderer>, ILabelRendererGroup { public new void Add(ILabelRenderer renderer) { if (renderer == null) return; if (renderer is ScaleRenderer) { base.Add(renderer); } else { base.Add(new ScaleRenderer(renderer)); } } } private class ScaleRendererPersist : IPersistable { ScaleRenderer _renderer; public ScaleRendererPersist(ScaleRenderer scaleRenderer) { _renderer = scaleRenderer; } internal ScaleRenderer ScaleRenderer { get { return _renderer; } } #region IPersistable Member public void Load(IPersistStream stream) { if (_renderer == null) return; _renderer.MinimumScale = (double)stream.Load("MinScale", 0.0); _renderer.MaximumScale = (double)stream.Load("MaxScale", 0.0); _renderer.Renderer = stream.Load("Renderer", null) as ILabelRenderer; } public void Save(IPersistStream stream) { if (_renderer == null) return; stream.Save("MinScale", _renderer.MinimumScale); stream.Save("MaxScale", _renderer.MaximumScale); stream.Save("Renderer", _renderer.Renderer); } #endregion } private class ScaleRenderer : ILabelRenderer, ILegendGroup, IScaledependent, IPropertyPage { private ILabelRenderer _renderer = null; private double _minScale = 0, _maxScale = 0; public ScaleRenderer(ILabelRenderer renderer) { _renderer = renderer; } public ScaleRenderer(ILabelRenderer renderer, double minScale, double maxScale) : this(renderer) { _minScale = minScale; _maxScale = maxScale; } internal ILabelRenderer Renderer { get { return _renderer; } set { _renderer = value; } } #region IScaledependent public double MinimumScale { get { return _minScale; } set { _minScale = value; } } public double MaximumScale { get { return _maxScale; } set { _maxScale = value; } } #endregion #region ILabelRenderer Member public void PrepareQueryFilter(IDisplay display, gView.Framework.Data.IFeatureLayer layer, gView.Framework.Data.IQueryFilter filter) { if (_renderer != null) _renderer.PrepareQueryFilter(display, layer, filter); } public bool CanRender(gView.Framework.Data.IFeatureLayer layer, IMap map) { if (_renderer != null) return _renderer.CanRender(layer, map); return false; } public string Name { get { if (_renderer != null) return _renderer.Name; return "???"; } } public LabelRenderMode RenderMode { get { if (_renderer != null) return _renderer.RenderMode; return LabelRenderMode.UseRenderPriority; } } public int RenderPriority { get { if (_renderer != null) return _renderer.RenderPriority; return 0; } } public void Draw(IDisplay disp, gView.Framework.Data.IFeature feature) { if (_renderer == null) return; if (this.MinimumScale > 1 && this.MinimumScale > disp.mapScale) return; if (this.MaximumScale > 1 && this.MaximumScale < disp.mapScale) return; _renderer.Draw(disp, feature); } #endregion #region IgViewExtension Member public Guid GUID { get { return PlugInManager.PlugInID(_renderer); } } #endregion #region IPersistable Member public void Load(gView.Framework.IO.IPersistStream stream) { ScaleRendererPersist persist = new ScaleRendererPersist(this); persist.Load(stream); } public void Save(gView.Framework.IO.IPersistStream stream) { ScaleRendererPersist persist = new ScaleRendererPersist(this); persist.Save(stream); } #endregion #region IClone Member public object Clone() { ILabelRenderer renderer = _renderer.Clone() as ILabelRenderer; ScaleRenderer scaleRenderer = new ScaleRenderer(renderer); scaleRenderer._minScale = _minScale; scaleRenderer._maxScale = _maxScale; return scaleRenderer; } #endregion #region IClone2 Member public object Clone(IDisplay display) { if (_renderer == null) return null; ILabelRenderer renderer = _renderer.Clone(display) as ILabelRenderer; if (renderer == null) return null; ScaleRenderer scaleRenderer = new ScaleRenderer(renderer); scaleRenderer._minScale = _minScale; scaleRenderer._maxScale = _maxScale; return scaleRenderer; } public void Release() { if (_renderer != null) _renderer.Release(); } #endregion #region IPropertyPage Member public object PropertyPage(object initObject) { if (_renderer is IPropertyPage) return ((IPropertyPage)_renderer).PropertyPage(initObject); return null; } public object PropertyPageObject() { if (_renderer is IPropertyPage) return ((IPropertyPage)_renderer).PropertyPageObject(); return null; } #endregion #region ILegendGroup Member public int LegendItemCount { get { if (_renderer is ILegendGroup) return ((ILegendGroup)_renderer).LegendItemCount; return 0; } } public ILegendItem LegendItem(int index) { if (_renderer is ILegendGroup) return ((ILegendGroup)_renderer).LegendItem(index); return null; } public void SetSymbol(ILegendItem item, ISymbol symbol) { if (_renderer is ILegendGroup) ((ILegendGroup)_renderer).SetSymbol(item, symbol); } #endregion #region IRenderer Member public List<ISymbol> Symbols { get { if (_renderer != null) return _renderer.Symbols; return new List<ISymbol>(); } } public bool Combine(IRenderer renderer) { return false; } #endregion } #region IRenderer Member public List<ISymbol> Symbols { get { List<ISymbol> symbols = new List<ISymbol>(); if (_renderers != null) { foreach (IRenderer renderer in _renderers) { if (renderer == null) continue; symbols.AddRange(renderer.Symbols); } } return symbols; } } public bool Combine(IRenderer renderer) { return false; } #endregion } }
/* * Copyright (2011) Intel Corporation and Sandia Corporation. Under the * terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the * U.S. Government retains certain rights in this software. * * 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 Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR ITS * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ using System; using System.Collections.Generic; using System.Reflection; using System.Text; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using WaterWars; using WaterWars.Models; using WaterWars.States; using WaterWars.Views.Interactions; using WaterWars.Views.Widgets; using WaterWars.Views.Widgets.Behaviours; namespace WaterWars.Views { public class BuyPointView : WaterWarsView { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); const string WAITING_FOR_GAME_TO_BEGIN_BUY_POINT_STATUS_MSG = "Waiting for game to begin"; const string GAME_ENDED_STATUS_MSG = "Game ended. Thanks for playing!"; const string BUY_POINT_SALE_MSG = "Development rights owned by {0}\nRights price: " + WaterWarsConstants.MONEY_UNIT + "{1}\nTransferable water rights: {2}\nClick me to buy"; const string BUY_POINT_STATUS_MSG = "Development rights owned by {0}\nAssets on parcel: {1}"; public const string GAME_RESETTING_STATUS_MSG = "Game resetting, please wait."; /// <value> /// TEMPORARY STORAGE FOR FIELD VIEWS /// </value> protected Dictionary<UUID, FieldView> m_fieldViews = new Dictionary<UUID, FieldView>(); /// <value> /// Scale of fields. /// </value> protected Vector3 m_fieldViewScale = Vector3.Zero; protected BuyPoint m_bp; BuyPointViewButton m_button; /// <summary> /// List of names to use when changing between different scene objects /// </summary> protected Dictionary<AbstractGameAssetType, string> m_veSceneObjectNames = new Dictionary<AbstractGameAssetType, string>(); public string Status { get { return m_button.LabelBehaviour.Text; } set { m_button.LabelBehaviour.Text = value; } } public BuyPointView(WaterWarsController controller, Scene scene, AbstractView itemStoreView, BuyPoint bp) : base (controller, scene, itemStoreView) { m_bp = bp; m_bp.OnChange += Update; m_veSceneObjectNames[AbstractGameAssetType.None] = "For Sale"; m_veSceneObjectNames[AbstractGameAssetType.Crops] = "Farmhouse"; m_veSceneObjectNames[AbstractGameAssetType.Houses] = "Site Office"; m_veSceneObjectNames[AbstractGameAssetType.Factory] = "Portacabin"; } public override void Close() { m_bp.OnChange -= Update; } public override void Initialize(Vector3 pos) { // m_log.InfoFormat("[WATER WARS]: Creating BuyPointView at {0}", pos); TaskInventoryItem item = GetItem(m_itemStoreView, m_veSceneObjectNames[AbstractGameAssetType.None]); SceneObjectGroup so = m_scene.RezObject( m_itemStoreView.RootPart, item, pos, Quaternion.Identity, Vector3.Zero, 0); // m_log.InfoFormat("[WATER WARS]: Created scene object with name {0}", so.Name); Initialize(so); // We can only reposition after we've passed the scene object up to the parent class so.AbsolutePosition = FindOnGroundPosition(so); so.SendGroupFullUpdate(); // FIXME: We have to do this manually right now but really it's the responsibilty of OpenSim. so.CreateScriptInstances(0, true, m_scene.DefaultScriptEngine, 0); } public override void Initialize(SceneObjectPart rootPart) { base.Initialize(rootPart); m_button.Initialize(m_bp); } protected override void RegisterPart(SceneObjectPart part) { if (part.IsRoot) m_button = new BuyPointViewButton(m_controller, part); } protected void Update(AbstractModel model) { // m_log.InfoFormat("RECEIVED UPDATE FROM BUYPOINT"); RootPart.Name = m_bp.Name; RootPart.OwnerID = m_bp.DevelopmentRightsOwner.Uuid; GameStateType state = m_controller.Game.State; if (state == GameStateType.Registration) { Status = WAITING_FOR_GAME_TO_BEGIN_BUY_POINT_STATUS_MSG; } else if (state == GameStateType.Build) { if (m_bp.HasAnyOwner) { Status = string.Format( BUY_POINT_STATUS_MSG, m_bp.DevelopmentRightsOwner.Name, m_bp.GameAssets.Count); } else { Status = string.Format( BUY_POINT_SALE_MSG, m_bp.DevelopmentRightsOwner.Name, m_bp.CombinedPrice, m_bp.InitialWaterRights); } } else if (state == GameStateType.Water) { Status = string.Format( BUY_POINT_STATUS_MSG, m_bp.DevelopmentRightsOwner.Name, m_bp.GameAssets.Count); } else if (state == GameStateType.Game_Ended) { Status = GAME_ENDED_STATUS_MSG; } else if (state == GameStateType.Game_Resetting) { Status = GAME_RESETTING_STATUS_MSG; } } /// <summary> /// Change the specialization presentation of this buy point view /// </summary> /// <param name="assetType"></param> /// <param name="fields">Fields for which field views need to be created</param> public Dictionary<UUID, FieldView> ChangeSpecialization(AbstractGameAssetType assetType, List<Field> fields) { Dictionary<UUID, FieldView> fvs = new Dictionary<UUID, FieldView>(); string morphItemName = m_veSceneObjectNames[assetType]; ChangeSceneObject(m_itemStoreView, morphItemName); m_bp.Name = morphItemName; if (assetType != AbstractGameAssetType.None) { Vector3 p1, p2; WaterWarsUtils.FindSquareParcelCorners(m_bp.Location.Parcel, out p1, out p2); // m_log.InfoFormat("[WATER WARS]: Found corners of parcel at ({0}),({1})", p1, p2); int shortDimension = (int)Math.Floor(Math.Sqrt(fields.Count)); int longDimension = (int)Math.Ceiling((float)fields.Count / shortDimension); // m_log.InfoFormat("[WATER WARS]: Would space as [{0}][{1}]", shortDimension, longDimension); // XXX: For now, we're always going to short space the fields on the x axis // This shouldn't be a problem if all our regions are square but might start to look a bit odd if they // were different rectangular sizes // Adjust dimensions to leave a gap around the edges for the buypoint p1.X += 5; p1.Y += 5; p2.X -= 5; p2.Y -= 5; float xSpacing = (p2.X - p1.X) / (float)shortDimension; float ySpacing = (p2.Y - p1.Y) / (float)longDimension; List<Vector3> placementPoints = new List<Vector3>(); // for (int y = y1; y < y2; y += ySpacing) // { // for (float x = x1; x < x2; x += xSpacing) // { // placementPoints.Add(new Vector3(x, y, (float)heightHere + 0.1f)); // } // } for (int y = 0; y < longDimension; y++) { for (float x = 0; x < shortDimension; x++) { Vector3 spacing = new Vector3(x * xSpacing, y * ySpacing, 2f); placementPoints.Add(p1 + spacing); } } m_fieldViewScale = new Vector3(xSpacing, ySpacing, 0.1f); Vector3 placementAdjustment = new Vector3(xSpacing / 2, ySpacing / 2, 0); int i = 0; foreach (Vector3 v in placementPoints) { FieldView fv = CreateFieldView(fields[i++], v + placementAdjustment); fvs.Add(fv.RootPart.UUID, fv); } } else { lock (m_fieldViews) { foreach (FieldView fv in m_fieldViews.Values) fv.Close(); m_fieldViews.Clear(); } } return fvs; } /// <summary> /// Create a field view at the given position. /// </summary> /// <param name="pos"></param> /// <returns></returns> public FieldView CreateFieldView(SceneObjectGroup so) { // We could register an existing field here if we wanted to. FieldView fv = new FieldView( m_controller, m_scene, new Field(so.RootPart.UUID, "FieldToDelete"), m_fieldViewScale, m_itemStoreView); fv.Initialize(so); lock (m_fieldViews) m_fieldViews.Add(fv.Uuid, fv); return fv; } /// <summary> /// Create a field view at the given position. /// </summary> /// <param name="field"></param> /// <param name="pos"></param> /// <returns></returns> public FieldView CreateFieldView(Field f, Vector3 pos) { // m_log.InfoFormat("[WATER WARS]: Placing field {0} at {1}", name, pos); FieldView fv = new FieldView(m_controller, m_scene, f, m_fieldViewScale, m_itemStoreView); fv.Initialize(pos); lock (m_fieldViews) m_fieldViews.Add(fv.Uuid, fv); return fv; } /// <summary> /// Create a game asset view /// </summary> /// <param name="asset"></param> /// <returns>A view that doesn't have a link to the model. The caller needs to link this subsequently</returns> public GameAssetView CreateGameAssetView(AbstractGameAsset asset) { GameAssetView v = null; FieldView fv = m_fieldViews[asset.Field.Uuid]; Vector3 pos = fv.RootPart.AbsolutePosition; if (asset.Type == AbstractGameAssetType.Factory) v = new FactoryView(m_controller, m_scene, asset, m_itemStoreView); else if (asset.Type == AbstractGameAssetType.Houses) v = new HousesView(m_controller, m_scene, asset, m_itemStoreView); else if (asset.Type == AbstractGameAssetType.Crops) v = new CropsView(m_controller, m_scene, asset, m_itemStoreView); else throw new Exception(string.Format("Unrecognized asset type {0} at position {1}", asset.Type, pos)); fv.Close(); m_fieldViews.Remove(asset.Field.Uuid); v.Initialize(pos); return v; } /// <summary> /// Fetch game configuration. /// </summary> /// <returns></returns> public string FetchConfiguration() { return m_button.FetchConfiguration(); } public override void ChangeSceneObject(AbstractView newObjectContainer, string newObjectName) { base.ChangeSceneObject(newObjectContainer, newObjectName); m_button.ResetButtonPrims(); } /// <summary> /// Handle buy point activities /// </summary> class BuyPointViewButton : WaterWarsButton { protected BuyPoint m_bp; public BuyPointViewButton(WaterWarsController controller, SceneObjectPart part) : base(controller, part, 4600, new FixedTextureBehaviour()) { Enabled = true; OnClick += delegate(Vector3 offsetPos, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs) { Util.FireAndForget( delegate { controller.ViewerWebServices.PlayerServices.SetLastSelected( remoteClient.AgentId, m_bp); }); }; } public void Initialize(BuyPoint bp) { m_bp = bp; } public string FetchConfiguration() { return base.FetchConfiguration(WaterWarsConstants.REGISTRATION_INI_NAME); } // protected override AbstractInteraction CreateInteraction(IClientAPI remoteClient) // { // return new BuyPointInteraction(m_controller, this, remoteClient.AgentId, m_bp); // } } } }
using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Orleans.CodeGenerator.Model; using Orleans.CodeGenerator.Utilities; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace Orleans.CodeGenerator.Generators { /// <summary> /// Generates IGrainMethodInvoker implementations for grains. /// </summary> internal class GrainMethodInvokerGenerator { private readonly CodeGeneratorOptions options; private readonly WellKnownTypes wellKnownTypes; /// <summary> /// The next id used for generated code disambiguation purposes. /// </summary> private int nextId; public GrainMethodInvokerGenerator(CodeGeneratorOptions options, WellKnownTypes wellKnownTypes) { this.options = options; this.wellKnownTypes = wellKnownTypes; } /// <summary> /// Returns the name of the generated class for the provided type. /// </summary> internal static string GetGeneratedClassName(INamedTypeSymbol type) => CodeGenerator.ToolName + type.GetSuitableClassName() + "MethodInvoker"; /// <summary> /// Generates the class for the provided grain types. /// </summary> internal TypeDeclarationSyntax GenerateClass(GrainInterfaceDescription description) { var generatedTypeName = description.InvokerTypeName; var grainType = description.Type; var baseTypes = new List<BaseTypeSyntax> { SimpleBaseType(wellKnownTypes.IGrainMethodInvoker.ToTypeSyntax()) }; var genericTypes = grainType.GetHierarchyTypeParameters() .Select(_ => TypeParameter(_.ToString())) .ToArray(); // Create the special method invoker marker attribute. var interfaceId = description.InterfaceId; var interfaceIdArgument = interfaceId.ToHexLiteral(); var grainTypeArgument = TypeOfExpression(grainType.WithoutTypeParameters().ToTypeSyntax()); var attributes = new List<AttributeSyntax> { GeneratedCodeAttributeGenerator.GetGeneratedCodeAttributeSyntax(wellKnownTypes), Attribute(wellKnownTypes.MethodInvokerAttribute.ToNameSyntax()) .AddArgumentListArguments( AttributeArgument(grainTypeArgument), AttributeArgument(interfaceIdArgument)), Attribute(wellKnownTypes.ExcludeFromCodeCoverageAttribute.ToNameSyntax()) }; var genericInvokerFields = GenerateGenericInvokerFields(wellKnownTypes, description.Methods); var members = new List<MemberDeclarationSyntax>(genericInvokerFields.Values.Select(x => x.Declaration)) { GenerateInvokeMethod(wellKnownTypes, grainType, genericInvokerFields), GenerateInterfaceTypeProperty(wellKnownTypes, description, genericTypes), GenerateGetTargetMethod(wellKnownTypes, description) }; // If this is an IGrainExtension, make the generated class implement IGrainExtensionMethodInvoker. if (grainType.HasInterface(wellKnownTypes.IGrainExtension)) { baseTypes.Add(SimpleBaseType(wellKnownTypes.IGrainExtensionMethodInvoker.ToTypeSyntax())); } var classDeclaration = ClassDeclaration(generatedTypeName) .AddModifiers(Token(SyntaxKind.InternalKeyword)) .AddBaseListTypes(baseTypes.ToArray()) .AddConstraintClauses(grainType.GetTypeConstraintSyntax()) .AddMembers(members.ToArray()) .AddAttributeLists(AttributeList().AddAttributes(attributes.ToArray())); if (genericTypes.Length > 0) { classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes); } if (this.options.DebuggerStepThrough) { var debuggerStepThroughAttribute = Attribute(this.wellKnownTypes.DebuggerStepThroughAttribute.ToNameSyntax()); classDeclaration = classDeclaration.AddAttributeLists(AttributeList().AddAttributes(debuggerStepThroughAttribute)); } return classDeclaration; } /// <summary> /// Generates syntax for the IGrainMethodInvoker.Invoke method. /// </summary> private MethodDeclarationSyntax GenerateInvokeMethod( WellKnownTypes wellKnownTypes, INamedTypeSymbol grainType, Dictionary<IMethodSymbol, GenericInvokerField> genericInvokerFields) { // Get the method with the correct type. var invokeMethod = wellKnownTypes.IGrainMethodInvoker.Method("Invoke", wellKnownTypes.IGrainContext, wellKnownTypes.InvokeMethodRequest); return GenerateInvokeMethod(wellKnownTypes, grainType, invokeMethod, genericInvokerFields); } /// <summary> /// Generates syntax for an invoke method. /// </summary> private MethodDeclarationSyntax GenerateInvokeMethod( WellKnownTypes wellKnownTypes, INamedTypeSymbol grainType, IMethodSymbol invokeMethod, Dictionary<IMethodSymbol, GenericInvokerField> genericInvokerFields) { var parameters = invokeMethod.Parameters; var grainArgument = parameters[0].Name.ToIdentifierName(); var requestArgument = parameters[1].Name.ToIdentifierName(); var interfaceIdProperty = wellKnownTypes.InvokeMethodRequest.Property("InterfaceTypeCode"); var methodIdProperty = wellKnownTypes.InvokeMethodRequest.Property("MethodId"); var argumentsProperty = wellKnownTypes.InvokeMethodRequest.Property("Arguments"); // Store the relevant values from the request in local variables. var interfaceIdDeclaration = LocalDeclarationStatement( VariableDeclaration(wellKnownTypes.Int32.ToTypeSyntax()) .AddVariables( VariableDeclarator("interfaceTypeCode") .WithInitializer(EqualsValueClause(requestArgument.Member(interfaceIdProperty.Name))))); var interfaceIdVariable = IdentifierName("interfaceTypeCode"); var methodIdDeclaration = LocalDeclarationStatement( VariableDeclaration(wellKnownTypes.Int32.ToTypeSyntax()) .AddVariables( VariableDeclarator("methodId") .WithInitializer(EqualsValueClause(requestArgument.Member(methodIdProperty.Name))))); var methodIdVariable = IdentifierName("methodId"); var argumentsDeclaration = LocalDeclarationStatement( VariableDeclaration(IdentifierName("var")) .AddVariables( VariableDeclarator("arguments") .WithInitializer(EqualsValueClause(requestArgument.Member(argumentsProperty.Name))))); var argumentsVariable = IdentifierName("arguments"); var methodDeclaration = invokeMethod.GetDeclarationSyntax() .AddModifiers(Token(SyntaxKind.AsyncKeyword)) .AddBodyStatements(interfaceIdDeclaration, methodIdDeclaration, argumentsDeclaration); var callThrowMethodNotImplemented = InvocationExpression(IdentifierName("ThrowMethodNotImplemented")) .WithArgumentList(ArgumentList(SeparatedList(new[] { Argument(interfaceIdVariable), Argument(methodIdVariable) }))); // This method is used directly after its declaration to create blocks for each interface id, comprising // primarily of a nested switch statement for each of the methods in the given interface. BlockSyntax ComposeInterfaceBlock(INamedTypeSymbol interfaceType, SwitchStatementSyntax methodSwitch) { ExpressionSyntax targetObject; if (grainType.HasInterface(wellKnownTypes.IGrainExtension)) { targetObject = InvocationExpression(grainArgument.Member("GetGrainExtension", interfaceType), ArgumentList()); } else { targetObject = grainArgument.Member("GrainInstance"); } var typedGrainDeclaration = LocalDeclarationStatement( VariableDeclaration(IdentifierName("var")) .AddVariables( VariableDeclarator("casted") .WithInitializer(EqualsValueClause(ParenthesizedExpression(CastExpression(interfaceType.ToTypeSyntax(), targetObject)))))); return Block(typedGrainDeclaration, methodSwitch.AddSections(SwitchSection() .AddLabels(DefaultSwitchLabel()) .AddStatements( ExpressionStatement(callThrowMethodNotImplemented), ReturnStatement(LiteralExpression(SyntaxKind.NullLiteralExpression))))); } var interfaceCases = GrainInterfaceCommon.GenerateGrainInterfaceAndMethodSwitch( wellKnownTypes, grainType, methodIdVariable, methodType => GenerateInvokeForMethod(wellKnownTypes, IdentifierName("casted"), methodType, argumentsVariable, genericInvokerFields), ComposeInterfaceBlock); var throwInterfaceNotImplemented = GrainInterfaceCommon.GenerateMethodNotImplementedFunction(wellKnownTypes); var throwMethodNotImplemented = GrainInterfaceCommon.GenerateInterfaceNotImplementedFunction(wellKnownTypes); // Generate the default case, which will call the above local function to throw . var callThrowInterfaceNotImplemented = InvocationExpression(IdentifierName("ThrowInterfaceNotImplemented")) .WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(interfaceIdVariable)))); var defaultCase = SwitchSection() .AddLabels(DefaultSwitchLabel()) .AddStatements( ExpressionStatement(callThrowInterfaceNotImplemented), ReturnStatement(LiteralExpression(SyntaxKind.NullLiteralExpression))); var interfaceIdSwitch = SwitchStatement(interfaceIdVariable).AddSections(interfaceCases.ToArray()).AddSections(defaultCase); return methodDeclaration.AddBodyStatements(interfaceIdSwitch, throwInterfaceNotImplemented, throwMethodNotImplemented); } /// <summary> /// Generates syntax to invoke a method on a grain. /// </summary> private StatementSyntax[] GenerateInvokeForMethod( WellKnownTypes wellKnownTypes, ExpressionSyntax castGrain, IMethodSymbol method, ExpressionSyntax arguments, Dictionary<IMethodSymbol, GenericInvokerField> genericInvokerFields) { // Construct expressions to retrieve each of the method's parameters. var parameters = new List<ExpressionSyntax>(); var methodParameters = method.Parameters.ToList(); for (var i = 0; i < methodParameters.Count; i++) { var parameter = methodParameters[i]; var parameterType = parameter.Type.ToTypeSyntax(); var indexArg = Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(i))); var arg = CastExpression( parameterType, ElementAccessExpression(arguments).AddArgumentListArguments(indexArg)); parameters.Add(arg); } // If the method is a generic method definition, use the generic method invoker field to invoke the method. if (method.IsGenericMethod) { var invokerFieldName = genericInvokerFields[method].FieldName; var invokerCall = InvocationExpression( IdentifierName(invokerFieldName) .Member(wellKnownTypes.IGrainMethodInvoker.Method("Invoke").Name)) .AddArgumentListArguments(Argument(castGrain), Argument(arguments)); return new StatementSyntax[] { ReturnStatement(AwaitExpression(invokerCall)) }; } // Invoke the method. var grainMethodCall = InvocationExpression(castGrain.Member(method.Name)) .AddArgumentListArguments(parameters.Select(Argument).ToArray()); // For void methods, invoke the method and return null. if (method.ReturnsVoid) { return new StatementSyntax[] { ExpressionStatement(grainMethodCall), ReturnStatement(LiteralExpression(SyntaxKind.NullLiteralExpression)) }; } // For methods which return an awaitable type which has no result type, await the method and return null. if (method.ReturnType.Method("GetAwaiter").ReturnType.Method("GetResult").ReturnsVoid) { return new StatementSyntax[] { ExpressionStatement(AwaitExpression(grainMethodCall)), ReturnStatement(LiteralExpression(SyntaxKind.NullLiteralExpression)) }; } return new StatementSyntax[] { ReturnStatement(AwaitExpression(grainMethodCall)) }; } /// <summary> /// Generates GenericMethodInvoker fields for the generic methods in <paramref name="methodDescriptions"/>. /// </summary> private Dictionary<IMethodSymbol, GenericInvokerField> GenerateGenericInvokerFields(WellKnownTypes wellKnownTypes, List<GrainMethodDescription> methodDescriptions) { if (!(wellKnownTypes.GenericMethodInvoker is WellKnownTypes.Some genericMethodInvoker)) return new Dictionary<IMethodSymbol, GenericInvokerField>(SymbolEqualityComparer.Default); var result = new Dictionary<IMethodSymbol, GenericInvokerField>(methodDescriptions.Count, SymbolEqualityComparer.Default); foreach (var description in methodDescriptions) { var method = description.Method; if (!method.IsGenericMethod) continue; result[method] = GenerateGenericInvokerField(method, genericMethodInvoker.Value); } return result; } /// <summary> /// Generates a GenericMethodInvoker field for the provided generic method. /// </summary> private GenericInvokerField GenerateGenericInvokerField(IMethodSymbol method, INamedTypeSymbol genericMethodInvoker) { var fieldName = $"GenericInvoker_{method.Name}_{Interlocked.Increment(ref nextId):X}"; var fieldInfoVariable = VariableDeclarator(fieldName) .WithInitializer( EqualsValueClause( ObjectCreationExpression(genericMethodInvoker.ToTypeSyntax()) .AddArgumentListArguments( Argument(TypeOfExpression(method.ContainingType.ToTypeSyntax())), Argument(method.Name.ToLiteralExpression()), Argument( LiteralExpression( SyntaxKind.NumericLiteralExpression, Literal(method.TypeArguments.Length)))))); var declaration = FieldDeclaration( VariableDeclaration(genericMethodInvoker.ToTypeSyntax()).AddVariables(fieldInfoVariable)) .AddModifiers( Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.StaticKeyword), Token(SyntaxKind.ReadOnlyKeyword)); return new GenericInvokerField(fieldName, declaration); } private PropertyDeclarationSyntax GenerateInterfaceTypeProperty(WellKnownTypes wellKnownTypes, GrainInterfaceDescription description, TypeParameterSyntax[] genericTypes) { var property = wellKnownTypes.IGrainMethodInvoker.Property("InterfaceType"); var returnValue = TypeOfExpression(description.Type.ToTypeSyntax()); return PropertyDeclaration(wellKnownTypes.Type.ToTypeSyntax(), property.Name) .WithExpressionBody(ArrowExpressionClause(returnValue)) .AddModifiers(Token(SyntaxKind.PublicKeyword)) .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); } private MethodDeclarationSyntax GenerateGetTargetMethod(WellKnownTypes wellKnownTypes, GrainInterfaceDescription description) { var method = wellKnownTypes.IGrainMethodInvoker.Method("GetTarget"); var grainContextParameter = method.Parameters[0].Name.ToIdentifierName(); ExpressionSyntax returnValue; if (description.Type.HasInterface(wellKnownTypes.IGrainExtension)) { returnValue = InvocationExpression(grainContextParameter.Member("GetGrainExtension", description.Type), ArgumentList()); } else { returnValue = grainContextParameter.Member("GrainInstance"); } return method.GetDeclarationSyntax() .WithExpressionBody(ArrowExpressionClause(returnValue)) .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); } private readonly struct GenericInvokerField { public GenericInvokerField(string fieldName, MemberDeclarationSyntax declaration) { this.FieldName = fieldName; this.Declaration = declaration; } public string FieldName { get; } public MemberDeclarationSyntax Declaration { get; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Threading.Tasks; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Threading.Tests { public class MutexTests : FileCleanupTestBase { [Fact] public void Ctor_ConstructWaitRelease() { using (Mutex m = new Mutex()) { m.CheckedWait(); m.ReleaseMutex(); } using (Mutex m = new Mutex(false)) { m.CheckedWait(); m.ReleaseMutex(); } using (Mutex m = new Mutex(true)) { m.CheckedWait(); m.ReleaseMutex(); m.ReleaseMutex(); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void Ctor_InvalidNames_Unix() { AssertExtensions.Throws<ArgumentException>("name", null, () => new Mutex(false, new string('a', 1000), out bool createdNew)); } [Theory] [MemberData(nameof(GetValidNames))] public void Ctor_ValidName(string name) { bool createdNew; using (Mutex m1 = new Mutex(false, name, out createdNew)) { Assert.True(createdNew); using (Mutex m2 = new Mutex(false, name, out createdNew)) { Assert.False(createdNew); } } } [PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix [Fact] public void Ctor_NameUsedByOtherSynchronizationPrimitive_Windows() { string name = Guid.NewGuid().ToString("N"); using (Semaphore s = new Semaphore(1, 1, name)) { Assert.Throws<WaitHandleCannotBeOpenedException>(() => new Mutex(false, name)); } } [PlatformSpecific(TestPlatforms.Windows)] [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotInAppContainer))] // Can't create global objects in appcontainer public void Ctor_ImpersonateAnonymousAndTryCreateGlobalMutexTest() { ThreadTestHelpers.RunTestInBackgroundThread(() => { if (!ImpersonateAnonymousToken(GetCurrentThread())) { // Impersonation is not allowed in the current context, this test is inappropriate in such a case return; } Assert.Throws<UnauthorizedAccessException>(() => new Mutex(false, "Global\\" + Guid.NewGuid().ToString("N"))); Assert.True(RevertToSelf()); }); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsInAppContainer))] // Can't create global objects in appcontainer [PlatformSpecific(TestPlatforms.Windows)] public void Ctor_TryCreateGlobalMutexTest_Uwp() { ThreadTestHelpers.RunTestInBackgroundThread(() => Assert.Throws<UnauthorizedAccessException>(() => new Mutex(false, "Global\\" + Guid.NewGuid().ToString("N")))); } [Theory] [MemberData(nameof(GetValidNames))] public void OpenExisting(string name) { Mutex resultHandle; Assert.False(Mutex.TryOpenExisting(name, out resultHandle)); using (Mutex m1 = new Mutex(false, name)) { using (Mutex m2 = Mutex.OpenExisting(name)) { m1.CheckedWait(); Assert.False(Task.Factory.StartNew(() => m2.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result); m1.ReleaseMutex(); m2.CheckedWait(); Assert.False(Task.Factory.StartNew(() => m1.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result); m2.ReleaseMutex(); } Assert.True(Mutex.TryOpenExisting(name, out resultHandle)); Assert.NotNull(resultHandle); resultHandle.Dispose(); } } [Fact] public void OpenExisting_InvalidNames() { AssertExtensions.Throws<ArgumentNullException>("name", () => Mutex.OpenExisting(null)); AssertExtensions.Throws<ArgumentException>("name", null, () => Mutex.OpenExisting(string.Empty)); } [Fact] public void OpenExisting_UnavailableName() { string name = Guid.NewGuid().ToString("N"); Assert.Throws<WaitHandleCannotBeOpenedException>(() => Mutex.OpenExisting(name)); Mutex ignored; Assert.False(Mutex.TryOpenExisting(name, out ignored)); } [PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix [Fact] public void OpenExisting_NameUsedByOtherSynchronizationPrimitive_Windows() { string name = Guid.NewGuid().ToString("N"); using (Semaphore sema = new Semaphore(1, 1, name)) { Assert.Throws<WaitHandleCannotBeOpenedException>(() => Mutex.OpenExisting(name)); Mutex ignored; Assert.False(Mutex.TryOpenExisting(name, out ignored)); } } private static IEnumerable<string> GetNamePrefixes() { yield return string.Empty; yield return "Local\\"; // Creating global sync objects is not allowed in UWP apps if (!PlatformDetection.IsUap) { yield return "Global\\"; } } public static IEnumerable<object[]> AbandonExisting_MemberData() { var nameGuidStr = Guid.NewGuid().ToString("N"); for (int waitType = 0; waitType < 2; ++waitType) // 0 == WaitOne, 1 == WaitAny { yield return new object[] { null, waitType }; foreach (var namePrefix in GetNamePrefixes()) { yield return new object[] { namePrefix + nameGuidStr, waitType }; } } } [Theory] [MemberData(nameof(AbandonExisting_MemberData))] public void AbandonExisting(string name, int waitType) { ThreadTestHelpers.RunTestInBackgroundThread(() => { using (var m = new Mutex(false, name)) { Task t = Task.Factory.StartNew(() => { m.CheckedWait(); // don't release the mutex; abandon it on this thread }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); t.CheckedWait(); switch (waitType) { case 0: // WaitOne Assert.Throws<AbandonedMutexException>(() => m.CheckedWait()); break; case 1: // WaitAny AbandonedMutexException ame = Assert.Throws<AbandonedMutexException>( () => WaitHandle.WaitAny(new[] { m }, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); Assert.Equal(0, ame.MutexIndex); Assert.Equal(m, ame.Mutex); break; } } }); } public static IEnumerable<object[]> CrossProcess_NamedMutex_ProtectedFileAccessAtomic_MemberData() { var nameGuidStr = Guid.NewGuid().ToString("N"); foreach (var namePrefix in GetNamePrefixes()) { yield return new object[] { namePrefix + nameGuidStr }; } } [ActiveIssue(34666)] [Theory] [MemberData(nameof(CrossProcess_NamedMutex_ProtectedFileAccessAtomic_MemberData))] public void CrossProcess_NamedMutex_ProtectedFileAccessAtomic(string prefix) { ThreadTestHelpers.RunTestInBackgroundThread(() => { string mutexName = prefix + Guid.NewGuid().ToString("N"); string fileName = GetTestFilePath(); Func<string, string, int> otherProcess = (m, f) => { using (var mutex = Mutex.OpenExisting(m)) { mutex.CheckedWait(); try { File.WriteAllText(f, "0"); } finally { mutex.ReleaseMutex(); } IncrementValueInFileNTimes(mutex, f, 10); } return RemoteExecutor.SuccessExitCode; }; using (var mutex = new Mutex(false, mutexName)) using (var remote = RemoteExecutor.Invoke(otherProcess, mutexName, fileName)) { SpinWait.SpinUntil(() => File.Exists(fileName), ThreadTestHelpers.UnexpectedTimeoutMilliseconds); IncrementValueInFileNTimes(mutex, fileName, 10); } Assert.Equal(20, int.Parse(File.ReadAllText(fileName))); }); } private static void IncrementValueInFileNTimes(Mutex mutex, string fileName, int n) { for (int i = 0; i < n; i++) { mutex.CheckedWait(); try { int current = int.Parse(File.ReadAllText(fileName)); Thread.Sleep(10); File.WriteAllText(fileName, (current + 1).ToString()); } finally { mutex.ReleaseMutex(); } } } public static TheoryData<string> GetValidNames() { var names = new TheoryData<string>() { Guid.NewGuid().ToString("N") }; if (PlatformDetection.IsWindows) names.Add(Guid.NewGuid().ToString("N") + new string('a', 1000)); return names; } [DllImport("kernel32.dll")] private static extern IntPtr GetCurrentThread(); [DllImport("advapi32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool ImpersonateAnonymousToken(IntPtr threadHandle); [DllImport("advapi32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool RevertToSelf(); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// SubnetsOperations operations. /// </summary> internal partial class SubnetsOperations : IServiceOperations<NetworkManagementClient>, ISubnetsOperations { /// <summary> /// Initializes a new instance of the SubnetsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal SubnetsOperations(NetworkManagementClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// The delete subnet operation deletes the specified subnet. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync( resourceGroupName, virtualNetworkName, subnetName, customHeaders, cancellationToken); return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken); } /// <summary> /// The delete subnet operation deletes the specified subnet. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (subnetName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subnetName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("subnetName", subnetName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subnetName}", Uri.EscapeDataString(subnetName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 204 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _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> /// The Get subnet operation retrieves information about the specified subnet. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='expand'> /// expand references resources. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Subnet>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (subnetName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subnetName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("subnetName", subnetName); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subnetName}", Uri.EscapeDataString(subnetName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Subnet>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Subnet>(_responseContent, this.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> /// The Put Subnet operation creates/updates a subnet in the specified virtual /// network /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='subnetParameters'> /// Parameters supplied to the create/update Subnet operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<Subnet>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<Subnet> _response = await BeginCreateOrUpdateWithHttpMessagesAsync( resourceGroupName, virtualNetworkName, subnetName, subnetParameters, customHeaders, cancellationToken); return await this.Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken); } /// <summary> /// The Put Subnet operation creates/updates a subnet in the specified virtual /// network /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='subnetParameters'> /// Parameters supplied to the create/update Subnet operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Subnet>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (subnetName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subnetName"); } if (subnetParameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subnetParameters"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("subnetName", subnetName); tracingParameters.Add("subnetParameters", subnetParameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subnetName}", Uri.EscapeDataString(subnetName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(subnetParameters != null) { _requestContent = SafeJsonConvert.SerializeObject(subnetParameters, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Subnet>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Subnet>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Subnet>(_responseContent, this.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> /// The List subnets operation retrieves all the subnets in a virtual network. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Subnet>>> ListWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Subnet>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<Subnet>>(_responseContent, this.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> /// The List subnets operation retrieves all the subnets in a virtual network. /// </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> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Subnet>>> ListNextWithHttpMessagesAsync(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, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Subnet>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<Subnet>>(_responseContent, this.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; } } }
// // Tests.cs // // Author: // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2009 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #if ENABLE_TESTS using System; using System.Linq; using NUnit.Framework; using GLib; using Banshee.Base; namespace Banshee.IO.Gio { [TestFixture] public class GioTests { private File file = new File (); private Directory dir = new Directory (); private string tmp_dir = System.IO.Path.Combine (System.Environment.CurrentDirectory, "tmp-gio"); private SafeUri foo, baz; private string woo; static GioTests () { GLib.GType.Init (); } [SetUp] public void Setup () { foo = Uri ("foo"); baz = Uri ("baz"); woo = Path ("woo"); System.IO.Directory.CreateDirectory (tmp_dir); System.IO.File.WriteAllText (Path ("foo"), "bar"); System.IO.File.WriteAllText (Path ("baz"), "oof"); System.IO.Directory.CreateDirectory (Path ("woo")); } [TearDown] public void Teardown () { try { System.IO.File.Delete (Path ("foo")); } catch {} try { System.IO.File.Delete (Path ("baz")); } catch {} try { System.IO.Directory.Delete (woo); } catch {} try { System.IO.Directory.Delete (tmp_dir, true); } catch {} } [Test] public void Exists () { Assert.IsTrue (file.Exists (foo)); Assert.IsTrue (file.Exists (baz)); Assert.IsTrue ( dir.Exists (woo)); } [Test] public void DoesntExist () { Assert.IsFalse ( dir.Exists (Path ("foo"))); Assert.IsFalse (file.Exists (Uri ("woo"))); Assert.IsFalse (file.Exists (Uri ("asd"))); } [Test] public void Move () { file.Move (foo, Uri ("fooz")); Assert.IsTrue (file.Exists (Uri ("fooz"))); Assert.IsFalse (file.Exists (foo)); dir.Move (new SafeUri (woo), Uri ("wooz")); Assert.IsTrue (dir.Exists (Path ("wooz"))); Assert.IsFalse (dir.Exists (woo)); } [Test] public void Create () { var newf = Uri ("newfile"); Assert.IsFalse (file.Exists (newf)); file.OpenWrite (newf, false).Close (); Assert.IsTrue (file.Exists (newf)); try { file.OpenWrite (newf, false).Close (); Assert.Fail ("Should have thrown an exception creating already-exists file w/o overwrite"); } catch {} try { file.OpenWrite (newf, true).Close (); } catch { Assert.Fail ("Should not have thrown an exception creating already-exists file w/ overwrite"); } var newd = Path ("newdir"); Assert.IsFalse (dir.Exists (newd)); dir.Create (newd); Assert.IsTrue (dir.Exists (newd)); } [Test] public void DemuxCreateFile () { var newf = Uri ("newfile"); var newp = Path ("newfile"); Assert.IsFalse (file.Exists (newf)); var demux = new DemuxVfs (newp); Assert.IsTrue (demux.IsWritable); Assert.IsTrue (demux.IsReadable); var stream = demux.WriteStream; Assert.IsTrue (stream.CanWrite); stream.WriteByte (0xAB); demux.CloseStream (stream); Assert.IsTrue (file.Exists (newf)); } [Test] public void DemuxOverwriteFile () { Assert.IsTrue (file.Exists (foo)); Assert.AreEqual (3, file.GetSize (foo)); var demux = new DemuxVfs (foo.AbsoluteUri); Assert.IsTrue (demux.IsWritable); Assert.IsTrue (demux.IsReadable); var stream = demux.WriteStream; Assert.IsTrue (stream.CanWrite); // Make sure can read from WriteStream - required by TagLib# // FIXME - depends on glib 2.22 and new gio# - see gio DemuxVfs.cs Assert.AreEqual ((byte)'b', stream.ReadByte (), "Known failure, bug in Gio backend, depends on glib 2.22 for fix"); stream.Position = 0; stream.WriteByte (0xAB); demux.CloseStream (stream); Assert.IsTrue (file.Exists (foo)); Assert.AreEqual (1, file.GetSize (foo)); } [Test] public void DemuxReadFile () { Assert.IsTrue (file.Exists (foo)); var demux = new DemuxVfs (foo.AbsoluteUri); var stream = demux.ReadStream; // foo contains 'bar' Assert.AreEqual ((byte)'b', stream.ReadByte ()); Assert.AreEqual ((byte)'a', stream.ReadByte ()); Assert.AreEqual ((byte)'r', stream.ReadByte ()); demux.CloseStream (stream); } [Test] public void GetFileProperties () { Assert.AreEqual (3, file.GetSize (foo)); Assert.IsTrue (file.GetModifiedTime (foo) > 0); } [Test] public void Delete () { Assert.IsTrue (file.Exists (foo)); file.Delete (foo); Assert.IsFalse (file.Exists (foo)); Assert.IsTrue (dir.Exists (woo)); dir.Delete (woo); Assert.IsFalse (dir.Exists (woo)); } [Test] public void DeleteRecursive () { dir.Delete (tmp_dir, true); } [Test] public void DeleteRecursiveWithoutNativeOptimization () { Directory.DisableNativeOptimizations = true; dir.Delete (tmp_dir, true); Directory.DisableNativeOptimizations = false; } [Test] public void GetChildFiles () { var files = dir.GetFiles (tmp_dir).ToArray (); Assert.AreEqual (files, new string [] { foo.AbsoluteUri, baz.AbsoluteUri }); } [Test] public void GetChildDirs () { var dirs = dir.GetDirectories (tmp_dir).ToArray (); Assert.AreEqual (dirs, new string [] { new SafeUri (woo).AbsoluteUri }); } private SafeUri Uri (string filename) { return new SafeUri (Path (filename)); } private string Path (string filename) { return System.IO.Path.Combine (tmp_dir, filename); } } } #endif
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for LoadBalancersOperations. /// </summary> public static partial class LoadBalancersOperationsExtensions { /// <summary> /// Deletes the specified load balancer. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> public static void Delete(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName) { operations.DeleteAsync(resourceGroupName, loadBalancerName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified load balancer. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, loadBalancerName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified load balancer. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> public static LoadBalancer Get(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, string expand = default(string)) { return operations.GetAsync(resourceGroupName, loadBalancerName, expand).GetAwaiter().GetResult(); } /// <summary> /// Gets the specified load balancer. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<LoadBalancer> GetAsync(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, loadBalancerName, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a load balancer. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update load balancer operation. /// </param> public static LoadBalancer CreateOrUpdate(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, LoadBalancer parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, loadBalancerName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a load balancer. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update load balancer operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<LoadBalancer> CreateOrUpdateAsync(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, LoadBalancer parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, loadBalancerName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the load balancers in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<LoadBalancer> ListAll(this ILoadBalancersOperations operations) { return operations.ListAllAsync().GetAwaiter().GetResult(); } /// <summary> /// Gets all the load balancers in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<LoadBalancer>> ListAllAsync(this ILoadBalancersOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the load balancers in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> public static IPage<LoadBalancer> List(this ILoadBalancersOperations operations, string resourceGroupName) { return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Gets all the load balancers in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<LoadBalancer>> ListAsync(this ILoadBalancersOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified load balancer. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> public static void BeginDelete(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName) { operations.BeginDeleteAsync(resourceGroupName, loadBalancerName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified load balancer. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, loadBalancerName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates or updates a load balancer. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update load balancer operation. /// </param> public static LoadBalancer BeginCreateOrUpdate(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, LoadBalancer parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, loadBalancerName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a load balancer. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update load balancer operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<LoadBalancer> BeginCreateOrUpdateAsync(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, LoadBalancer parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, loadBalancerName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the load balancers in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<LoadBalancer> ListAllNext(this ILoadBalancersOperations operations, string nextPageLink) { return operations.ListAllNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all the load balancers in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<LoadBalancer>> ListAllNextAsync(this ILoadBalancersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the load balancers in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<LoadBalancer> ListNext(this ILoadBalancersOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all the load balancers in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<LoadBalancer>> ListNextAsync(this ILoadBalancersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.DataQnA.V1Alpha { /// <summary>Settings for <see cref="AutoSuggestionServiceClient"/> instances.</summary> public sealed partial class AutoSuggestionServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="AutoSuggestionServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="AutoSuggestionServiceSettings"/>.</returns> public static AutoSuggestionServiceSettings GetDefault() => new AutoSuggestionServiceSettings(); /// <summary> /// Constructs a new <see cref="AutoSuggestionServiceSettings"/> object with default settings. /// </summary> public AutoSuggestionServiceSettings() { } private AutoSuggestionServiceSettings(AutoSuggestionServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); SuggestQueriesSettings = existing.SuggestQueriesSettings; OnCopy(existing); } partial void OnCopy(AutoSuggestionServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AutoSuggestionServiceClient.SuggestQueries</c> and <c>AutoSuggestionServiceClient.SuggestQueriesAsync</c> /// . /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 2 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings SuggestQueriesSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(2000))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="AutoSuggestionServiceSettings"/> object.</returns> public AutoSuggestionServiceSettings Clone() => new AutoSuggestionServiceSettings(this); } /// <summary> /// Builder class for <see cref="AutoSuggestionServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> public sealed partial class AutoSuggestionServiceClientBuilder : gaxgrpc::ClientBuilderBase<AutoSuggestionServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public AutoSuggestionServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public AutoSuggestionServiceClientBuilder() { UseJwtAccessWithScopes = AutoSuggestionServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref AutoSuggestionServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AutoSuggestionServiceClient> task); /// <summary>Builds the resulting client.</summary> public override AutoSuggestionServiceClient Build() { AutoSuggestionServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<AutoSuggestionServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<AutoSuggestionServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private AutoSuggestionServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return AutoSuggestionServiceClient.Create(callInvoker, Settings); } private async stt::Task<AutoSuggestionServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return AutoSuggestionServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => AutoSuggestionServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => AutoSuggestionServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => AutoSuggestionServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>AutoSuggestionService client wrapper, for convenient use.</summary> /// <remarks> /// This stateless API provides automatic suggestions for natural language /// queries for the data sources in the provided project and location. /// /// The service provides a resourceless operation `suggestQueries` that can be /// called to get a list of suggestions for a given incomplete query and scope /// (or list of scopes) under which the query is to be interpreted. /// /// There are two types of suggestions, ENTITY for single entity suggestions /// and TEMPLATE for full sentences. By default, both types are returned. /// /// Example Request: /// ``` /// GetSuggestions({ /// parent: "locations/us/projects/my-project" /// scopes: /// "//bigquery.googleapis.com/projects/my-project/datasets/my-dataset/tables/my-table" /// query: "top it" /// }) /// ``` /// /// The service will retrieve information based on the given scope(s) and give /// suggestions based on that (e.g. "top item" for "top it" if "item" is a known /// dimension for the provided scope). /// ``` /// suggestions { /// suggestion_info { /// annotated_suggestion { /// text_formatted: "top item by sum of usd_revenue_net" /// markups { /// type: DIMENSION /// start_char_index: 4 /// length: 4 /// } /// markups { /// type: METRIC /// start_char_index: 19 /// length: 15 /// } /// } /// query_matches { /// start_char_index: 0 /// length: 6 /// } /// } /// suggestion_type: TEMPLATE /// ranking_score: 0.9 /// } /// suggestions { /// suggestion_info { /// annotated_suggestion { /// text_formatted: "item" /// markups { /// type: DIMENSION /// start_char_index: 4 /// length: 2 /// } /// } /// query_matches { /// start_char_index: 0 /// length: 6 /// } /// } /// suggestion_type: ENTITY /// ranking_score: 0.8 /// } /// ``` /// </remarks> public abstract partial class AutoSuggestionServiceClient { /// <summary> /// The default endpoint for the AutoSuggestionService service, which is a host of "dataqna.googleapis.com" and /// a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "dataqna.googleapis.com:443"; /// <summary>The default AutoSuggestionService scopes.</summary> /// <remarks> /// The default AutoSuggestionService scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="AutoSuggestionServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="AutoSuggestionServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="AutoSuggestionServiceClient"/>.</returns> public static stt::Task<AutoSuggestionServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new AutoSuggestionServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="AutoSuggestionServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="AutoSuggestionServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="AutoSuggestionServiceClient"/>.</returns> public static AutoSuggestionServiceClient Create() => new AutoSuggestionServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="AutoSuggestionServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="AutoSuggestionServiceSettings"/>.</param> /// <returns>The created <see cref="AutoSuggestionServiceClient"/>.</returns> internal static AutoSuggestionServiceClient Create(grpccore::CallInvoker callInvoker, AutoSuggestionServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } AutoSuggestionService.AutoSuggestionServiceClient grpcClient = new AutoSuggestionService.AutoSuggestionServiceClient(callInvoker); return new AutoSuggestionServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC AutoSuggestionService client</summary> public virtual AutoSuggestionService.AutoSuggestionServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Gets a list of suggestions based on a prefix string. /// AutoSuggestion tolerance should be less than 1 second. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual SuggestQueriesResponse SuggestQueries(SuggestQueriesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Gets a list of suggestions based on a prefix string. /// AutoSuggestion tolerance should be less than 1 second. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<SuggestQueriesResponse> SuggestQueriesAsync(SuggestQueriesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Gets a list of suggestions based on a prefix string. /// AutoSuggestion tolerance should be less than 1 second. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<SuggestQueriesResponse> SuggestQueriesAsync(SuggestQueriesRequest request, st::CancellationToken cancellationToken) => SuggestQueriesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>AutoSuggestionService client wrapper implementation, for convenient use.</summary> /// <remarks> /// This stateless API provides automatic suggestions for natural language /// queries for the data sources in the provided project and location. /// /// The service provides a resourceless operation `suggestQueries` that can be /// called to get a list of suggestions for a given incomplete query and scope /// (or list of scopes) under which the query is to be interpreted. /// /// There are two types of suggestions, ENTITY for single entity suggestions /// and TEMPLATE for full sentences. By default, both types are returned. /// /// Example Request: /// ``` /// GetSuggestions({ /// parent: "locations/us/projects/my-project" /// scopes: /// "//bigquery.googleapis.com/projects/my-project/datasets/my-dataset/tables/my-table" /// query: "top it" /// }) /// ``` /// /// The service will retrieve information based on the given scope(s) and give /// suggestions based on that (e.g. "top item" for "top it" if "item" is a known /// dimension for the provided scope). /// ``` /// suggestions { /// suggestion_info { /// annotated_suggestion { /// text_formatted: "top item by sum of usd_revenue_net" /// markups { /// type: DIMENSION /// start_char_index: 4 /// length: 4 /// } /// markups { /// type: METRIC /// start_char_index: 19 /// length: 15 /// } /// } /// query_matches { /// start_char_index: 0 /// length: 6 /// } /// } /// suggestion_type: TEMPLATE /// ranking_score: 0.9 /// } /// suggestions { /// suggestion_info { /// annotated_suggestion { /// text_formatted: "item" /// markups { /// type: DIMENSION /// start_char_index: 4 /// length: 2 /// } /// } /// query_matches { /// start_char_index: 0 /// length: 6 /// } /// } /// suggestion_type: ENTITY /// ranking_score: 0.8 /// } /// ``` /// </remarks> public sealed partial class AutoSuggestionServiceClientImpl : AutoSuggestionServiceClient { private readonly gaxgrpc::ApiCall<SuggestQueriesRequest, SuggestQueriesResponse> _callSuggestQueries; /// <summary> /// Constructs a client wrapper for the AutoSuggestionService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="AutoSuggestionServiceSettings"/> used within this client.</param> public AutoSuggestionServiceClientImpl(AutoSuggestionService.AutoSuggestionServiceClient grpcClient, AutoSuggestionServiceSettings settings) { GrpcClient = grpcClient; AutoSuggestionServiceSettings effectiveSettings = settings ?? AutoSuggestionServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callSuggestQueries = clientHelper.BuildApiCall<SuggestQueriesRequest, SuggestQueriesResponse>(grpcClient.SuggestQueriesAsync, grpcClient.SuggestQueries, effectiveSettings.SuggestQueriesSettings).WithGoogleRequestParam("parent", request => request.Parent); Modify_ApiCall(ref _callSuggestQueries); Modify_SuggestQueriesApiCall(ref _callSuggestQueries); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_SuggestQueriesApiCall(ref gaxgrpc::ApiCall<SuggestQueriesRequest, SuggestQueriesResponse> call); partial void OnConstruction(AutoSuggestionService.AutoSuggestionServiceClient grpcClient, AutoSuggestionServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC AutoSuggestionService client</summary> public override AutoSuggestionService.AutoSuggestionServiceClient GrpcClient { get; } partial void Modify_SuggestQueriesRequest(ref SuggestQueriesRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Gets a list of suggestions based on a prefix string. /// AutoSuggestion tolerance should be less than 1 second. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override SuggestQueriesResponse SuggestQueries(SuggestQueriesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_SuggestQueriesRequest(ref request, ref callSettings); return _callSuggestQueries.Sync(request, callSettings); } /// <summary> /// Gets a list of suggestions based on a prefix string. /// AutoSuggestion tolerance should be less than 1 second. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<SuggestQueriesResponse> SuggestQueriesAsync(SuggestQueriesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_SuggestQueriesRequest(ref request, ref callSettings); return _callSuggestQueries.Async(request, callSettings); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices.Backup { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// ProtectionContainerOperationResultsOperations operations. /// </summary> internal partial class ProtectionContainerOperationResultsOperations : Microsoft.Rest.IServiceOperations<RecoveryServicesBackupClient>, IProtectionContainerOperationResultsOperations { /// <summary> /// Initializes a new instance of the ProtectionContainerOperationResultsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ProtectionContainerOperationResultsOperations(RecoveryServicesBackupClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the RecoveryServicesBackupClient /// </summary> public RecoveryServicesBackupClient Client { get; private set; } /// <summary> /// Fetches the result of any operation on the container. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='fabricName'> /// Fabric name associated with the container. /// </param> /// <param name='containerName'> /// Container name whose information should be fetched. /// </param> /// <param name='operationId'> /// Operation ID which represents the operation whose result needs to be /// fetched. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ProtectionContainerResource>> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string fabricName, string containerName, string operationId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (vaultName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "fabricName"); } if (containerName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "containerName"); } if (operationId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "operationId"); } string apiVersion = "2016-06-01"; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("containerName", containerName); tracingParameters.Add("operationId", operationId); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/operationResults/{operationId}").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{containerName}", System.Uri.EscapeDataString(containerName)); _url = _url.Replace("{operationId}", System.Uri.EscapeDataString(operationId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.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 System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<ProtectionContainerResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ProtectionContainerResource>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/api/context.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Api { /// <summary>Holder for reflection information generated from google/api/context.proto</summary> public static partial class ContextReflection { #region Descriptor /// <summary>File descriptor for google/api/context.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ContextReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Chhnb29nbGUvYXBpL2NvbnRleHQucHJvdG8SCmdvb2dsZS5hcGkiMQoHQ29u", "dGV4dBImCgVydWxlcxgBIAMoCzIXLmdvb2dsZS5hcGkuQ29udGV4dFJ1bGUi", "RAoLQ29udGV4dFJ1bGUSEAoIc2VsZWN0b3IYASABKAkSEQoJcmVxdWVzdGVk", "GAIgAygJEhAKCHByb3ZpZGVkGAMgAygJQm4KDmNvbS5nb29nbGUuYXBpQgxD", "b250ZXh0UHJvdG9QAVpFZ29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29v", "Z2xlYXBpcy9hcGkvc2VydmljZWNvbmZpZztzZXJ2aWNlY29uZmlnogIER0FQ", "SWIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Context), global::Google.Api.Context.Parser, new[]{ "Rules" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.ContextRule), global::Google.Api.ContextRule.Parser, new[]{ "Selector", "Requested", "Provided" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// `Context` defines which contexts an API requests. /// /// Example: /// /// context: /// rules: /// - selector: "*" /// requested: /// - google.rpc.context.ProjectContext /// - google.rpc.context.OriginContext /// /// The above specifies that all methods in the API request /// `google.rpc.context.ProjectContext` and /// `google.rpc.context.OriginContext`. /// /// Available context types are defined in package /// `google.rpc.context`. /// </summary> public sealed partial class Context : pb::IMessage<Context> { private static readonly pb::MessageParser<Context> _parser = new pb::MessageParser<Context>(() => new Context()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Context> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.ContextReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Context() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Context(Context other) : this() { rules_ = other.rules_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Context Clone() { return new Context(this); } /// <summary>Field number for the "rules" field.</summary> public const int RulesFieldNumber = 1; private static readonly pb::FieldCodec<global::Google.Api.ContextRule> _repeated_rules_codec = pb::FieldCodec.ForMessage(10, global::Google.Api.ContextRule.Parser); private readonly pbc::RepeatedField<global::Google.Api.ContextRule> rules_ = new pbc::RepeatedField<global::Google.Api.ContextRule>(); /// <summary> /// A list of RPC context rules that apply to individual API methods. /// /// **NOTE:** All service configuration rules follow "last one wins" order. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Api.ContextRule> Rules { get { return rules_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Context); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Context other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!rules_.Equals(other.rules_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= rules_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { rules_.WriteTo(output, _repeated_rules_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += rules_.CalculateSize(_repeated_rules_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Context other) { if (other == null) { return; } rules_.Add(other.rules_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { rules_.AddEntriesFrom(input, _repeated_rules_codec); break; } } } } } /// <summary> /// A context rule provides information about the context for an individual API /// element. /// </summary> public sealed partial class ContextRule : pb::IMessage<ContextRule> { private static readonly pb::MessageParser<ContextRule> _parser = new pb::MessageParser<ContextRule>(() => new ContextRule()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ContextRule> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.ContextReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ContextRule() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ContextRule(ContextRule other) : this() { selector_ = other.selector_; requested_ = other.requested_.Clone(); provided_ = other.provided_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ContextRule Clone() { return new ContextRule(this); } /// <summary>Field number for the "selector" field.</summary> public const int SelectorFieldNumber = 1; private string selector_ = ""; /// <summary> /// Selects the methods to which this rule applies. /// /// Refer to [selector][google.api.DocumentationRule.selector] for syntax details. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Selector { get { return selector_; } set { selector_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "requested" field.</summary> public const int RequestedFieldNumber = 2; private static readonly pb::FieldCodec<string> _repeated_requested_codec = pb::FieldCodec.ForString(18); private readonly pbc::RepeatedField<string> requested_ = new pbc::RepeatedField<string>(); /// <summary> /// A list of full type names of requested contexts. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> Requested { get { return requested_; } } /// <summary>Field number for the "provided" field.</summary> public const int ProvidedFieldNumber = 3; private static readonly pb::FieldCodec<string> _repeated_provided_codec = pb::FieldCodec.ForString(26); private readonly pbc::RepeatedField<string> provided_ = new pbc::RepeatedField<string>(); /// <summary> /// A list of full type names of provided contexts. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> Provided { get { return provided_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ContextRule); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ContextRule other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Selector != other.Selector) return false; if(!requested_.Equals(other.requested_)) return false; if(!provided_.Equals(other.provided_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Selector.Length != 0) hash ^= Selector.GetHashCode(); hash ^= requested_.GetHashCode(); hash ^= provided_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Selector.Length != 0) { output.WriteRawTag(10); output.WriteString(Selector); } requested_.WriteTo(output, _repeated_requested_codec); provided_.WriteTo(output, _repeated_provided_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Selector.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Selector); } size += requested_.CalculateSize(_repeated_requested_codec); size += provided_.CalculateSize(_repeated_provided_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ContextRule other) { if (other == null) { return; } if (other.Selector.Length != 0) { Selector = other.Selector; } requested_.Add(other.requested_); provided_.Add(other.provided_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Selector = input.ReadString(); break; } case 18: { requested_.AddEntriesFrom(input, _repeated_requested_codec); break; } case 26: { provided_.AddEntriesFrom(input, _repeated_provided_codec); break; } } } } } #endregion } #endregion Designer generated code
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; using System.Windows.Forms.Design; using Microsoft.PythonTools.Analysis; using Microsoft.PythonTools.Commands; using Microsoft.PythonTools.Debugger; using Microsoft.PythonTools.Debugger.DebugEngine; using Microsoft.PythonTools.Debugger.Remote; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Intellisense; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.InterpreterList; using Microsoft.PythonTools.Navigation; using Microsoft.PythonTools.Options; using Microsoft.PythonTools.Project; using Microsoft.PythonTools.Project.Web; using Microsoft.VisualStudio; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.InteractiveWindow.Shell; using Microsoft.VisualStudio.Settings; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Utilities; using Microsoft.VisualStudioTools; using Microsoft.VisualStudioTools.Navigation; using Microsoft.VisualStudioTools.Project; using NativeMethods = Microsoft.VisualStudioTools.Project.NativeMethods; namespace Microsoft.PythonTools { /// <summary> /// This is the class that implements the package exposed by this assembly. /// /// The minimum requirement for a class to be considered a valid package for Visual Studio /// is to implement the IVsPackage interface and register itself with the shell. /// This package uses the helper classes defined inside the Managed Package Framework (MPF) /// to do it: it derives from the Package class that provides the implementation of the /// IVsPackage interface and uses the registration attributes defined in the framework to /// register itself and its components with the shell. /// </summary> [PackageRegistration(UseManagedResourcesOnly = true)] // This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is a package. // This attribute is used to register the informations needed to show the this package in the Help/About dialog of Visual Studio. [InstalledProductRegistration("#110", "#112", AssemblyVersionInfo.Version, IconResourceID = 400)] // This attribute is needed to let the shell know that this package exposes some menus. [ProvideMenuResource(1000, 1)] [ProvideKeyBindingTable(PythonConstants.EditorFactoryGuid, 3004, AllowNavKeyBinding = true)] [Description("Python Tools Package")] [ProvideAutomationObject("VsPython")] [ProvideLanguageEditorOptionPage(typeof(PythonAdvancedEditorOptionsPage), PythonConstants.LanguageName, "", "Advanced", "113")] [ProvideLanguageEditorOptionPage(typeof(PythonFormattingGeneralOptionsPage), PythonConstants.LanguageName, "Formatting", "General", "120")] //[ProvideLanguageEditorOptionPage(typeof(PythonFormattingNewLinesOptionsPage), PythonConstants.LanguageName, "Formatting", "New Lines", "121")] [ProvideLanguageEditorOptionPage(typeof(PythonFormattingSpacingOptionsPage), PythonConstants.LanguageName, "Formatting", "Spacing", "122")] [ProvideLanguageEditorOptionPage(typeof(PythonFormattingStatementsOptionsPage), PythonConstants.LanguageName, "Formatting", "Statements", "123")] [ProvideLanguageEditorOptionPage(typeof(PythonFormattingWrappingOptionsPage), PythonConstants.LanguageName, "Formatting", "Wrapping", "124")] [ProvideOptionPage(typeof(PythonInteractiveOptionsPage), "Python Tools", "Interactive Windows", 115, 117, true)] [ProvideOptionPage(typeof(PythonGeneralOptionsPage), "Python Tools", "General", 115, 120, true)] [ProvideOptionPage(typeof(PythonDebuggingOptionsPage), "Python Tools", "Debugging", 115, 125, true)] [Guid(GuidList.guidPythonToolsPkgString)] // our packages GUID [ProvideLanguageService(typeof(PythonLanguageInfo), PythonConstants.LanguageName, 106, RequestStockColors = true, ShowSmartIndent = true, ShowCompletion = true, DefaultToInsertSpaces = true, HideAdvancedMembersByDefault = true, EnableAdvancedMembersOption = true, ShowDropDownOptions = true)] [ProvideLanguageExtension(typeof(PythonLanguageInfo), PythonConstants.FileExtension)] [ProvideLanguageExtension(typeof(PythonLanguageInfo), PythonConstants.WindowsFileExtension)] [ProvideDebugEngine(AD7Engine.DebugEngineName, typeof(AD7ProgramProvider), typeof(AD7Engine), AD7Engine.DebugEngineId, hitCountBp: true)] [ProvideDebugLanguage("Python", "{DA3C7D59-F9E4-4697-BEE7-3A0703AF6BFF}", PythonExpressionEvaluatorGuid, AD7Engine.DebugEngineId)] [ProvideDebugPortSupplier("Python remote (ptvsd)", typeof(PythonRemoteDebugPortSupplier), PythonRemoteDebugPortSupplier.PortSupplierId, typeof(PythonRemoteDebugPortPicker))] [ProvideDebugPortPicker(typeof(PythonRemoteDebugPortPicker))] #region Exception List [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "ArithmeticError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "AssertionError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "AttributeError", BreakByDefault = false)] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "BaseException")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "BufferError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "BytesWarning")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "DeprecationWarning")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "EOFError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "EnvironmentError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "Exception")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "FloatingPointError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "FutureWarning")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "GeneratorExit", BreakByDefault = false)] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "IOError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "ImportError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "ImportWarning")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "IndentationError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "IndexError", BreakByDefault = false)] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "KeyError", BreakByDefault = false)] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "KeyboardInterrupt")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "LookupError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "MemoryError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "NameError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "NotImplementedError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "BlockingIOError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "ChildProcessError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "ConnectionError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "ConnectionError", "BrokenPipeError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "ConnectionError", "ConnectionAbortedError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "ConnectionError", "ConnectionRefusedError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "ConnectionError", "ConnectionResetError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "FileExistsError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "FileNotFoundError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "InterruptedError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "IsADirectoryError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "NotADirectoryError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "PermissionError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "ProcessLookupError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "TimeoutError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OverflowError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "PendingDeprecationWarning")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "ReferenceError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "RuntimeError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "RuntimeWarning")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "StandardError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "StopIteration", BreakByDefault = false)] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "SyntaxError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "SyntaxWarning")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "SystemError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "SystemExit")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "TabError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "TypeError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "UnboundLocalError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "UnicodeDecodeError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "UnicodeEncodeError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "UnicodeError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "UnicodeTranslateError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "UnicodeWarning")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "UserWarning")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "ValueError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "Warning")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "WindowsError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "ZeroDivisionError")] #endregion [ProvideComponentPickerPropertyPage(typeof(PythonToolsPackage), typeof(WebPiComponentPickerControl), "WebPi", DefaultPageNameValue = "#4000")] [ProvideToolWindow(typeof(InterpreterListToolWindow), Style = VsDockStyle.Linked, Window = ToolWindowGuids80.SolutionExplorer)] [ProvideDiffSupportedContentType(".py;.pyw", "")] [ProvideCodeExpansions(GuidList.guidPythonLanguageService, false, 106, "Python", @"Snippets\%LCID%\SnippetsIndex.xml", @"Snippets\%LCID%\Python\")] [ProvideCodeExpansionPath("Python", "Test", @"Snippets\%LCID%\Test\")] #if DEV14 // TODO: Restore attribute and remove entry from Repl.v15.0.pkgdef [ProvideInteractiveWindow(GuidList.guidPythonInteractiveWindow, Style = VsDockStyle.Linked, Orientation = ToolWindowOrientation.none, Window = ToolWindowGuids80.Outputwindow)] #endif [ProvideBraceCompletion(PythonCoreConstants.ContentType)] [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "Object is owned by VS and cannot be disposed")] internal sealed class PythonToolsPackage : CommonPackage, IVsComponentSelectorProvider, IPythonToolsToolWindowService { private PythonAutomation _autoObject; private PackageContainer _packageContainer; internal const string PythonExpressionEvaluatorGuid = "{D67D5DB8-3D44-4105-B4B8-47AB1BA66180}"; internal PythonToolsService _pyService; /// <summary> /// Default constructor of the package. /// Inside this method you can place any initialization code that does not require /// any Visual Studio service because at this point the package object is created but /// not sited yet inside Visual Studio environment. The place to do all the other /// initialization is the Initialize method. /// </summary> public PythonToolsPackage() { Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString())); #if DEBUG System.Threading.Tasks.TaskScheduler.UnobservedTaskException += (sender, e) => { if (!e.Observed) { var str = e.Exception.ToString(); if (str.Contains("Python")) { try { ActivityLog.LogError( "UnobservedTaskException", string.Format("An exception in a task was not observed: {0}", e.Exception.ToString()) ); } catch (InvalidOperationException) { } Debug.Fail("An exception in a task was not observed. See ActivityLog.xml for more details.", e.Exception.ToString()); } e.SetObserved(); } }; #endif if (IsIpyToolsInstalled()) { MessageBox.Show( @"WARNING: Both Python Tools for Visual Studio and IronPython Tools are installed. Only one extension can handle Python source files and having both installed will usually cause both to be broken. You should uninstall IronPython 2.7 and re-install it with the ""Tools for Visual Studio"" option unchecked.", "Python Tools for Visual Studio", MessageBoxButtons.OK, MessageBoxIcon.Warning ); } } internal static bool IsIpyToolsInstalled() { // the component guid which IpyTools is installed under from IronPython 2.7 const string ipyToolsComponentGuid = "{2DF41B37-FAEF-4FD8-A2F5-46B57FF9E951}"; // Check if the IpyTools component is known... StringBuilder productBuffer = new StringBuilder(39); if (NativeMethods.MsiGetProductCode(ipyToolsComponentGuid, productBuffer) == 0) { // If it is then make sure that it's installed locally... StringBuilder buffer = new StringBuilder(1024); uint charsReceived = (uint)buffer.Capacity; var res = NativeMethods.MsiGetComponentPath(productBuffer.ToString(), ipyToolsComponentGuid, buffer, ref charsReceived); switch (res) { case NativeMethods.MsiInstallState.Source: case NativeMethods.MsiInstallState.Local: return true; } } return false; } internal static void NavigateTo(System.IServiceProvider serviceProvider, string filename, Guid docViewGuidType, int line, int col) { VsUtilities.NavigateTo(serviceProvider, filename, docViewGuidType, line, col); } internal static void NavigateTo(System.IServiceProvider serviceProvider, string filename, Guid docViewGuidType, int pos) { IVsTextView viewAdapter; IVsWindowFrame pWindowFrame; VsUtilities.OpenDocument(serviceProvider, filename, out viewAdapter, out pWindowFrame); ErrorHandler.ThrowOnFailure(pWindowFrame.Show()); // Set the cursor at the beginning of the declaration. int line, col; ErrorHandler.ThrowOnFailure(viewAdapter.GetLineAndColumn(pos, out line, out col)); ErrorHandler.ThrowOnFailure(viewAdapter.SetCaretPos(line, col)); // Make sure that the text is visible. viewAdapter.CenterLines(line, 1); } internal static ITextBuffer GetBufferForDocument(System.IServiceProvider serviceProvider, string filename) { IVsTextView viewAdapter; IVsWindowFrame frame; VsUtilities.OpenDocument(serviceProvider, filename, out viewAdapter, out frame); IVsTextLines lines; ErrorHandler.ThrowOnFailure(viewAdapter.GetBuffer(out lines)); var adapter = serviceProvider.GetComponentModel().GetService<IVsEditorAdaptersFactoryService>(); return adapter.GetDocumentBuffer(lines); } internal static IProjectLauncher GetLauncher(IServiceProvider serviceProvider, IPythonProject project) { var launchProvider = serviceProvider.GetUIThread().Invoke<string>(() => project.GetProperty(PythonConstants.LaunchProvider)); IPythonLauncherProvider defaultLaunchProvider = null; foreach (var launcher in serviceProvider.GetComponentModel().GetExtensions<IPythonLauncherProvider>()) { if (launcher.Name == launchProvider) { return serviceProvider.GetUIThread().Invoke<IProjectLauncher>(() => launcher.CreateLauncher(project)); } if (launcher.Name == DefaultLauncherProvider.DefaultLauncherName) { defaultLaunchProvider = launcher; } } // no launcher configured, use the default one. Debug.Assert(defaultLaunchProvider != null); return (defaultLaunchProvider != null) ? serviceProvider.GetUIThread().Invoke<IProjectLauncher>(() => defaultLaunchProvider.CreateLauncher(project)) : null; } void IPythonToolsToolWindowService.ShowWindowPane(Type windowType, bool focus) { var window = FindWindowPane(windowType, 0, true) as ToolWindowPane; if (window != null) { var frame = window.Frame as IVsWindowFrame; if (frame != null) { ErrorHandler.ThrowOnFailure(frame.Show()); } if (focus) { var content = window.Content as System.Windows.UIElement; if (content != null) { content.Focus(); } } } } internal static void OpenNoInterpretersHelpPage(System.IServiceProvider serviceProvider, string page = null) { OpenVsWebBrowser(serviceProvider, page ?? PythonToolsInstallPath.GetFile("NoInterpreters.mht")); } public static string InterpreterHelpUrl { get { return string.Format("http://go.microsoft.com/fwlink/?LinkId=299429&clcid=0x{0:X}", CultureInfo.CurrentCulture.LCID); } } protected override object GetAutomationObject(string name) { if (name == "VsPython") { return _autoObject; } return base.GetAutomationObject(name); } public override bool IsRecognizedFile(string filename) { return ModulePath.IsPythonSourceFile(filename); } public override Type GetLibraryManagerType() { return typeof(IPythonLibraryManager); } public string InteractiveOptions { get { // FIXME return ""; } } public PythonGeneralOptionsPage GeneralOptionsPage { get { return (PythonGeneralOptionsPage)GetDialogPage(typeof(PythonGeneralOptionsPage)); } } public PythonDebuggingOptionsPage DebuggingOptionsPage { get { return (PythonDebuggingOptionsPage)GetDialogPage(typeof(PythonDebuggingOptionsPage)); } } public PythonAdvancedEditorOptionsPage AdvancedEditorOptionsPage { get { return (PythonAdvancedEditorOptionsPage)GetDialogPage(typeof(PythonAdvancedEditorOptionsPage)); } } private new IComponentModel ComponentModel { get { return (IComponentModel)GetService(typeof(SComponentModel)); } } /// <summary> /// The analyzer which is used for loose files. /// </summary> internal VsProjectAnalyzer DefaultAnalyzer { get { return _pyService.DefaultAnalyzer; } } internal PythonToolsService PythonService { get { return _pyService; } } internal override LibraryManager CreateLibraryManager(CommonPackage package) { return new PythonLibraryManager((PythonToolsPackage)package); } public IVsSolution Solution { get { return GetService(typeof(SVsSolution)) as IVsSolution; } } internal static SettingsManager GetSettings(System.IServiceProvider serviceProvider) { return SettingsManagerCreator.GetSettingsManager(serviceProvider); } ///////////////////////////////////////////////////////////////////////////// // Overriden Package Implementation /// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initilaization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString())); base.Initialize(); var services = (IServiceContainer)this; // register our options service which provides registry access for various options var optionsService = new PythonToolsOptionsService(this); services.AddService(typeof(IPythonToolsOptionsService), optionsService, promote: true); services.AddService(typeof(IClipboardService), new ClipboardService(), promote: true); services.AddService(typeof(IPythonToolsToolWindowService), this, promote: true); // register our PythonToolsService which provides access to core PTVS functionality var pyService = _pyService = new PythonToolsService(services); services.AddService(typeof(PythonToolsService), pyService, promote: true); _autoObject = new PythonAutomation(this); services.AddService( typeof(ErrorTaskProvider), (container, serviceType) => { var errorList = GetService(typeof(SVsErrorList)) as IVsTaskList; var model = ComponentModel; var errorProvider = model != null ? model.GetService<IErrorProviderFactory>() : null; return new ErrorTaskProvider(this, errorList, errorProvider); }, promote: true); services.AddService( typeof(CommentTaskProvider), (container, serviceType) => { var taskList = GetService(typeof(SVsTaskList)) as IVsTaskList; var model = ComponentModel; var errorProvider = model != null ? model.GetService<IErrorProviderFactory>() : null; return new CommentTaskProvider(this, taskList, errorProvider); }, promote: true); var solutionEventListener = new SolutionEventsListener(this); solutionEventListener.StartListeningForChanges(); services.AddService( typeof(SolutionEventsListener), solutionEventListener, promote: true ); // Register custom debug event service var customDebuggerEventHandler = new CustomDebuggerEventHandler(this); services.AddService(customDebuggerEventHandler.GetType(), customDebuggerEventHandler, promote: true); // Enable the mixed-mode debugger UI context UIContext.FromUIContextGuid(DkmEngineId.NativeEng).IsActive = true; // Add our command handlers for menu (commands must exist in the .vsct file) RegisterCommands(new Command[] { new OpenReplCommand(this, (int)PkgCmdIDList.cmdidReplWindow), new OpenReplCommand(this, (int)PythonConstants.OpenInteractiveForEnvironment), new OpenDebugReplCommand(this), new ExecuteInReplCommand(this), new SendToReplCommand(this), new StartWithoutDebuggingCommand(this), new StartDebuggingCommand(this), new FillParagraphCommand(this), new DiagnosticsCommand(this), new RemoveImportsCommand(this, true), new RemoveImportsCommand(this, false), new OpenInterpreterListCommand(this), new ImportWizardCommand(this), new SurveyNewsCommand(this), new ImportCoverageCommand(this), new ShowPythonViewCommand(this), new ShowCppViewCommand(this), new ShowNativePythonFrames(this), new UsePythonStepping(this), new AzureExplorerAttachDebuggerCommand(this), }, GuidList.guidPythonToolsCmdSet); RegisterProjectFactory(new PythonWebProjectFactory(this)); // Enable the Python debugger UI context UIContext.FromUIContextGuid(AD7Engine.DebugEngineGuid).IsActive = true; var interpreters = ComponentModel.GetService<IInterpreterRegistryService>(); var interpreterService = ComponentModel.GetService<IInterpreterOptionsService>(); //var loadedProjectProvider = interpreterService.KnownProviders // .OfType<LoadedProjectInterpreterFactoryProvider>() // .FirstOrDefault(); //// Ensure the provider is available - if not, you probably need to //// rebuild or clean your experimental hive. //Debug.Assert(loadedProjectProvider != null, "Expected LoadedProjectInterpreterFactoryProvider"); //if (loadedProjectProvider != null) { // loadedProjectProvider.SetSolution((IVsSolution)GetService(typeof(SVsSolution))); //} // The variable is inherited by child processes backing Test Explorer, and is used in PTVS // test discoverer and test executor to connect back to VS. Environment.SetEnvironmentVariable("_PTVS_PID", Process.GetCurrentProcess().Id.ToString()); } internal static bool TryGetStartupFileAndDirectory(System.IServiceProvider serviceProvider, out string filename, out string dir, out VsProjectAnalyzer analyzer) { var startupProject = GetStartupProject(serviceProvider); if (startupProject != null) { filename = startupProject.GetStartupFile(); dir = startupProject.GetWorkingDirectory(); analyzer = ((PythonProjectNode)startupProject).GetAnalyzer(); } else { var textView = CommonPackage.GetActiveTextView(serviceProvider); if (textView == null) { filename = null; dir = null; analyzer = null; return false; } filename = textView.GetFilePath(); analyzer = textView.GetAnalyzerAtCaret(serviceProvider); dir = Path.GetDirectoryName(filename); } return true; } public EnvDTE.DTE DTE { get { return (EnvDTE.DTE)GetService(typeof(EnvDTE.DTE)); } } #region IVsComponentSelectorProvider Members public int GetComponentSelectorPage(ref Guid rguidPage, VSPROPSHEETPAGE[] ppage) { if (rguidPage == typeof(WebPiComponentPickerControl).GUID) { var page = new VSPROPSHEETPAGE(); page.dwSize = (uint)Marshal.SizeOf(typeof(VSPROPSHEETPAGE)); var pickerPage = new WebPiComponentPickerControl(); if (_packageContainer == null) { _packageContainer = new PackageContainer(this); } _packageContainer.Add(pickerPage); //IWin32Window window = pickerPage; page.hwndDlg = pickerPage.Handle; ppage[0] = page; return VSConstants.S_OK; } return VSConstants.E_FAIL; } /// <devdoc> /// This class derives from container to provide a service provider /// connection to the package. /// </devdoc> private sealed class PackageContainer : Container { private IUIService _uis; private AmbientProperties _ambientProperties; private System.IServiceProvider _provider; /// <devdoc> /// Creates a new container using the given service provider. /// </devdoc> internal PackageContainer(System.IServiceProvider provider) { _provider = provider; } /// <devdoc> /// Override to GetService so we can route requests /// to the package's service provider. /// </devdoc> protected override object GetService(Type serviceType) { if (serviceType == null) { throw new ArgumentNullException("serviceType"); } if (_provider != null) { if (serviceType.IsEquivalentTo(typeof(AmbientProperties))) { if (_uis == null) { _uis = (IUIService)_provider.GetService(typeof(IUIService)); } if (_ambientProperties == null) { _ambientProperties = new AmbientProperties(); } if (_uis != null) { // update the _ambientProperties in case the styles have changed // since last time. _ambientProperties.Font = (Font)_uis.Styles["DialogFont"]; } return _ambientProperties; } object service = _provider.GetService(serviceType); if (service != null) { return service; } } return base.GetService(serviceType); } } #endregion } }
using System; using System.Collections.Generic; using Microsoft.Data.Entity.Migrations; namespace AllReady.Migrations { public partial class TaskDateTimeOffset : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_Activity_Campaign_CampaignId", table: "Activity"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_Campaign_Tenant_ManagingTenantId", table: "Campaign"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TenantContact_Contact_ContactId", table: "TenantContact"); migrationBuilder.DropForeignKey(name: "FK_TenantContact_Tenant_TenantId", table: "TenantContact"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.AddColumn<DateTimeOffset>( name: "EndDateTime", table: "AllReadyTask", nullable: true); migrationBuilder.AddColumn<DateTimeOffset>( name: "StartDateTime", table: "AllReadyTask", nullable: true); migrationBuilder.Sql("UPDATE AllReadyTask SET StartDateTime = StartDateTimeUtc, EndDateTime = EndDateTimeUtc"); migrationBuilder.DropColumn(name: "EndDateTimeUtc", table: "AllReadyTask"); migrationBuilder.DropColumn(name: "StartDateTimeUtc", table: "AllReadyTask"); migrationBuilder.AddForeignKey( name: "FK_Activity_Campaign_CampaignId", table: "Activity", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill", column: "ActivityId", principalTable: "Activity", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Campaign_Tenant_ManagingTenantId", table: "Campaign", column: "ManagingTenantId", principalTable: "Tenant", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill", column: "TaskId", principalTable: "AllReadyTask", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TenantContact_Contact_ContactId", table: "TenantContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TenantContact_Tenant_TenantId", table: "TenantContact", column: "TenantId", principalTable: "Tenant", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_UserSkill_Skill_SkillId", table: "UserSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_Activity_Campaign_CampaignId", table: "Activity"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_Campaign_Tenant_ManagingTenantId", table: "Campaign"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TenantContact_Contact_ContactId", table: "TenantContact"); migrationBuilder.DropForeignKey(name: "FK_TenantContact_Tenant_TenantId", table: "TenantContact"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.AddColumn<DateTimeOffset>( name: "EndDateTimeUtc", table: "AllReadyTask", nullable: true); migrationBuilder.AddColumn<DateTimeOffset>( name: "StartDateTimeUtc", table: "AllReadyTask", nullable: true); migrationBuilder.Sql("UPDATE AllReadyTask SET StartDateTimeUtc = StartDateTime, EndDateTimeUtc = EndDateTime"); migrationBuilder.DropColumn(name: "EndDateTime", table: "AllReadyTask"); migrationBuilder.DropColumn(name: "StartDateTime", table: "AllReadyTask"); migrationBuilder.AddForeignKey( name: "FK_Activity_Campaign_CampaignId", table: "Activity", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill", column: "ActivityId", principalTable: "Activity", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Campaign_Tenant_ManagingTenantId", table: "Campaign", column: "ManagingTenantId", principalTable: "Tenant", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill", column: "TaskId", principalTable: "AllReadyTask", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TenantContact_Contact_ContactId", table: "TenantContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TenantContact_Tenant_TenantId", table: "TenantContact", column: "TenantId", principalTable: "Tenant", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_UserSkill_Skill_SkillId", table: "UserSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace AllHttpMethods.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
/******************************************************************************* * Copyright 2008-2011, Cypress Semiconductor Corporation. All rights reserved. * You may use this file only in accordance with the license, terms, conditions, * disclaimers, and limitations in the end user license agreement accompanying * the software package with which this file was provided. ********************************************************************************/ using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.ComponentModel; using CyDesigner.Extensions.Common; using CyDesigner.Extensions.Gde; namespace SPI_HFC_Master_v0_1 { #region Component Parameter Names public class CyParamNames { // Basic tab parameners public const string MODE = "Mode"; //public const string BIDIRECT_MODE = "BidirectMode"; public const string NUMBER_OF_DATA_BITS = "NumberOfDataBits"; public const string SHIFT_DIR = "ShiftDir"; public const string DESIRED_BIT_RATE = "DesiredBitRate"; // Advanced tab parameters public const string CLOCK_INTERNAL = "ClockInternal"; public const string INTERRUPT_ON_SPI_DONE = "InterruptOnSPIDone"; public const string INTERRUPT_ON_SPI_IDLE = "InterruptOnSPIIdle"; public const string INTERRUPT_ON_TX_EMPTY = "InterruptOnTXEmpty"; public const string INTERRUPT_ON_TX_NOT_FULL = "InterruptOnTXNotFull"; public const string INTERRUPT_ON_RX_FULL = "InterruptOnRXFull"; public const string INTERRUPT_ON_RX_NOT_EMPTY = "InterruptOnRXNotEmpty"; public const string INTERRUPT_ON_RX_OVERRUN = "InterruptOnRXOverrun"; public const string INTERRUPT_ON_BYTE_COMPLETE = "InterruptOnByteComplete"; public const string RX_BUFFER_SIZE = "RxBufferSize"; public const string TX_BUFFER_SIZE = "TxBufferSize"; public const string USE_INTERNAL_INTERRUPT = "UseInternalInterrupt"; public const string USE_TX_INTERNAL_INTERRUPT = "UseTxInternalInterrupt"; public const string USE_RX_INTERNAL_INTERRUPT = "UseRxInternalInterrupt"; public const string HIGH_SPEED_MODE = "HighSpeedMode"; } #endregion #region Component Parameters Range public class CyParamRange { // Basic Tab Constants public const byte NUM_BITS_MIN = 3; public const byte NUM_BITS_MAX = 16; public const int FREQUENCY_MIN = 1; public const int FREQUENCY_MAX = 33000000; // Advanced Tab Constants public const byte BUFFER_SIZE_MIN = 4; public const byte BUFFER_SIZE_MAX = 255; } #endregion #region Component types public enum E_SPI_MODES { Mode_00 = 1, Mode_01 = 2, Mode_10 = 3, Mode_11 = 4 }; public enum E_B_SPI_MASTER_SHIFT_DIRECTION { [Description("MSB First")] MSB_First = 0, [Description("LSB First")] LSB_First = 1 }; #endregion public class CySPIMParameters { public ICyInstEdit_v1 m_inst; public CySPIMControl m_basicTab; public CySPIMControlAdv m_advTab; /// <summary> /// During first getting of parameters this variable is false, what means that assigning /// values to form controls will not immediatly overwrite parameters with the same values. /// </summary> public bool m_bGlobalEditMode = false; public List<string> m_modeList; public List<string> m_shiftDirectionList; #region Constructor(s) public CySPIMParameters(ICyInstEdit_v1 inst) { this.m_inst = inst; m_modeList = new List<string>(inst.GetPossibleEnumValues(CyParamNames.MODE)); m_shiftDirectionList = new List<string>(inst.GetPossibleEnumValues(CyParamNames.SHIFT_DIR)); } #endregion #region Basic Tab Properties public E_SPI_MODES Mode { get { return GetValue<E_SPI_MODES>(CyParamNames.MODE); } set { SetValue(CyParamNames.MODE, value); } } /* public bool BidirectMode { get { return GetValue<bool>(CyParamNames.BIDIRECT_MODE); } set { SetValue(CyParamNames.BIDIRECT_MODE, value); } } */ public byte? NumberOfDataBits { get { return GetValue<byte>(CyParamNames.NUMBER_OF_DATA_BITS); } set { SetValue(CyParamNames.NUMBER_OF_DATA_BITS, value); } } public E_B_SPI_MASTER_SHIFT_DIRECTION ShiftDir { get { return GetValue<E_B_SPI_MASTER_SHIFT_DIRECTION>(CyParamNames.SHIFT_DIR); } set { SetValue(CyParamNames.SHIFT_DIR, value); } } public double? DesiredBitRate { get { return GetValue<double>(CyParamNames.DESIRED_BIT_RATE); } set { SetValue(CyParamNames.DESIRED_BIT_RATE, value); } } #endregion #region Advanced Tab Properties public bool ClockInternal { get { return GetValue<bool>(CyParamNames.CLOCK_INTERNAL); } set { SetValue(CyParamNames.CLOCK_INTERNAL, value); } } public bool HighSpeedMode { get { return GetValue<bool>(CyParamNames.HIGH_SPEED_MODE); } set { SetValue(CyParamNames.HIGH_SPEED_MODE, value); } } public bool InterruptOnRXFull { get { return GetValue<bool>(CyParamNames.INTERRUPT_ON_RX_FULL); } set { SetValue(CyParamNames.INTERRUPT_ON_RX_FULL, value); } } public bool InterruptOnTXNotFull { get { return GetValue<bool>(CyParamNames.INTERRUPT_ON_TX_NOT_FULL); } set { SetValue(CyParamNames.INTERRUPT_ON_TX_NOT_FULL, value); } } public bool InterruptOnSPIDone { get { return GetValue<bool>(CyParamNames.INTERRUPT_ON_SPI_DONE); } set { SetValue(CyParamNames.INTERRUPT_ON_SPI_DONE, value); } } public bool InterruptOnSPIIdle { get { return GetValue<bool>(CyParamNames.INTERRUPT_ON_SPI_IDLE); } set { SetValue(CyParamNames.INTERRUPT_ON_SPI_IDLE, value); } } public bool InterruptOnRXOverrun { get { return GetValue<bool>(CyParamNames.INTERRUPT_ON_RX_OVERRUN); } set { SetValue(CyParamNames.INTERRUPT_ON_RX_OVERRUN, value); } } public bool InterruptOnTXEmpty { get { return GetValue<bool>(CyParamNames.INTERRUPT_ON_TX_EMPTY); } set { SetValue(CyParamNames.INTERRUPT_ON_TX_EMPTY, value); } } public bool InterruptOnRXNotEmpty { get { return GetValue<bool>(CyParamNames.INTERRUPT_ON_RX_NOT_EMPTY); } set { SetValue(CyParamNames.INTERRUPT_ON_RX_NOT_EMPTY, value); } } public bool InterruptOnByteComplete { get { return GetValue<bool>(CyParamNames.INTERRUPT_ON_BYTE_COMPLETE); } set { SetValue(CyParamNames.INTERRUPT_ON_BYTE_COMPLETE, value); } } public byte? RxBufferSize { get { return GetValue<byte>(CyParamNames.RX_BUFFER_SIZE); } set { SetValue(CyParamNames.RX_BUFFER_SIZE, value); } } public byte? TxBufferSize { get { return GetValue<byte>(CyParamNames.TX_BUFFER_SIZE); } set { SetValue(CyParamNames.TX_BUFFER_SIZE, value); } } public bool UseTxInternalInterrupt { get { return GetValue<bool>(CyParamNames.USE_TX_INTERNAL_INTERRUPT); } set { SetValue(CyParamNames.USE_TX_INTERNAL_INTERRUPT, value); } } public bool UseRxInternalInterrupt { get { return GetValue<bool>(CyParamNames.USE_RX_INTERNAL_INTERRUPT); } set { SetValue(CyParamNames.USE_RX_INTERNAL_INTERRUPT, value); } } public bool UseInternalInterrupt { get { // Backward compatibility. This parameter isn't in use anymore but have to be analyzed // during update from versions lower than 2.0. bool useInternalInterrupt = GetValue<bool>(CyParamNames.USE_INTERNAL_INTERRUPT); if (useInternalInterrupt) { this.UseTxInternalInterrupt = useInternalInterrupt; this.UseRxInternalInterrupt = useInternalInterrupt; } else { // UseTXInternalInterrupt this.UseTxInternalInterrupt = GetValue<bool>(CyParamNames.USE_TX_INTERNAL_INTERRUPT); // UseRXInternalInterrupt this.UseRxInternalInterrupt = GetValue<bool>(CyParamNames.USE_RX_INTERNAL_INTERRUPT); } return useInternalInterrupt; } set { SetValue(CyParamNames.USE_INTERNAL_INTERRUPT, value); } } #endregion #region Getting parameters private T GetValue<T>(string paramName) { T value; CyCustErr err = m_inst.GetCommittedParam(paramName).TryGetValueAs<T>(out value); if (err.IsOK) { return value; } else { m_basicTab.ShowError(paramName, err); return default(T); } } public void LoadParameters(ICyInstEdit_v1 inst) { m_bGlobalEditMode = false; m_basicTab.UpdateUI(); m_advTab.UpdateUI(); m_bGlobalEditMode = true; } #endregion #region Setting parameters private void SetValue<T>(string paramName, T value) { if (m_bGlobalEditMode) { switch (paramName) { case CyParamNames.MODE: SetParam<T>(paramName, value, false); break; case CyParamNames.SHIFT_DIR: string desc = CyEnumConverter.GetEnumDesc(value); string valueToSet = m_inst.ResolveEnumDisplayToId(paramName, desc); SetParam<string>(paramName, valueToSet, false); break; default: SetParam<T>(paramName, value, true); break; } m_inst.CommitParamExprs(); } } private void SetParam<T>(string paramName, T value, bool toLowerCase) { if (toLowerCase) { m_inst.SetParamExpr(paramName, value.ToString().ToLower()); } else { m_inst.SetParamExpr(paramName, value.ToString()); } } #endregion } }
//----------------------------------------------------------------------- // <copyright file="X509Util.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace System.IdentityModel { using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.Security.Claims; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Claim = System.Security.Claims.Claim; using System.Runtime; internal static class X509Util { internal static RSA EnsureAndGetPrivateRSAKey(X509Certificate2 certificate) { Fx.Assert(certificate != null, "certificate != null"); // Reject no private key if (!certificate.HasPrivateKey) { #pragma warning suppress 56526 // no validation necessary for value.Thumbprint throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.ID1001, certificate.Thumbprint))); } // Check for accessibility of private key AsymmetricAlgorithm privateKey; try { privateKey = certificate.PrivateKey; } catch (CryptographicException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.ID1039, certificate.Thumbprint), e)); } // Reject weird private key RSA rsa = privateKey as RSA; if (rsa == null) { #pragma warning suppress 56526 // no validation necessary for value.Thumbprint throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.ID1002, certificate.Thumbprint))); } return rsa; } internal static X509Certificate2 ResolveCertificate(StoreName storeName, StoreLocation storeLocation, X509FindType findType, object findValue) { X509Certificate2 certificate = null; // Throwing InvalidOperationException here, following WCF precedent. // Might be worth introducing a more specific exception here. if (!TryResolveCertificate(storeName, storeLocation, findType, findValue, out certificate)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException(SR.GetString(SR.ID1025, storeName, storeLocation, findType, findValue))); } return certificate; } internal static bool TryResolveCertificate(StoreName storeName, StoreLocation storeLocation, X509FindType findType, object findValue, out X509Certificate2 certificate) { X509Store store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadOnly); certificate = null; X509Certificate2Collection certs = null; X509Certificate2Collection matches = null; try { certs = store.Certificates; matches = certs.Find(findType, findValue, false); // Throwing InvalidOperationException here, following WCF precedent. // Might be worth introducing a more specific exception here. if (matches.Count == 1) { certificate = new X509Certificate2(matches[0]); return true; } } finally { CryptoHelper.ResetAllCertificates(matches); CryptoHelper.ResetAllCertificates(certs); store.Close(); } return false; } internal static string GetCertificateId(X509Certificate2 certificate) { if (certificate == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("certificate"); } string certificateId = certificate.SubjectName.Name; if (string.IsNullOrEmpty(certificateId)) { certificateId = certificate.Thumbprint; } return certificateId; } internal static string GetCertificateIssuerName(X509Certificate2 certificate, IssuerNameRegistry issuerNameRegistry) { if (certificate == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("certificate"); } if (issuerNameRegistry == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("issuerNameRegistry"); } X509Chain chain = new X509Chain(); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.Build(certificate); X509ChainElementCollection elements = chain.ChainElements; string issuer = null; if (elements.Count > 1) { using (X509SecurityToken token = new X509SecurityToken(elements[1].Certificate)) { issuer = issuerNameRegistry.GetIssuerName(token); } } else { // This is a self-issued certificate. Use the thumbprint of the current certificate. using (X509SecurityToken token = new X509SecurityToken(certificate)) { issuer = issuerNameRegistry.GetIssuerName(token); } } for (int i = 1; i < elements.Count; ++i) { // Resets the state of the certificate and frees resources associated with it. elements[i].Certificate.Reset(); } return issuer; } /// <summary> /// Creates an X509CertificateValidator using the given parameters. /// </summary> /// <param name="certificateValidationMode">The certificate validation mode to use.</param> /// <param name="revocationMode">The revocation mode to use.</param> /// <param name="trustedStoreLocation">The store to use.</param> /// <returns>The X509CertificateValidator.</returns> /// <remarks>Due to a WCF bug, X509CertificateValidatorEx must be used rather than WCF's validators directly</remarks> internal static X509CertificateValidator CreateCertificateValidator( System.ServiceModel.Security.X509CertificateValidationMode certificateValidationMode, X509RevocationMode revocationMode, StoreLocation trustedStoreLocation) { return new X509CertificateValidatorEx(certificateValidationMode, revocationMode, trustedStoreLocation); } public static IEnumerable<Claim> GetClaimsFromCertificate(X509Certificate2 certificate, string issuer) { if (certificate == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("certificate"); } ICollection<Claim> claimsCollection = new Collection<Claim>(); string thumbprint = Convert.ToBase64String(certificate.GetCertHash()); claimsCollection.Add(new Claim(ClaimTypes.Thumbprint, thumbprint, ClaimValueTypes.Base64Binary, issuer)); string value = certificate.SubjectName.Name; if (!string.IsNullOrEmpty(value)) { claimsCollection.Add(new Claim(ClaimTypes.X500DistinguishedName, value, ClaimValueTypes.String, issuer)); } value = certificate.GetNameInfo(X509NameType.DnsName, false); if (!string.IsNullOrEmpty(value)) { claimsCollection.Add(new Claim(ClaimTypes.Dns, value, ClaimValueTypes.String, issuer)); } value = certificate.GetNameInfo(X509NameType.SimpleName, false); if (!string.IsNullOrEmpty(value)) { claimsCollection.Add(new Claim(ClaimTypes.Name, value, ClaimValueTypes.String, issuer)); } value = certificate.GetNameInfo(X509NameType.EmailName, false); if (!string.IsNullOrEmpty(value)) { claimsCollection.Add(new Claim(ClaimTypes.Email, value, ClaimValueTypes.String, issuer)); } value = certificate.GetNameInfo(X509NameType.UpnName, false); if (!string.IsNullOrEmpty(value)) { claimsCollection.Add(new Claim(ClaimTypes.Upn, value, ClaimValueTypes.String, issuer)); } value = certificate.GetNameInfo(X509NameType.UrlName, false); if (!string.IsNullOrEmpty(value)) { claimsCollection.Add(new Claim(ClaimTypes.Uri, value, ClaimValueTypes.String, issuer)); } RSA rsa = certificate.PublicKey.Key as RSA; if (rsa != null) { claimsCollection.Add(new Claim(ClaimTypes.Rsa, rsa.ToXmlString(false), ClaimValueTypes.RsaKeyValue, issuer)); } DSA dsa = certificate.PublicKey.Key as DSA; if (dsa != null) { claimsCollection.Add(new Claim(ClaimTypes.Dsa, dsa.ToXmlString(false), ClaimValueTypes.DsaKeyValue, issuer)); } value = certificate.SerialNumber; if (!string.IsNullOrEmpty(value)) { claimsCollection.Add(new Claim(ClaimTypes.SerialNumber, value, ClaimValueTypes.String, issuer)); } return claimsCollection; } } }
/* * 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: devcenter@docusign.com * 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> /// AccountPasswordStrengthTypeOption /// </summary> [DataContract] public partial class AccountPasswordStrengthTypeOption : IEquatable<AccountPasswordStrengthTypeOption>, IValidatableObject { public AccountPasswordStrengthTypeOption() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="AccountPasswordStrengthTypeOption" /> class. /// </summary> /// <param name="MinimumLength">MinimumLength.</param> /// <param name="Name">Name.</param> /// <param name="PasswordIncludeDigit">PasswordIncludeDigit.</param> /// <param name="PasswordIncludeDigitOrSpecialCharacter">PasswordIncludeDigitOrSpecialCharacter.</param> /// <param name="PasswordIncludeLowerCase">PasswordIncludeLowerCase.</param> /// <param name="PasswordIncludeSpecialCharacter">PasswordIncludeSpecialCharacter.</param> /// <param name="PasswordIncludeUpperCase">PasswordIncludeUpperCase.</param> public AccountPasswordStrengthTypeOption(string MinimumLength = default(string), string Name = default(string), string PasswordIncludeDigit = default(string), string PasswordIncludeDigitOrSpecialCharacter = default(string), string PasswordIncludeLowerCase = default(string), string PasswordIncludeSpecialCharacter = default(string), string PasswordIncludeUpperCase = default(string)) { this.MinimumLength = MinimumLength; this.Name = Name; this.PasswordIncludeDigit = PasswordIncludeDigit; this.PasswordIncludeDigitOrSpecialCharacter = PasswordIncludeDigitOrSpecialCharacter; this.PasswordIncludeLowerCase = PasswordIncludeLowerCase; this.PasswordIncludeSpecialCharacter = PasswordIncludeSpecialCharacter; this.PasswordIncludeUpperCase = PasswordIncludeUpperCase; } /// <summary> /// Gets or Sets MinimumLength /// </summary> [DataMember(Name="minimumLength", EmitDefaultValue=false)] public string MinimumLength { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets PasswordIncludeDigit /// </summary> [DataMember(Name="passwordIncludeDigit", EmitDefaultValue=false)] public string PasswordIncludeDigit { get; set; } /// <summary> /// Gets or Sets PasswordIncludeDigitOrSpecialCharacter /// </summary> [DataMember(Name="passwordIncludeDigitOrSpecialCharacter", EmitDefaultValue=false)] public string PasswordIncludeDigitOrSpecialCharacter { get; set; } /// <summary> /// Gets or Sets PasswordIncludeLowerCase /// </summary> [DataMember(Name="passwordIncludeLowerCase", EmitDefaultValue=false)] public string PasswordIncludeLowerCase { get; set; } /// <summary> /// Gets or Sets PasswordIncludeSpecialCharacter /// </summary> [DataMember(Name="passwordIncludeSpecialCharacter", EmitDefaultValue=false)] public string PasswordIncludeSpecialCharacter { get; set; } /// <summary> /// Gets or Sets PasswordIncludeUpperCase /// </summary> [DataMember(Name="passwordIncludeUpperCase", EmitDefaultValue=false)] public string PasswordIncludeUpperCase { 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 AccountPasswordStrengthTypeOption {\n"); sb.Append(" MinimumLength: ").Append(MinimumLength).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" PasswordIncludeDigit: ").Append(PasswordIncludeDigit).Append("\n"); sb.Append(" PasswordIncludeDigitOrSpecialCharacter: ").Append(PasswordIncludeDigitOrSpecialCharacter).Append("\n"); sb.Append(" PasswordIncludeLowerCase: ").Append(PasswordIncludeLowerCase).Append("\n"); sb.Append(" PasswordIncludeSpecialCharacter: ").Append(PasswordIncludeSpecialCharacter).Append("\n"); sb.Append(" PasswordIncludeUpperCase: ").Append(PasswordIncludeUpperCase).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 AccountPasswordStrengthTypeOption); } /// <summary> /// Returns true if AccountPasswordStrengthTypeOption instances are equal /// </summary> /// <param name="other">Instance of AccountPasswordStrengthTypeOption to be compared</param> /// <returns>Boolean</returns> public bool Equals(AccountPasswordStrengthTypeOption other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.MinimumLength == other.MinimumLength || this.MinimumLength != null && this.MinimumLength.Equals(other.MinimumLength) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.PasswordIncludeDigit == other.PasswordIncludeDigit || this.PasswordIncludeDigit != null && this.PasswordIncludeDigit.Equals(other.PasswordIncludeDigit) ) && ( this.PasswordIncludeDigitOrSpecialCharacter == other.PasswordIncludeDigitOrSpecialCharacter || this.PasswordIncludeDigitOrSpecialCharacter != null && this.PasswordIncludeDigitOrSpecialCharacter.Equals(other.PasswordIncludeDigitOrSpecialCharacter) ) && ( this.PasswordIncludeLowerCase == other.PasswordIncludeLowerCase || this.PasswordIncludeLowerCase != null && this.PasswordIncludeLowerCase.Equals(other.PasswordIncludeLowerCase) ) && ( this.PasswordIncludeSpecialCharacter == other.PasswordIncludeSpecialCharacter || this.PasswordIncludeSpecialCharacter != null && this.PasswordIncludeSpecialCharacter.Equals(other.PasswordIncludeSpecialCharacter) ) && ( this.PasswordIncludeUpperCase == other.PasswordIncludeUpperCase || this.PasswordIncludeUpperCase != null && this.PasswordIncludeUpperCase.Equals(other.PasswordIncludeUpperCase) ); } /// <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.MinimumLength != null) hash = hash * 59 + this.MinimumLength.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.PasswordIncludeDigit != null) hash = hash * 59 + this.PasswordIncludeDigit.GetHashCode(); if (this.PasswordIncludeDigitOrSpecialCharacter != null) hash = hash * 59 + this.PasswordIncludeDigitOrSpecialCharacter.GetHashCode(); if (this.PasswordIncludeLowerCase != null) hash = hash * 59 + this.PasswordIncludeLowerCase.GetHashCode(); if (this.PasswordIncludeSpecialCharacter != null) hash = hash * 59 + this.PasswordIncludeSpecialCharacter.GetHashCode(); if (this.PasswordIncludeUpperCase != null) hash = hash * 59 + this.PasswordIncludeUpperCase.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Desafio.API.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { using Runtime.CompilerServices; using System.Net.Sockets; /// <devdoc> /// <para>Provides an internet protocol (IP) address.</para> /// </devdoc> [Serializable] public class IPAddress { public static readonly IPAddress Any = new IPAddress(0x0000000000000000); public static readonly IPAddress Loopback = new IPAddress(0x000000000100007F); //--// internal long m_Address; public IPAddress(long newAddress) { if (newAddress < 0 || newAddress > 0x00000000FFFFFFFF) { // BUG: This always throws. Needs investigation //throw new ArgumentOutOfRangeException(); } m_Address = newAddress; } public IPAddress(byte[] newAddressBytes) : this(((((newAddressBytes[3] << 0x18) | (newAddressBytes[2] << 0x10)) | (newAddressBytes[1] << 0x08)) | newAddressBytes[0]) & ((long)0xFFFFFFFF)) { } public override bool Equals(object obj) { IPAddress addr = obj as IPAddress; if (obj == null) return false; return this.m_Address == addr.m_Address; } public override int GetHashCode() { return (int)this.m_Address; } public byte[] GetAddressBytes() { return new byte[] { (byte)(m_Address), (byte)(m_Address >> 8), (byte)(m_Address >> 16), (byte)(m_Address >> 24) }; } public AddressFamily AddressFamily { get { return AddressFamily.InterNetwork; } } public static IPAddress Parse(string ipString) { if (ipString == null) throw new ArgumentNullException(); ulong ipAddress = 0L; int lastIndex = 0; int shiftIndex = 0; ulong mask = 0x00000000000000FF; ulong octet = 0L; int length = ipString.Length; for (int i = 0; i < length; ++i) { // Parse to '.' or end of IP address if (ipString[i] == '.' || i == length - 1) // If the IP starts with a '.' // or a segment is longer than 3 characters or shiftIndex > last bit position throw. if (i == 0 || i - lastIndex > 3 || shiftIndex > 24) { throw new ArgumentException(); } else { i = i == length - 1 ? ++i : i; octet = (ulong)(ConvertStringToInt32(ipString.Substring(lastIndex, i - lastIndex)) & 0x00000000000000FF); ipAddress = ipAddress + (ulong)((octet << shiftIndex) & mask); lastIndex = i + 1; shiftIndex = shiftIndex + 8; mask = (mask << 8); } } return new IPAddress((long)ipAddress); } public override string ToString() { return ((byte)(m_Address)).ToString() + "." + ((byte)(m_Address >> 8)).ToString() + "." + ((byte)(m_Address >> 16)).ToString() + "." + ((byte)(m_Address >> 24)).ToString(); } //--// //////////////////////////////////////////////////////////////////////////////////////// // this method ToInt32 is part of teh Convert class which we will bring over later // at that time we will get rid of this code // /// <summary> /// Converts the specified System.String representation of a number to an equivalent /// 32-bit signed integer. /// </summary> /// <param name="value">A System.String containing a number to convert.</param> /// <returns> /// A 32-bit signed integer equivalent to the value of value.-or- Zero if value /// is null. /// </returns> /// <exception cref="System.OverflowException"> /// Value represents a number less than System.Int32.MinValue or greater than /// System.Int32.MaxValue. /// </exception> /// <exception cref="System.ArgumentNullException"> /// The value parameter is null. /// </exception> /// <exception cref="System.FormatException"> /// Value does not consist of an optional sign followed by a sequence of digits /// (zero through nine). /// </exception> private static int ConvertStringToInt32(string value) { char[] num = value.ToCharArray(); int result = 0; bool isNegative = false; int signIndex = 0; if (num[0] == '-') { isNegative = true; signIndex = 1; } else if (num[0] == '+') { signIndex = 1; } int exp = 1; for (int i = num.Length - 1; i >= signIndex; i--) { if (num[i] < '0' || num[i] > '9') { throw new ArgumentException(); } result += ((num[i] - '0') * exp); exp *= 10; } return (isNegative) ? (-1 * result) : result; } // this method ToInt32 is part of teh Convert class which we will bring over later //////////////////////////////////////////////////////////////////////////////////////// public static IPAddress GetDefaultLocalAddress() { // Special conditions are implemented here because of a ptoblem with GetHostEntry // on the digi device and NetworkInterface from the emulator. // In the emulator we must use GetHostEntry. // On the device and Windows NetworkInterface works and is preferred. try { string localAddress = GetDefaultLocalAddressImpl(); if (string.IsNullOrEmpty(localAddress)) { return IPAddress.Parse(localAddress); } } catch { } try { IPAddress localAddress = null; IPHostEntry hostEntry = Dns.GetHostEntry(""); int cnt = hostEntry.AddressList.Length; for (int i = 0; i < cnt; ++i) { if ((localAddress = hostEntry.AddressList[i]) != null) { if(localAddress.m_Address != 0) { return localAddress; } } } } catch { } return IPAddress.Any; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static string GetDefaultLocalAddressImpl(); } // class IPAddress } // namespace System.Net
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Threading; namespace System.Diagnostics { public partial class Process : IDisposable { /// <summary> /// Creates an array of <see cref="Process"/> components that are associated with process resources on a /// remote computer. These process resources share the specified process name. /// </summary> public static Process[] GetProcessesByName(string processName, string machineName) { if (processName == null) { processName = string.Empty; } Process[] procs = GetProcesses(machineName); var list = new List<Process>(); for (int i = 0; i < procs.Length; i++) { if (string.Equals(processName, procs[i].ProcessName, StringComparison.OrdinalIgnoreCase)) { list.Add(procs[i]); } else { procs[i].Dispose(); } } return list.ToArray(); } [CLSCompliant(false)] public static Process Start(string fileName, string userName, SecureString password, string domain) { ProcessStartInfo startInfo = new ProcessStartInfo(fileName); startInfo.UserName = userName; startInfo.Password = password; startInfo.Domain = domain; startInfo.UseShellExecute = false; return Start(startInfo); } [CLSCompliant(false)] public static Process Start(string fileName, string arguments, string userName, SecureString password, string domain) { ProcessStartInfo startInfo = new ProcessStartInfo(fileName, arguments); startInfo.UserName = userName; startInfo.Password = password; startInfo.Domain = domain; startInfo.UseShellExecute = false; return Start(startInfo); } /// <summary> /// Puts a Process component in state to interact with operating system processes that run in a /// special mode by enabling the native property SeDebugPrivilege on the current thread. /// </summary> public static void EnterDebugMode() { SetPrivilege(Interop.Advapi32.SeDebugPrivilege, (int)Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_ENABLED); } /// <summary> /// Takes a Process component out of the state that lets it interact with operating system processes /// that run in a special mode. /// </summary> public static void LeaveDebugMode() { SetPrivilege(Interop.Advapi32.SeDebugPrivilege, 0); } /// <summary>Stops the associated process immediately.</summary> public void Kill() { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_TERMINATE)) { if (!Interop.Kernel32.TerminateProcess(handle, -1)) throw new Win32Exception(); } } /// <summary>Discards any information about the associated process.</summary> private void RefreshCore() { _signaled = false; } /// <summary>Additional logic invoked when the Process is closed.</summary> private void CloseCore() { // Nop } /// <devdoc> /// Make sure we are watching for a process exit. /// </devdoc> /// <internalonly/> private void EnsureWatchingForExit() { if (!_watchingForExit) { lock (this) { if (!_watchingForExit) { Debug.Assert(_haveProcessHandle, "Process.EnsureWatchingForExit called with no process handle"); Debug.Assert(Associated, "Process.EnsureWatchingForExit called with no associated process"); _watchingForExit = true; try { _waitHandle = new Interop.Kernel32.ProcessWaitHandle(_processHandle); _registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(_waitHandle, new WaitOrTimerCallback(CompletionCallback), _waitHandle, -1, true); } catch { _watchingForExit = false; throw; } } } } } /// <summary> /// Instructs the Process component to wait the specified number of milliseconds for the associated process to exit. /// </summary> private bool WaitForExitCore(int milliseconds) { SafeProcessHandle handle = null; try { handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.SYNCHRONIZE, false); if (handle.IsInvalid) return true; using (Interop.Kernel32.ProcessWaitHandle processWaitHandle = new Interop.Kernel32.ProcessWaitHandle(handle)) { return _signaled = processWaitHandle.WaitOne(milliseconds); } } finally { // If we have a hard timeout, we cannot wait for the streams if (_output != null && milliseconds == Timeout.Infinite) _output.WaitUtilEOF(); if (_error != null && milliseconds == Timeout.Infinite) _error.WaitUtilEOF(); handle?.Dispose(); } } /// <summary>Gets the main module for the associated process.</summary> public ProcessModule MainModule { get { // We only return null if we couldn't find a main module. This could be because // the process hasn't finished loading the main module (most likely). // On NT, the first module is the main module. EnsureState(State.HaveId | State.IsLocal); return NtProcessManager.GetFirstModule(_processId); } } /// <summary>Checks whether the process has exited and updates state accordingly.</summary> private void UpdateHasExited() { using (SafeProcessHandle handle = GetProcessHandle( Interop.Advapi32.ProcessOptions.PROCESS_QUERY_LIMITED_INFORMATION | Interop.Advapi32.ProcessOptions.SYNCHRONIZE, false)) { if (handle.IsInvalid) { _exited = true; } else { int localExitCode; // Although this is the wrong way to check whether the process has exited, // it was historically the way we checked for it, and a lot of code then took a dependency on // the fact that this would always be set before the pipes were closed, so they would read // the exit code out after calling ReadToEnd() or standard output or standard error. In order // to allow 259 to function as a valid exit code and to break as few people as possible that // took the ReadToEnd dependency, we check for an exit code before doing the more correct // check to see if we have been signaled. if (Interop.Kernel32.GetExitCodeProcess(handle, out localExitCode) && localExitCode != Interop.Kernel32.HandleOptions.STILL_ACTIVE) { _exitCode = localExitCode; _exited = true; } else { // The best check for exit is that the kernel process object handle is invalid, // or that it is valid and signaled. Checking if the exit code != STILL_ACTIVE // does not guarantee the process is closed, // since some process could return an actual STILL_ACTIVE exit code (259). if (!_signaled) // if we just came from WaitForExit, don't repeat { using (var wh = new Interop.Kernel32.ProcessWaitHandle(handle)) { _signaled = wh.WaitOne(0); } } if (_signaled) { if (!Interop.Kernel32.GetExitCodeProcess(handle, out localExitCode)) throw new Win32Exception(); _exitCode = localExitCode; _exited = true; } } } } } /// <summary>Gets the time that the associated process exited.</summary> private DateTime ExitTimeCore { get { return GetProcessTimes().ExitTime; } } /// <summary>Gets the amount of time the process has spent running code inside the operating system core.</summary> public TimeSpan PrivilegedProcessorTime { get { return GetProcessTimes().PrivilegedProcessorTime; } } /// <summary>Gets the time the associated process was started.</summary> internal DateTime StartTimeCore { get { return GetProcessTimes().StartTime; } } /// <summary> /// Gets the amount of time the associated process has spent utilizing the CPU. /// It is the sum of the <see cref='System.Diagnostics.Process.UserProcessorTime'/> and /// <see cref='System.Diagnostics.Process.PrivilegedProcessorTime'/>. /// </summary> public TimeSpan TotalProcessorTime { get { return GetProcessTimes().TotalProcessorTime; } } /// <summary> /// Gets the amount of time the associated process has spent running code /// inside the application portion of the process (not the operating system core). /// </summary> public TimeSpan UserProcessorTime { get { return GetProcessTimes().UserProcessorTime; } } /// <summary> /// Gets or sets a value indicating whether the associated process priority /// should be temporarily boosted by the operating system when the main window /// has focus. /// </summary> private bool PriorityBoostEnabledCore { get { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION)) { bool disabled; if (!Interop.Kernel32.GetProcessPriorityBoost(handle, out disabled)) { throw new Win32Exception(); } return !disabled; } } set { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_SET_INFORMATION)) { if (!Interop.Kernel32.SetProcessPriorityBoost(handle, !value)) throw new Win32Exception(); } } } /// <summary> /// Gets or sets the overall priority category for the associated process. /// </summary> private ProcessPriorityClass PriorityClassCore { get { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION)) { int value = Interop.Kernel32.GetPriorityClass(handle); if (value == 0) { throw new Win32Exception(); } return (ProcessPriorityClass)value; } } set { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_SET_INFORMATION)) { if (!Interop.Kernel32.SetPriorityClass(handle, (int)value)) throw new Win32Exception(); } } } /// <summary> /// Gets or sets which processors the threads in this process can be scheduled to run on. /// </summary> private IntPtr ProcessorAffinityCore { get { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION)) { IntPtr processAffinity, systemAffinity; if (!Interop.Kernel32.GetProcessAffinityMask(handle, out processAffinity, out systemAffinity)) throw new Win32Exception(); return processAffinity; } } set { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_SET_INFORMATION)) { if (!Interop.Kernel32.SetProcessAffinityMask(handle, value)) throw new Win32Exception(); } } } /// <summary>Gets the ID of the current process.</summary> private static int GetCurrentProcessId() { return unchecked((int)Interop.Kernel32.GetCurrentProcessId()); } /// <summary> /// Gets a short-term handle to the process, with the given access. If a handle exists, /// then it is reused. If the process has exited, it throws an exception. /// </summary> private SafeProcessHandle GetProcessHandle() { return GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_ALL_ACCESS); } /// <summary>Get the minimum and maximum working set limits.</summary> private void GetWorkingSetLimits(out IntPtr minWorkingSet, out IntPtr maxWorkingSet) { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION)) { int ignoredFlags; if (!Interop.Kernel32.GetProcessWorkingSetSizeEx(handle, out minWorkingSet, out maxWorkingSet, out ignoredFlags)) throw new Win32Exception(); } } /// <summary>Sets one or both of the minimum and maximum working set limits.</summary> /// <param name="newMin">The new minimum working set limit, or null not to change it.</param> /// <param name="newMax">The new maximum working set limit, or null not to change it.</param> /// <param name="resultingMin">The resulting minimum working set limit after any changes applied.</param> /// <param name="resultingMax">The resulting maximum working set limit after any changes applied.</param> private void SetWorkingSetLimitsCore(IntPtr? newMin, IntPtr? newMax, out IntPtr resultingMin, out IntPtr resultingMax) { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION | Interop.Advapi32.ProcessOptions.PROCESS_SET_QUOTA)) { IntPtr min, max; int ignoredFlags; if (!Interop.Kernel32.GetProcessWorkingSetSizeEx(handle, out min, out max, out ignoredFlags)) { throw new Win32Exception(); } if (newMin.HasValue) { min = newMin.Value; } if (newMax.HasValue) { max = newMax.Value; } if ((long)min > (long)max) { if (newMin != null) { throw new ArgumentException(SR.BadMinWorkset); } else { throw new ArgumentException(SR.BadMaxWorkset); } } // We use SetProcessWorkingSetSizeEx which gives an option to follow // the max and min value even in low-memory and abundant-memory situations. // However, we do not use these flags to emulate the existing behavior if (!Interop.Kernel32.SetProcessWorkingSetSizeEx(handle, min, max, 0)) { throw new Win32Exception(); } // The value may be rounded/changed by the OS, so go get it if (!Interop.Kernel32.GetProcessWorkingSetSizeEx(handle, out min, out max, out ignoredFlags)) { throw new Win32Exception(); } resultingMin = min; resultingMax = max; } } /// <summary>Starts the process using the supplied start info.</summary> /// <param name="startInfo">The start info with which to start the process.</param> private unsafe bool StartWithCreateProcess(ProcessStartInfo startInfo) { // See knowledge base article Q190351 for an explanation of the following code. Noteworthy tricky points: // * The handles are duplicated as non-inheritable before they are passed to CreateProcess so // that the child process can not close them // * CreateProcess allows you to redirect all or none of the standard IO handles, so we use // GetStdHandle for the handles that are not being redirected StringBuilder commandLine = BuildCommandLine(startInfo.FileName, StartInfo.Arguments); Process.AppendArguments(commandLine, StartInfo.ArgumentList); Interop.Kernel32.STARTUPINFO startupInfo = new Interop.Kernel32.STARTUPINFO(); Interop.Kernel32.PROCESS_INFORMATION processInfo = new Interop.Kernel32.PROCESS_INFORMATION(); Interop.Kernel32.SECURITY_ATTRIBUTES unused_SecAttrs = new Interop.Kernel32.SECURITY_ATTRIBUTES(); SafeProcessHandle procSH = new SafeProcessHandle(); SafeThreadHandle threadSH = new SafeThreadHandle(); // handles used in parent process SafeFileHandle parentInputPipeHandle = null; SafeFileHandle childInputPipeHandle = null; SafeFileHandle parentOutputPipeHandle = null; SafeFileHandle childOutputPipeHandle = null; SafeFileHandle parentErrorPipeHandle = null; SafeFileHandle childErrorPipeHandle = null; lock (s_createProcessLock) { try { startupInfo.cb = sizeof(Interop.Kernel32.STARTUPINFO); // set up the streams if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError) { if (startInfo.RedirectStandardInput) { CreatePipe(out parentInputPipeHandle, out childInputPipeHandle, true); } else { childInputPipeHandle = new SafeFileHandle(Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_INPUT_HANDLE), false); } if (startInfo.RedirectStandardOutput) { CreatePipe(out parentOutputPipeHandle, out childOutputPipeHandle, false); } else { childOutputPipeHandle = new SafeFileHandle(Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_OUTPUT_HANDLE), false); } if (startInfo.RedirectStandardError) { CreatePipe(out parentErrorPipeHandle, out childErrorPipeHandle, false); } else { childErrorPipeHandle = new SafeFileHandle(Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_ERROR_HANDLE), false); } startupInfo.hStdInput = childInputPipeHandle.DangerousGetHandle(); startupInfo.hStdOutput = childOutputPipeHandle.DangerousGetHandle(); startupInfo.hStdError = childErrorPipeHandle.DangerousGetHandle(); startupInfo.dwFlags = Interop.Advapi32.StartupInfoOptions.STARTF_USESTDHANDLES; } // set up the creation flags parameter int creationFlags = 0; if (startInfo.CreateNoWindow) creationFlags |= Interop.Advapi32.StartupInfoOptions.CREATE_NO_WINDOW; // set up the environment block parameter string environmentBlock = null; if (startInfo._environmentVariables != null) { creationFlags |= Interop.Advapi32.StartupInfoOptions.CREATE_UNICODE_ENVIRONMENT; environmentBlock = GetEnvironmentVariablesBlock(startInfo._environmentVariables); } string workingDirectory = startInfo.WorkingDirectory; if (workingDirectory == string.Empty) workingDirectory = Directory.GetCurrentDirectory(); bool retVal; int errorCode = 0; if (startInfo.UserName.Length != 0) { if (startInfo.Password != null && startInfo.PasswordInClearText != null) { throw new ArgumentException(SR.CantSetDuplicatePassword); } Interop.Advapi32.LogonFlags logonFlags = (Interop.Advapi32.LogonFlags)0; if (startInfo.LoadUserProfile) { logonFlags = Interop.Advapi32.LogonFlags.LOGON_WITH_PROFILE; } fixed (char* passwordInClearTextPtr = startInfo.PasswordInClearText ?? string.Empty) fixed (char* environmentBlockPtr = environmentBlock) { IntPtr passwordPtr = (startInfo.Password != null) ? Marshal.SecureStringToGlobalAllocUnicode(startInfo.Password) : IntPtr.Zero; try { retVal = Interop.Advapi32.CreateProcessWithLogonW( startInfo.UserName, startInfo.Domain, (passwordPtr != IntPtr.Zero) ? passwordPtr : (IntPtr)passwordInClearTextPtr, logonFlags, null, // we don't need this since all the info is in commandLine commandLine, creationFlags, (IntPtr)environmentBlockPtr, workingDirectory, ref startupInfo, // pointer to STARTUPINFO ref processInfo // pointer to PROCESS_INFORMATION ); if (!retVal) errorCode = Marshal.GetLastWin32Error(); } finally { if (passwordPtr != IntPtr.Zero) Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr); } } } else { fixed (char* environmentBlockPtr = environmentBlock) { retVal = Interop.Kernel32.CreateProcess( null, // we don't need this since all the info is in commandLine commandLine, // pointer to the command line string ref unused_SecAttrs, // address to process security attributes, we don't need to inherit the handle ref unused_SecAttrs, // address to thread security attributes. true, // handle inheritance flag creationFlags, // creation flags (IntPtr)environmentBlockPtr, // pointer to new environment block workingDirectory, // pointer to current directory name ref startupInfo, // pointer to STARTUPINFO ref processInfo // pointer to PROCESS_INFORMATION ); if (!retVal) errorCode = Marshal.GetLastWin32Error(); } } if (processInfo.hProcess != IntPtr.Zero && processInfo.hProcess != new IntPtr(-1)) procSH.InitialSetHandle(processInfo.hProcess); if (processInfo.hThread != IntPtr.Zero && processInfo.hThread != new IntPtr(-1)) threadSH.InitialSetHandle(processInfo.hThread); if (!retVal) { if (errorCode == Interop.Errors.ERROR_BAD_EXE_FORMAT || errorCode == Interop.Errors.ERROR_EXE_MACHINE_TYPE_MISMATCH) { throw new Win32Exception(errorCode, SR.InvalidApplication); } throw new Win32Exception(errorCode); } } finally { childInputPipeHandle?.Dispose(); childOutputPipeHandle?.Dispose(); childErrorPipeHandle?.Dispose(); threadSH?.Dispose(); } } if (startInfo.RedirectStandardInput) { Encoding enc = startInfo.StandardInputEncoding ?? GetEncoding((int)Interop.Kernel32.GetConsoleCP()); _standardInput = new StreamWriter(new FileStream(parentInputPipeHandle, FileAccess.Write, 4096, false), enc, 4096); _standardInput.AutoFlush = true; } if (startInfo.RedirectStandardOutput) { Encoding enc = startInfo.StandardOutputEncoding ?? GetEncoding((int)Interop.Kernel32.GetConsoleOutputCP()); _standardOutput = new StreamReader(new FileStream(parentOutputPipeHandle, FileAccess.Read, 4096, false), enc, true, 4096); } if (startInfo.RedirectStandardError) { Encoding enc = startInfo.StandardErrorEncoding ?? GetEncoding((int)Interop.Kernel32.GetConsoleOutputCP()); _standardError = new StreamReader(new FileStream(parentErrorPipeHandle, FileAccess.Read, 4096, false), enc, true, 4096); } if (procSH.IsInvalid) return false; SetProcessHandle(procSH); SetProcessId((int)processInfo.dwProcessId); return true; } private static Encoding GetEncoding(int codePage) { Encoding enc = EncodingHelper.GetSupportedConsoleEncoding(codePage); return new ConsoleEncoding(enc); // ensure encoding doesn't output a preamble } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- private bool _signaled; private static StringBuilder BuildCommandLine(string executableFileName, string arguments) { // Construct a StringBuilder with the appropriate command line // to pass to CreateProcess. If the filename isn't already // in quotes, we quote it here. This prevents some security // problems (it specifies exactly which part of the string // is the file to execute). StringBuilder commandLine = new StringBuilder(); string fileName = executableFileName.Trim(); bool fileNameIsQuoted = (fileName.StartsWith("\"", StringComparison.Ordinal) && fileName.EndsWith("\"", StringComparison.Ordinal)); if (!fileNameIsQuoted) { commandLine.Append("\""); } commandLine.Append(fileName); if (!fileNameIsQuoted) { commandLine.Append("\""); } if (!string.IsNullOrEmpty(arguments)) { commandLine.Append(" "); commandLine.Append(arguments); } return commandLine; } /// <summary>Gets timing information for the current process.</summary> private ProcessThreadTimes GetProcessTimes() { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_LIMITED_INFORMATION, false)) { if (handle.IsInvalid) { throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString(CultureInfo.CurrentCulture))); } ProcessThreadTimes processTimes = new ProcessThreadTimes(); if (!Interop.Kernel32.GetProcessTimes(handle, out processTimes._create, out processTimes._exit, out processTimes._kernel, out processTimes._user)) { throw new Win32Exception(); } return processTimes; } } private static unsafe void SetPrivilege(string privilegeName, int attrib) { // this is only a "pseudo handle" to the current process - no need to close it later SafeProcessHandle processHandle = Interop.Kernel32.GetCurrentProcess(); SafeTokenHandle hToken = null; try { // get the process token so we can adjust the privilege on it. We DO need to // close the token when we're done with it. if (!Interop.Advapi32.OpenProcessToken(processHandle, Interop.Kernel32.HandleOptions.TOKEN_ADJUST_PRIVILEGES, out hToken)) { throw new Win32Exception(); } if (!Interop.Advapi32.LookupPrivilegeValue(null, privilegeName, out Interop.Advapi32.LUID luid)) { throw new Win32Exception(); } Interop.Advapi32.TOKEN_PRIVILEGE tp; tp.PrivilegeCount = 1; tp.Privileges.Luid = luid; tp.Privileges.Attributes = (uint)attrib; Interop.Advapi32.AdjustTokenPrivileges(hToken, false, &tp, 0, null, null); // AdjustTokenPrivileges can return true even if it failed to // set the privilege, so we need to use GetLastError if (Marshal.GetLastWin32Error() != Interop.Errors.ERROR_SUCCESS) { throw new Win32Exception(); } } finally { if (hToken != null) { hToken.Dispose(); } } } /// <devdoc> /// Gets a short-term handle to the process, with the given access. /// If a handle is stored in current process object, then use it. /// Note that the handle we stored in current process object will have all access we need. /// </devdoc> /// <internalonly/> private SafeProcessHandle GetProcessHandle(int access, bool throwIfExited) { if (_haveProcessHandle) { if (throwIfExited) { // Since haveProcessHandle is true, we know we have the process handle // open with at least SYNCHRONIZE access, so we can wait on it with // zero timeout to see if the process has exited. using (Interop.Kernel32.ProcessWaitHandle waitHandle = new Interop.Kernel32.ProcessWaitHandle(_processHandle)) { if (waitHandle.WaitOne(0)) { if (_haveProcessId) throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString(CultureInfo.CurrentCulture))); else throw new InvalidOperationException(SR.ProcessHasExitedNoId); } } } // If we dispose of our contained handle we'll be in a bad state. NetFX dealt with this // by doing a try..finally around every usage of GetProcessHandle and only disposed if // it wasn't our handle. return new SafeProcessHandle(_processHandle.DangerousGetHandle(), ownsHandle: false); } else { EnsureState(State.HaveId | State.IsLocal); SafeProcessHandle handle = SafeProcessHandle.InvalidHandle; handle = ProcessManager.OpenProcess(_processId, access, throwIfExited); if (throwIfExited && (access & Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION) != 0) { if (Interop.Kernel32.GetExitCodeProcess(handle, out _exitCode) && _exitCode != Interop.Kernel32.HandleOptions.STILL_ACTIVE) { throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString(CultureInfo.CurrentCulture))); } } return handle; } } /// <devdoc> /// Gets a short-term handle to the process, with the given access. If a handle exists, /// then it is reused. If the process has exited, it throws an exception. /// </devdoc> /// <internalonly/> private SafeProcessHandle GetProcessHandle(int access) { return GetProcessHandle(access, true); } private static void CreatePipeWithSecurityAttributes(out SafeFileHandle hReadPipe, out SafeFileHandle hWritePipe, ref Interop.Kernel32.SECURITY_ATTRIBUTES lpPipeAttributes, int nSize) { bool ret = Interop.Kernel32.CreatePipe(out hReadPipe, out hWritePipe, ref lpPipeAttributes, nSize); if (!ret || hReadPipe.IsInvalid || hWritePipe.IsInvalid) { throw new Win32Exception(); } } // Using synchronous Anonymous pipes for process input/output redirection means we would end up // wasting a worker threadpool thread per pipe instance. Overlapped pipe IO is desirable, since // it will take advantage of the NT IO completion port infrastructure. But we can't really use // Overlapped I/O for process input/output as it would break Console apps (managed Console class // methods such as WriteLine as well as native CRT functions like printf) which are making an // assumption that the console standard handles (obtained via GetStdHandle()) are opened // for synchronous I/O and hence they can work fine with ReadFile/WriteFile synchronously! private void CreatePipe(out SafeFileHandle parentHandle, out SafeFileHandle childHandle, bool parentInputs) { Interop.Kernel32.SECURITY_ATTRIBUTES securityAttributesParent = new Interop.Kernel32.SECURITY_ATTRIBUTES(); securityAttributesParent.bInheritHandle = Interop.BOOL.TRUE; SafeFileHandle hTmp = null; try { if (parentInputs) { CreatePipeWithSecurityAttributes(out childHandle, out hTmp, ref securityAttributesParent, 0); } else { CreatePipeWithSecurityAttributes(out hTmp, out childHandle, ref securityAttributesParent, 0); } // Duplicate the parent handle to be non-inheritable so that the child process // doesn't have access. This is done for correctness sake, exact reason is unclear. // One potential theory is that child process can do something brain dead like // closing the parent end of the pipe and there by getting into a blocking situation // as parent will not be draining the pipe at the other end anymore. SafeProcessHandle currentProcHandle = Interop.Kernel32.GetCurrentProcess(); if (!Interop.Kernel32.DuplicateHandle(currentProcHandle, hTmp, currentProcHandle, out parentHandle, 0, false, Interop.Kernel32.HandleOptions.DUPLICATE_SAME_ACCESS)) { throw new Win32Exception(); } } finally { if (hTmp != null && !hTmp.IsInvalid) { hTmp.Dispose(); } } } private static string GetEnvironmentVariablesBlock(IDictionary<string, string> sd) { // get the keys string[] keys = new string[sd.Count]; sd.Keys.CopyTo(keys, 0); // sort both by the keys // Windows 2000 requires the environment block to be sorted by the key // It will first converting the case the strings and do ordinal comparison. // We do not use Array.Sort(keys, values, IComparer) since it is only supported // in System.Runtime contract from 4.20.0.0 and Test.Net depends on System.Runtime 4.0.10.0 // we workaround this by sorting only the keys and then lookup the values form the keys. Array.Sort(keys, StringComparer.OrdinalIgnoreCase); // create a list of null terminated "key=val" strings StringBuilder stringBuff = new StringBuilder(); for (int i = 0; i < sd.Count; ++i) { stringBuff.Append(keys[i]); stringBuff.Append('='); stringBuff.Append(sd[keys[i]]); stringBuff.Append('\0'); } // an extra null at the end that indicates end of list will come from the string. return stringBuff.ToString(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { 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> /// BgpServiceCommunitiesOperations operations. /// </summary> internal partial class BgpServiceCommunitiesOperations : IServiceOperations<NetworkManagementClient>, IBgpServiceCommunitiesOperations { /// <summary> /// Initializes a new instance of the BgpServiceCommunitiesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal BgpServiceCommunitiesOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Gets all the available bgp service communities. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<BgpServiceCommunity>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-06-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/bgpServiceCommunities").ToString(); _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); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<BgpServiceCommunity>>(); _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<BgpServiceCommunity>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the available bgp service communities. /// </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="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<BgpServiceCommunity>>> ListNextWithHttpMessagesAsync(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, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<BgpServiceCommunity>>(); _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<BgpServiceCommunity>>(_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; } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Text; namespace Csla { /// <summary> /// Represents a databindable, customized, view of a System.Collections.IList for sorting, filtering, searching, editing, and navigation. /// </summary> /// <author>Brian Criswell</author> /// <license>CREATIVE COMMONS - Attribution 2.5 License http://creativecommons.org/ </license> [ DefaultEvent("ListChanged"), Editor("Microsoft.VSDesigner.Data.Design.DataSourceEditor, Microsoft.VSDesigner", "System.Drawing.Design.UITypeEditor, System.Drawing"), DefaultProperty("List") ] public class ObjectListView : MarshalByValueComponent, IBindingListView, ITypedList { #region Fields // Source list private IList _list; private ObjectView _defaultItem; private bool _noProperties = false; // Sorting fields private ListSortDescriptionCollection _sorts; private List<ObjectView> _sortIndex; // Filtering fields private Type _indexedType; private PropertyDescriptorCollection _objectProperties = new PropertyDescriptorCollection(null); private DataRow _filteredRow; private DataView _filteredView = new DataView(); //IBindingList fields private IBindingList _iBindingList = null; #endregion #region Constructors /// <summary> /// Creates a new instance of an ObjectListView /// </summary> public ObjectListView() : this(null, string.Empty, string.Empty) { } /// <summary> /// Creates a new instance of an ObjectListView /// </summary> /// <param name="list">The source list.</param> public ObjectListView(IList list) : this(list, string.Empty, string.Empty) { } /// <summary> /// Creates a new instance of an ObjectListView /// </summary> /// <param name="list">The source list.</param> /// <param name="sort">The property or properties, and sort order for the <see cref="Csla.ObjectListView"/>.</param> public ObjectListView(IList list, string sort) : this(list, sort, string.Empty) { } /// <summary> /// Creates a new instance of an ObjectListView /// </summary> /// <param name="list">The source list.</param> /// <param name="sort">The property or properties, and sort order for the <see cref="Csla.ObjectListView"/>.</param> /// <param name="filter">The filter to apply.</param> public ObjectListView(IList list, string sort, string filter) { this.List = list; _filteredView.RowFilter = filter; this.Sort = sort; } #endregion #region Handle List Changes bool _addingItem = false; /// <summary> /// Reacts to changes in the source list. /// </summary> /// <param name="sender">The sender of the change.</param> /// <param name="e">The change information.</param> void _iBindingList_ListChanged(object sender, ListChangedEventArgs e) { switch (e.ListChangedType) { case ListChangedType.ItemAdded: if (!_addingItem) { ObjectView addedItem = ObjectView.NewObjectView(this, _list[e.NewIndex], e.NewIndex); addedItem.PropertyChanged += new PropertyChangedEventHandler(ObjectView_PropertyChanged); addedItem.ApplyFilter(_filteredView); if (addedItem.Visible) { this.OnListChanged(ListChangedType.ItemAdded, this.FilteredIndex(this.InsertInOrder(addedItem, 0, _sortIndex.Count))); } else { this.InsertInOrder(addedItem, 0, _sortIndex.Count); } } break; case ListChangedType.ItemChanged: if (e.NewIndex >= 0) { for (int i = 0; i < _sortIndex.Count; i++) { if (_sortIndex[i].BaseIndex == e.NewIndex) { if (!_sortIndex[i].IsEdit) { HandleChange(i, e.PropertyDescriptor); } break; } } } break; case ListChangedType.ItemDeleted: int deletedIndex = -1; for (int i = 0; i < _sortIndex.Count; i++) { if (_sortIndex[i].BaseIndex == e.NewIndex) { deletedIndex = this.SortedIndex(_sortIndex[i].BaseIndex); _sortIndex[i].PropertyChanged -= new PropertyChangedEventHandler(ObjectView_PropertyChanged); _sortIndex.RemoveAt(i); break; } } for (int i = 0; i < _sortIndex.Count; i++) { if (_sortIndex[i].BaseIndex > e.NewIndex) { _sortIndex[i].BaseIndex--; } } if (deletedIndex >= 0) { this.OnListChanged(ListChangedType.ItemDeleted, deletedIndex); } break; case ListChangedType.Reset: ListSortDescriptionCollection sorts = _sorts; ((IBindingListView)this).ApplySort(sorts); break; } } private void ObjectView_PropertyChanged(object sender, PropertyChangedEventArgs e) { int index = this.SortedIndex(((ObjectView)sender).BaseIndex); if (index >= 0) { PropertyDescriptor prop = null; if (!string.IsNullOrEmpty(e.PropertyName)) { prop = _objectProperties[e.PropertyName]; } this.HandleChange(index, prop); } } private void HandleChange(int index, PropertyDescriptor prop) { int baseIndex = _sortIndex[index].BaseIndex; int oldIndex = this.SortedIndex(baseIndex); ObjectView changedItem = _sortIndex[index]; bool wasVisible = changedItem.Visible; bool needsSorting = false; if (index > 0) { needsSorting = CompareObject(changedItem, _sortIndex[index - 1]) < 0; if (needsSorting) { _sortIndex.RemoveAt(index); this.InsertInOrder(changedItem, 0, index); } } if (!needsSorting && index < _sortIndex.Count - 1) { needsSorting = CompareObject(changedItem, _sortIndex[index + 1]) > 0; if (needsSorting) { _sortIndex.RemoveAt(index); this.InsertInOrder(changedItem, index + 1, _sortIndex.Count); } } changedItem.ApplyFilter(_filteredView); int newIndex = this.SortedIndex(changedItem.BaseIndex); if (wasVisible) { if (changedItem.Visible) { if (newIndex == oldIndex) { if (prop == null) { this.OnListChanged(ListChangedType.ItemChanged, oldIndex); } else { this.OnListChanged(ListChangedType.ItemChanged, oldIndex, prop); } } else { this.OnListChanged(ListChangedType.ItemMoved, newIndex, oldIndex); } } else { this.OnListChanged(ListChangedType.ItemDeleted, oldIndex); } } else { if (changedItem.Visible) { this.OnListChanged(ListChangedType.ItemAdded, newIndex); } } } #endregion #region Methods /// <summary> /// Reapplies the filter to the list. /// </summary> private void ApplyFilter() { for (int i = 0; i < _sortIndex.Count; i++) { _sortIndex[i].ApplyFilter(_filteredView); } } /// <summary> /// A helper method that compares to values. /// </summary> /// <param name="valueA">The first value.</param> /// <param name="valueB">The second value.</param> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. /// The return value has these meanings: Less than zero valueA is less than valueB. /// Zero valueA is equal to valueB. Greater than zero valueA is greater than valueB. /// </returns> private int Compare(object valueA, object valueB) { if (object.Equals(valueA, valueB)) { return 0; } if (valueA is IComparable) { return ((IComparable)valueA).CompareTo(valueB); } return valueA.ToString().CompareTo(valueB.ToString()); } /// <summary> /// A helper method that compares items in the list. /// </summary> /// <param name="objectA">The first item.</param> /// <param name="objectB">The second item.</param> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. /// The return value has these meanings: Less than zero objectA should be before objectB. /// Zero the order of objectA and objectB should not be changed. /// Greater than zero objectA should be after objectB. /// </returns> private int CompareObject(ObjectView objectA, ObjectView objectB) { if (_sorts == null || (objectA == null && objectB == null)) { return 0; } else if (objectA == null) { return -1; } else if (objectB == null) { return 1; } int comparison = 0; for (int i = 0; i < _sorts.Count; i++) { PropertyDescriptor prop = _sorts[i].PropertyDescriptor; object valueA = objectA[prop.Name]; object valueB = objectB[prop.Name]; if (objectA.Object is IExtendSort) valueA = ((IExtendSort)objectA.Object).GetSortValue(prop, valueA); if (objectB.Object is IExtendSort) valueB = ((IExtendSort)objectB.Object).GetSortValue(prop, valueB); this.OnExtendSort(prop, valueA); this.OnExtendSort(prop, valueB); comparison = this.Compare(valueA, valueB); if (comparison != 0) { if (_sorts[i].SortDirection == ListSortDirection.Descending) { comparison *= -1; } break; } } return comparison; } /// <summary> /// Inserts an item in order. /// </summary> /// <param name="item">The item to insert.</param> /// <param name="lowIndex">The index of the lowest item to check.</param> /// <param name="highIndex">One more than the highest index to check.</param> /// <returns>The sorted index of the item.</returns> private int InsertInOrder(ObjectView item, int lowIndex, int highIndex) { if (_sorts == null || _sorts.Count == 0 || _sortIndex.Count == 0) { _sortIndex.Add(item); return _sortIndex.Count - 1; } if (lowIndex == highIndex) { // We have gotten to the end of our test if (highIndex == _sortIndex.Count) { _sortIndex.Add(item); return _sortIndex.Count - 1; } else { _sortIndex.Insert(highIndex, item); return highIndex; } } int testIndex = (lowIndex + highIndex) / 2; int comparison = CompareObject(item, _sortIndex[testIndex]); if (comparison == 0) { _sortIndex.Insert(testIndex, item); return testIndex; } else if (comparison < 0) { return this.InsertInOrder(item, lowIndex, testIndex); } else { return this.InsertInOrder(item, testIndex + 1, highIndex); } } /// <summary> /// Gets the unfiltered but sorted index of an item in the sorted list. /// </summary> /// <param name="sortedIndex">The index of the item in the filtered, sorted list.</param> /// <returns>The index of the item in the sorted list.</returns> private int UnfilteredIndex(int sortedIndex) { int filteredIndex = -1; for (int i = 0; i < _sortIndex.Count; i++) { if (_sortIndex[i].Visible) { filteredIndex++; } if (filteredIndex == sortedIndex) { return i; } } throw new IndexOutOfRangeException(); } /// <summary> /// Gets the original index of an item in the source list. /// </summary> /// <param name="sortedIndex">The index of the item in the sorted list.</param> /// <returns>The index of the item in the source list.</returns> private int OriginalIndex(int sortedIndex) { return _sortIndex[UnfilteredIndex(sortedIndex)].BaseIndex; } /// <summary> /// Gets the sorted index of an item. /// </summary> /// <param name="originalIndex">The index of the item in the source list.</param> /// <returns>The sorted index of the item.</returns> private int SortedIndex(int originalIndex) { int filteredIndex = -1; for (int i = 0; i < _sortIndex.Count; i++) { ObjectView item = _sortIndex[i]; if(item.Visible) { filteredIndex++; } if (item.BaseIndex == originalIndex) { if (item.Visible) { return filteredIndex; } return -1; } } throw new IndexOutOfRangeException(); } /// <summary> /// Gets the filtered index of an item given a sorted but not filtered index. /// </summary> /// <param name="sortedIndex">The sorted index.</param> /// <returns>The filtered index or -1 if the item is not visible.</returns> private int FilteredIndex(int sortedIndex) { if (!_sortIndex[sortedIndex].Visible) { return -1; } int filteredIndex = -1; for (int i = 0; i <= sortedIndex; i++) { if (_sortIndex[i].Visible) { filteredIndex++; } } if (_defaultItem != null) { filteredIndex++; } return filteredIndex; } #endregion #region Properties /// <summary> /// Gets or sets the source list of the ObjectListView. /// </summary> [ Description("Indicates the list this ObjectListView uses to get data."), RefreshProperties(RefreshProperties.All), Category("Data"), DefaultValue(null), AttributeProvider(typeof(IListSource)) ] public IList List { get { return _list; } set { if (!object.Equals(_list, value)) { if (_iBindingList != null) { _iBindingList.ListChanged -= new ListChangedEventHandler(_iBindingList_ListChanged); } _list = null; _noProperties = false; _indexedType = null; _objectProperties = new PropertyDescriptorCollection(null); _iBindingList = null; _filteredRow = null; _filteredView.Table = null; if (value != null) { _list = value; PropertyDescriptorCollection props; if (value is Array) { _indexedType = value.GetType().GetElementType(); props = TypeDescriptor.GetProperties(_indexedType); } else { _indexedType = System.Windows.Forms.ListBindingHelper.GetListItemType(value); if (_indexedType.Equals(typeof(object))) { props = System.Windows.Forms.ListBindingHelper.GetListItemProperties(value); if (props.Count > 0) { _indexedType = props[0].ComponentType; } } props = TypeDescriptor.GetProperties(_indexedType); } for (int i = 0; i < props.Count; i++) { _objectProperties.Add(new ObjectView.ObjectViewPropertyDescriptor(props[i])); } DataTable table = new DataTable("Table"); foreach (PropertyDescriptor prop in _objectProperties) { if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { Type nullableType = prop.PropertyType.GetGenericArguments()[0]; table.Columns.Add(prop.Name, prop.PropertyType.GetGenericArguments()[0]); } else table.Columns.Add(prop.Name, prop.PropertyType); } if (table.Columns.Count == 0) { _noProperties = true; table.Columns.Add("Value", typeof(object)); } _filteredRow = table.Rows.Add(); _filteredView.Table = table; if (_noProperties) { _objectProperties.Add(new ObjectView.ObjectViewPropertyDescriptor(TypeDescriptor.GetProperties(_filteredView[0])[0])); } } if (value is IBindingList) { _iBindingList = (IBindingList)value; _iBindingList.ListChanged += new ListChangedEventHandler(_iBindingList_ListChanged); } } } } /// <summary> /// Gets or sets whether to include a default item in the ObjectListView. /// </summary> [ Category("Data"), Description("Indicates whether this ObjectListView should display a default item as the first item in the list."), DefaultValue(false) ] public bool IncludeDefault { get { return _defaultItem != null; } set { if (value) { if (!this.IncludeDefault) { _defaultItem = new ObjectView.DefaultItemObjectView(this); // Set the newIndex to -1 as OnListChanged will increment it // because IncludeDefault is now true. this.OnListChanged(ListChangedType.ItemAdded, -1); } } else { if (this.IncludeDefault) { _defaultItem = null; // Set the newIndex to 0 as OnListChanged will no longer increment it // because IncludeDefault is now false. this.OnListChanged(ListChangedType.ItemDeleted, 0); } } } } internal Type IndexedType { get { return _indexedType; } } internal bool NoProperties { get { return _noProperties; } } internal PropertyDescriptorCollection ObjectProperties { get { return _objectProperties; } } /// <summary> /// Gets or sets the sort property or properties, and sort order for the <see cref="Csla.ObjectListView"/> /// </summary> [ Category("Data"), Description("Indicates the name of the properties and the order in which items are returned by this ObjectListView."), DefaultValue("") ] public string Sort { get { ((IBindingListView)_filteredView).ApplySort(_sorts); return _filteredView.Sort; } set { if (_filteredView.Sort != value || _sortIndex == null) { _filteredView.Sort = value; ((IBindingListView)this).ApplySort(((IBindingListView)_filteredView).SortDescriptions); } } } #endregion #region ExtendSort event /// <summary> /// Extends the sorting algorithm by allowing a listener to exchange a comparison value with another value. /// </summary> public event EventHandler<ExtendSortEventArgs> ExtendSort; private void OnExtendSort(PropertyDescriptor property, object value) { EventHandler<ExtendSortEventArgs> temp = ExtendSort; if (temp != null) { temp(this, new ExtendSortEventArgs(property, value)); } } #endregion #region ObjectListView enumerator /// <summary> /// An enumerator for navigating through an ObjectListView /// </summary> private class ObjectListViewEnumerator : IEnumerator { #region Fields private ObjectListView _parent; private int _index; private bool _isValid = true; #endregion #region Constructor /// <summary> /// Initializes a new instance of the Csla.ObjectListView.ObjectListViewEnumerator class /// with the given System.Collections.Generic.IList and System.Collections.Generic.List&lt;ListItem>. /// </summary> /// <param name="parent">The parent ObjectListView.</param> public ObjectListViewEnumerator(ObjectListView parent) { _parent = parent; _parent.ListChanged += new ListChangedEventHandler(_parent_ListChanged); Reset(); } #endregion #region Properties /// <summary> /// Gets the current element in the collection. /// </summary> public ObjectView Current { get { if (_index < 0) { throw new InvalidOperationException("The enumerator is positioned before the first element of the collection."); } else if (_index >= _parent.Count) { throw new InvalidOperationException("The enumerator is positioned after the last element of the collection."); } return _parent[_index]; } } /// <summary> /// Gets the current element in the collection. /// </summary> Object System.Collections.IEnumerator.Current { get { return this.Current; } } #endregion #region Methods /// <summary> /// Invalidates the enumerator because the underlying list has changed. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _parent_ListChanged(object sender, ListChangedEventArgs e) { _isValid = false; } /// <summary> /// Advances the enumerator to the next element of the collection. /// </summary> /// <returns>true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.</returns> public bool MoveNext() { if (!_isValid) { throw new InvalidOperationException("The collection was modified after the enumerator was created."); } _index++; return _index < _parent.Count; } /// <summary> /// Sets the enumerator to its initial position, which is before the first element in the collection. /// </summary> public void Reset() { if (!_isValid) { throw new InvalidOperationException("The collection was modified after the enumerator was created."); } _index = -1; } #endregion } #endregion #region IBindingListView Members /// <summary> /// Applies a series of sort properties and directions to this ObjectListView. /// </summary> /// <param name="sorts">The sort directions and properties.</param> void IBindingListView.ApplySort(System.ComponentModel.ListSortDescriptionCollection sorts) { _sorts = sorts; if (_sortIndex != null) { for (int i = 0; i < _sortIndex.Count; i++) { _sortIndex[i].PropertyChanged -= new PropertyChangedEventHandler(ObjectView_PropertyChanged); } } if (_list == null) { _sortIndex = new List<ObjectView>(); } else { _sortIndex = new List<ObjectView>(_list.Count); for (int i = 0; i < _list.Count; i++) { ObjectView item = ObjectView.NewObjectView(this, _list[i], i); item.PropertyChanged += new PropertyChangedEventHandler(ObjectView_PropertyChanged); item.ApplyFilter(_filteredView); this.InsertInOrder(item, 0, _sortIndex.Count); } } this.OnListChanged(ListChangedType.Reset, -1); } /// <summary> /// Gets or sets the expression used to filter which items are viewed in the Csla.ObjectListView. /// </summary> [ Category("Data"), Description("Indicates an expression used to filter the items returned by this ObjectListView."), DefaultValue("") ] public string Filter { get { return _filteredView.RowFilter; } set { if (value == null) value = string.Empty; if (_filteredView.RowFilter != value) { _filteredView.RowFilter = value; this.ApplyFilter(); this.OnListChanged(ListChangedType.Reset, -1); } } } /// <summary> /// Removes the filter on the Csla.ObjectListView. /// </summary> void IBindingListView.RemoveFilter() { this.Filter = string.Empty; } /// <summary> /// Gets the sort properties and directions of the Csla.ObjectListView. /// </summary> ListSortDescriptionCollection IBindingListView.SortDescriptions { get { return _sorts; } } /// <summary> /// Gets whether advanced sorting is supported. /// </summary> bool IBindingListView.SupportsAdvancedSorting { get { return true; } } /// <summary> /// Gets whether filtering is supported. /// </summary> bool IBindingListView.SupportsFiltering { get { return true; } } #endregion #region IBindingList Members /// <summary> /// Adds an index to the source IBindingList. /// </summary> /// <param name="property"></param> void IBindingList.AddIndex(PropertyDescriptor property) { if (_iBindingList != null) { _iBindingList.AddIndex(property); } } /// <summary> /// Adds a new item to the source IBindingList. /// </summary> /// <returns></returns> public virtual ObjectView AddNew() { if (this.AllowNew) { if (_list == null) { throw new InvalidOperationException("Cannot add new items when the list is not set."); } try { _addingItem = true; ObjectView item; if (_iBindingList != null) { item = ObjectView.NewObjectView(this, _iBindingList.AddNew(), _list.Count - 1, true); } else { Object obj = Activator.CreateInstance(_indexedType); _list.Add(obj); item = ObjectView.NewObjectView(this, obj, _list.Count - 1, true); } item.PropertyChanged += new PropertyChangedEventHandler(ObjectView_PropertyChanged); item.BeginEdit(); _sortIndex.Add(item); return item; } finally { _addingItem = false; } } throw new NotSupportedException("Adding new items is not supported."); } object IBindingList.AddNew() { return this.AddNew(); } private bool _allowEdit = true; /// <summary> /// Gets whether the source IBindingList allows edits. /// </summary> [ Category("Data"), Description("Indicates whether this ObjectListView and the user interface associated with it allows edits."), DefaultValue(true) ] public bool AllowEdit { get { bool allowEdit = _allowEdit; if (_iBindingList != null) { allowEdit &= _iBindingList.AllowEdit; } else if(_list != null) { allowEdit &= !_list.IsReadOnly; } return allowEdit; } set { _allowEdit = value; } } private bool _allowNew = true; /// <summary> /// Gets whether the source IBindingList allows new items. /// </summary> [ Category("Data"), Description("Indicates whether this ObjectListView and the user interface associated with it allows new items to be added."), DefaultValue(true) ] public bool AllowNew { get { bool allowNew = _allowNew; if (_iBindingList != null) { allowNew &= _iBindingList.AllowNew; } else if (_list != null) { _allowNew &= !_list.IsReadOnly && !_list.IsFixedSize; } return allowNew; } set { _allowNew = value; } } private bool _allowRemove = true; /// <summary> /// Gets whether the source IBindingList allows removing of items. /// </summary> [ Category("Data"), Description("Indicates whether this ObjectListView and the user interface associated with it allows items to be removed."), DefaultValue(true) ] public bool AllowRemove { get { bool allowRemove = _allowRemove; if (_iBindingList != null) { allowRemove &= _iBindingList.AllowRemove; } else if (_list != null) { allowRemove &= !_list.IsReadOnly & !_list.IsFixedSize; } return allowRemove; } set { _allowRemove = value; } } /// <summary> /// Applies a sort property and direction to the Csla.ObjectListView. /// </summary> /// <param name="property">The sort property.</param> /// <param name="direction">The sort direction.</param> void IBindingList.ApplySort(PropertyDescriptor property, ListSortDirection direction) { if (property == null) throw new ArgumentNullException("property"); ((IBindingListView)this).ApplySort(new ListSortDescriptionCollection(new ListSortDescription[] { new ListSortDescription(property, direction) })); } /// <summary> /// Gets the first item whose property matches the key. /// </summary> /// <param name="propertyName">The name of the property to search.</param> /// <param name="key">The value for which to search.</param> /// <returns>The index of the first item whose property matches the key.</returns> public int Find(string propertyName, object key) { return ((IBindingList)this).Find(_objectProperties[propertyName], key); } /// <summary> /// Gets the first item whose property matches the key. /// </summary> /// <param name="property">The property to search.</param> /// <param name="key">The value for which to search.</param> /// <returns>The index of the first item whose property matches the key.</returns> int IBindingList.Find(PropertyDescriptor property, object key) { if (((IBindingList)this).SupportsSearching) { if (property == null) throw new ArgumentNullException("property"); if (this.IncludeDefault && object.Equals(key, _defaultItem[property.Name])) { return 0; } int index = -1; for (int i = 0; i < _sortIndex.Count; i++) { if (_sortIndex[i].Visible) { index++; if (object.Equals(key, _sortIndex[i][property.Name])) { if (this.IncludeDefault) { return index + 1; } return index; } } } return -1; } throw new NotSupportedException("Searching is not supported."); } /// <summary> /// Gets whether the Csla.ObjectListView is sorted. /// </summary> bool IBindingList.IsSorted { get { return _sorts != null; } } /// <summary> /// Occurs when the list managed by the ObjectListView changes. /// </summary> public event ListChangedEventHandler ListChanged; /// <summary> /// Raises the System.Data.DataView.ListChanged event. /// </summary> /// <param name="listChangedType">The type of change.</param> /// <param name="newIndex">The index of the row affected by the change.</param> /// <remarks> /// Used when adding or deleting a row. Also used with an index of -1 when resetting the /// list. Also used when a row has been changed but that change is not the result of a /// specific property changing in the row. /// </remarks> protected void OnListChanged(ListChangedType listChangedType, int newIndex) { if (_defaultItem != null) newIndex++; if (ListChanged != null) this.ListChanged(this, new ListChangedEventArgs(listChangedType, newIndex)); } /// <summary> /// Raises the System.Data.DataView.ListChanged event. /// </summary> /// <param name="listChangedType">The type of change.</param> /// <param name="newIndex">The index of the row affected by the change.</param> /// <param name="oldIndex">The previous index of the row.</param> /// <remarks>Used when moving a row.</remarks> protected void OnListChanged(ListChangedType listChangedType, int newIndex, int oldIndex) { if (_defaultItem != null) { newIndex++; oldIndex++; } if (ListChanged != null) this.ListChanged(this, new ListChangedEventArgs(listChangedType, newIndex, oldIndex)); } /// <summary> /// Raises the System.Data.DataView.ListChanged event. /// </summary> /// <param name="listChangedType">The type of change.</param> /// <param name="newIndex">The index of the row affected by the change.</param> /// <param name="propDesc">The property that changed on the row.</param> /// <remarks>Used when a change in the row is caused by a changing property.</remarks> protected void OnListChanged(ListChangedType listChangedType, int newIndex, PropertyDescriptor propDesc) { if (_defaultItem != null) newIndex++; if (ListChanged != null) this.ListChanged(this, new ListChangedEventArgs(listChangedType, newIndex, propDesc)); } /// <summary> /// Removes an index from the source System.ComponentModel.IBindingList. /// </summary> /// <param name="property">The property from which to remove the index.</param> void IBindingList.RemoveIndex(PropertyDescriptor property) { if (_iBindingList != null) { _iBindingList.RemoveIndex(property); } } /// <summary> /// Removes a sort from the Csla.ObjectListView. /// </summary> void IBindingList.RemoveSort() { if (_sorts != null) { ((IBindingListView)this).ApplySort(null); OnListChanged(ListChangedType.Reset, -1); } } /// <summary> /// Gets the sort direction of the first sort property. /// </summary> ListSortDirection IBindingList.SortDirection { get { if (_sorts == null) { return ListSortDirection.Ascending; } return _sorts[0].SortDirection; } } /// <summary> /// Gets the first property by which the Csla.ObjectListView is sorted. /// </summary> PropertyDescriptor IBindingList.SortProperty { get { if (_sorts == null || _sorts.Count == 0) { return null; } return _sorts[0].PropertyDescriptor; } } /// <summary> /// Gets whether the Csla.ObjectListView supports change notification. /// </summary> bool IBindingList.SupportsChangeNotification { get { return true; } } /// <summary> /// Gets whether the Csla.ObjectListView supports searching. /// </summary> bool IBindingList.SupportsSearching { get { return true; } } /// <summary> /// Gets whether the Csla.ObjectListView supports sorting. /// </summary> bool IBindingList.SupportsSorting { get { return true; } } #endregion #region IList Members /// <summary> /// Adds an object to the source list. /// </summary> /// <param name="value">The new object.</param> /// <returns>The sorted index of the object.</returns> int IList.Add(object value) { throw new NotImplementedException(); } /// <summary> /// Clears the source list. /// </summary> void IList.Clear() { throw new NotImplementedException(); } /// <summary> /// Gets whether the Csla.ObjectListView contains the given object. /// </summary> /// <param name="value">The object for which to check.</param> /// <returns>Whether the Csla.ObjectListView contains the given object.</returns> bool IList.Contains(object value) { return ((IList)this).IndexOf(value) >= 0; } /// <summary> /// Gets the sorted index of the given object. /// </summary> /// <param name="value">The object for which to check.</param> /// <returns>The sorted index of the given object, or -1 if the object is not in the Csla.ObjectListView.</returns> int IList.IndexOf(object value) { int index = -1; if (value is ObjectView) { if (this.IncludeDefault && _defaultItem.Equals(value)) { return 0; } for (int i = 0; i < _sortIndex.Count; i++) { if (_sortIndex[i].Equals(value)) { index = i; if (this.IncludeDefault) { index++; } break; } } } return index; } /// <summary> /// Inserts an item in the Csla.ObjectListView. /// </summary> /// <param name="index">The index at which to insert.</param> /// <param name="value">The item to insert.</param> /// <remarks>Throws a System.NotImplementedException.</remarks> void IList.Insert(int index, object value) { throw new NotImplementedException(); } /// <summary> /// Gets whether the Csla.ObjectListView is a fixed size. /// </summary> bool IList.IsFixedSize { get { return _list.IsFixedSize; } } /// <summary> /// Gets whether the source list is read only. /// </summary> bool IList.IsReadOnly { get { return _list.IsReadOnly; } } /// <summary> /// Removes an item from the Csla.ObjectListView. /// </summary> /// <param name="value">The item to remove.</param> void IList.Remove(object value) { if (this.AllowRemove) { if (value == _defaultItem) { // Cannot delete the default item, but do not raise an exception. return; } for (int i = 0; i < _sortIndex.Count; i++) { if (_sortIndex[i].Equals(value)) { _list.RemoveAt(_sortIndex[i].BaseIndex); return; } } throw new IndexOutOfRangeException(); } throw new InvalidOperationException(); } /// <summary> /// Removes the item at the sorted index. /// </summary> /// <param name="index">The sorted index to remove.</param> void IList.RemoveAt(int index) { if (this.AllowRemove) { if (this.IncludeDefault) { if (index == 0) { // Cannot delete the default item, but do not raise an exception. return; } index--; } _list.RemoveAt(this.OriginalIndex(index)); return; } throw new InvalidOperationException(); } /// <summary> /// Gets or sets the item at the given sorted index. /// </summary> /// <param name="index">The sorted index.</param> /// <returns>The item at the given sorted index.</returns> public ObjectView this[int index] { get { if (this.IncludeDefault) { if (index == 0) { return _defaultItem; } index--; } return _sortIndex[this.UnfilteredIndex(index)]; } } object IList.this[int index] { get { return this[index]; } set { throw new NotImplementedException(); } } #endregion #region ICollection Members /// <summary> /// Copies the elements of the Csla.ObjectListView into the given array starting at the given index. /// </summary> /// <param name="array">The array into which to copy.</param> /// <param name="index">The index at which to start the copying.</param> public void CopyTo(Array array, int index) { if (_list == null) { throw new InvalidOperationException("Cannot copy while the list is not set."); } if (this.Filter.Length == 0) { _list.CopyTo(array, index); } else { for (int i = 0; i < this.Count; i++) { array.SetValue(this[i], i); } } } /// <summary> /// Gets the number of elements in the Csla.ObjectListView. /// </summary> [Browsable(false)] public int Count { get { int filteredCount = 0; if (_list != null) { if (this.Filter.Length == 0) { filteredCount = _list.Count; } else { for (int i = 0; i < _sortIndex.Count; i++) { if (_sortIndex[i].Visible) { filteredCount++; } } } if (this.IncludeDefault) { filteredCount++; } } return filteredCount; } } /// <summary> /// Gets whether the Csla.ObjectListView is synchronized. /// </summary> bool ICollection.IsSynchronized { get { return false; } } /// <summary> /// Gets the SyncRoot. /// </summary> object ICollection.SyncRoot { get { return this; } } #endregion #region IEnumerable Members /// <summary> /// Gets an System.Collections.IEnumerator to navigate over the Csla.ObjectListView. /// </summary> /// <returns></returns> public IEnumerator GetEnumerator() { return new ObjectListViewEnumerator(this); } #endregion #region ITypedList Members PropertyDescriptorCollection ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors) { PropertyDescriptorCollection pdc; if (null == listAccessors) { pdc = new PropertyDescriptorCollection(null); BrowsableAttribute browsable = new BrowsableAttribute(true); // Return properties in sort order. for (int i = 0; i < _objectProperties.Count; i++) { PropertyDescriptor prop = _objectProperties[i]; if (prop.Attributes.Contains(browsable)) { pdc.Add(prop); } } } else { // Return child list shape. PropertyDescriptorCollection itemProps = System.Windows.Forms.ListBindingHelper.GetListItemProperties(listAccessors[0].PropertyType); PropertyDescriptorCollection props = new PropertyDescriptorCollection(null); for (int i = 0; i < itemProps.Count; i++) { props.Add(new ObjectView.ObjectViewPropertyDescriptor(itemProps[i])); } pdc = props; } return pdc; } string ITypedList.GetListName(PropertyDescriptor[] listAccessors) { if (_indexedType != null) return _indexedType.Name; if (_list != null && _list.GetType().IsArray) { string name = _list.GetType().Name; return name.Substring(0, name.Length - 2); } return string.Empty; } #endregion } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file=".cs" company="sgmunn"> // (c) sgmunn 2012 // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of // the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using MonoTouch.UIKit; using MonoTouch.Foundation; using System.ComponentModel; using MonoKit.DataBinding; using System.Drawing; using MonoKit.UI.Elements; namespace MonoKit.UI.Controls { public class ElementTableViewCell : UITableViewCell, INotifyPropertyChanged { private string text; public ElementTableViewCell() : base(UITableViewCellStyle.Default, "Element") { } public ElementTableViewCell(UITableViewCellStyle style, NSString reuseIdentifer) : base(style, reuseIdentifer) { } public string Text { get { return this.text; } set { if (this.text != value) { this.text = value; this.OnPropertyChanged("Text"); this.TextUpdated(value); } } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void TextUpdated(string newValue) { // todo: if the original value is null or empty this doesn;t update properly this.TextLabel.Text = newValue; } protected void OnPropertyChanged(string propertyName) { var ev = this.PropertyChanged; if (ev != null) { ev(this, new PropertyChangedEventArgs(propertyName)); } } } public class ElementTableViewCell<T> : ElementTableViewCell { private T value; public ElementTableViewCell() : base(UITableViewCellStyle.Subtitle, new NSString("StringElement")) { } public ElementTableViewCell(UITableViewCellStyle style, NSString reuseIdentifer) : base(style, reuseIdentifer) { } public T Value { get { return this.value; } set { if (!object.Equals(this.value, value)) { this.value = value; this.OnPropertyChanged("Value"); this.ValueUpdated(value); } } } protected virtual void ValueUpdated(T newValue) { } } public class StringElementTableViewCell : ElementTableViewCell<string> { public StringElementTableViewCell() : base(UITableViewCellStyle.Subtitle, new NSString("StringElement")) { } public StringElementTableViewCell(UITableViewCellStyle style, NSString reuseIdentifer) : base(style, reuseIdentifer) { } protected override void ValueUpdated(string newValue) { if (this.DetailTextLabel != null) { this.DetailTextLabel.Text = newValue; } } } public class DisclosureElementTableViewCell : ElementTableViewCell { public DisclosureElementTableViewCell() : base(UITableViewCellStyle.Subtitle, new NSString("DisclosureElement")) { this.Accessory = UITableViewCellAccessory.DisclosureIndicator; } public DisclosureElementTableViewCell(UITableViewCellStyle style, NSString reuseIdentifer) : base(style, reuseIdentifer) { this.Accessory = UITableViewCellAccessory.DisclosureIndicator; } } public class BooleanElementTableViewCell : ElementTableViewCell<bool> { private UISwitch boolSwitch; public BooleanElementTableViewCell() : base(UITableViewCellStyle.Default, new NSString("BooleanElement")) { this.ConfigureCell(); } public BooleanElementTableViewCell(UITableViewCellStyle style, NSString reuseIdentifer) : base(style, reuseIdentifer) { this.ConfigureCell(); } protected override void ValueUpdated(bool newValue) { base.ValueUpdated(newValue); this.boolSwitch.On = newValue; } protected override void Dispose (bool disposing) { if (disposing) { this.AccessoryView = null; this.boolSwitch.Dispose(); this.boolSwitch = null; } base.Dispose (disposing); } private void ConfigureCell () { this.boolSwitch = new UISwitch(); this.AccessoryView = this.boolSwitch; // The 'On' property doesn't trigger a property change so we need to do it ourselves this.boolSwitch.ValueChanged += (sender, e) => { this.Value = this.boolSwitch.On; }; } } public class CheckboxElementTableViewCell : ElementTableViewCell<bool> { public CheckboxElementTableViewCell() : base(UITableViewCellStyle.Default, new NSString("CheckboxElement")) { } public CheckboxElementTableViewCell(UITableViewCellStyle style, NSString reuseIdentifer) : base(style, reuseIdentifer) { } protected override void ValueUpdated(bool newValue) { this.Accessory = newValue ? UITableViewCellAccessory.Checkmark : UITableViewCellAccessory.None; } } public class ButtonElementTableViewCell : ElementTableViewCell<string> { private UIButton button; public ButtonElementTableViewCell() : base(UITableViewCellStyle.Default, new NSString("ButtonElement")) { this.ConfigureCell(); } public ButtonElementTableViewCell(UITableViewCellStyle style, NSString reuseIdentifer) : base(style, reuseIdentifer) { this.ConfigureCell(); } protected override void TextUpdated(string newValue) { //base.TextUpdated(newValue); this.button.SetTitle(newValue, UIControlState.Normal); } protected override void Dispose (bool disposing) { if (disposing) { this.AccessoryView = null; this.button.Dispose(); this.button = null; } base.Dispose (disposing); } public override void LayoutSubviews() { base.LayoutSubviews(); this.ContentView.BringSubviewToFront(this.button); this.button.Frame = this.ContentView.Bounds; } private void ConfigureCell () { this.button = new UIButton(UIButtonType.RoundedRect); this.button.AutoresizingMask = UIViewAutoresizing.FlexibleMargins; this.button.TintColor = UIColor.Red; this.ContentView.AddSubview(this.button); } } public class TextInputElementTableViewCell : ElementTableViewCell<string> { private UITextField textField; private string placeholder; private UIKeyboardType keyboardType; public TextInputElementTableViewCell() : base(UITableViewCellStyle.Default, new NSString("TextInputElement")) { this.ConfigureCell(); } public TextInputElementTableViewCell(UITableViewCellStyle style, NSString reuseIdentifer) : base(style, reuseIdentifer) { this.ConfigureCell(); } public string Placeholder { get { return this.placeholder; } set { if (value != this.placeholder) { this.placeholder = value; this.textField.Placeholder = value; } } } public UIKeyboardType KeyboardType { get { return this.keyboardType; } set { if (value != this.keyboardType) { this.keyboardType = value; this.textField.KeyboardType = value; } } } public UITextField TextField { get { return this.textField; } } public override void TouchesEnded (NSSet touches, UIEvent evt) { base.TouchesEnded (touches, evt); if (evt.Type == UIEventType.Touches) { this.textField.BecomeFirstResponder(); } } public override bool BecomeFirstResponder() { return this.textField.BecomeFirstResponder(); } public override bool ResignFirstResponder() { return this.textField.ResignFirstResponder(); } protected override void ValueUpdated(string newValue) { base.ValueUpdated(newValue); this.textField.Text = newValue; } protected override void TextUpdated (string newValue) { base.TextUpdated (newValue); this.textField.Frame = this.CalculateTextFieldFrame(newValue); this.ContentView.BringSubviewToFront(this.textField); } protected override void Dispose (bool disposing) { if (disposing) { this.textField.Dispose(); this.textField = null; } base.Dispose (disposing); } private void ConfigureCell () { this.SelectionStyle = UITableViewCellSelectionStyle.None; this.textField = new UITextField(this.CalculateTextFieldFrame(this.Text)) { Placeholder = this.Placeholder, KeyboardType = this.KeyboardType, VerticalAlignment = UIControlContentVerticalAlignment.Center, ClearButtonMode = UITextFieldViewMode.WhileEditing, }; this.textField.Font = UIFont.SystemFontOfSize(17); this.textField.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleLeftMargin; this.ContentView.AddSubview(this.textField); // The 'Text' property doesn't trigger a property change so we need to do it ourselves, but only when the editing has ended this.textField.Ended += (sender, e) => { this.Value = this.textField.Text; }; } private RectangleF CalculateTextFieldFrame(string textValue) { float margin = 10; var textSize = new RectangleF (margin, 10, this.ContentView.Bounds.Width - (margin * 2), this.ContentView.Bounds.Height - (margin * 2)); if (!String.IsNullOrEmpty(textValue)) { var sz = this.CalculateEntrySize(null); textSize = new RectangleF (sz.Width, (this.ContentView.Bounds.Height - sz.Height) / 2 - 1, sz.Width * 2 - margin, sz.Height); } return textSize; } private SizeF CalculateEntrySize (UITableView tv) { var sz = this.StringSize("W", UIFont.SystemFontOfSize (17)); float w = this.ContentView.Bounds.Width / 3; return new SizeF(w, sz.Height); } } public class PasswordInputElementTableViewCell : TextInputElementTableViewCell { public PasswordInputElementTableViewCell() : base(UITableViewCellStyle.Default, new NSString("PasswordInputElement")) { this.TextField.SecureTextEntry = true; } public PasswordInputElementTableViewCell(UITableViewCellStyle style, NSString reuseIdentifer) : base(style, reuseIdentifer) { this.TextField.SecureTextEntry = true; } } public class DateInputElementTableViewCell : ElementTableViewCell<DateTime> { private UIDateField dateField; public DateInputElementTableViewCell() : base(UITableViewCellStyle.Default, new NSString("DateInputElement")) { this.ConfigureCell(); } public DateInputElementTableViewCell(UITableViewCellStyle style, NSString reuseIdentifer) : base(style, reuseIdentifer) { this.ConfigureCell(); } public override void TouchesEnded (NSSet touches, UIEvent evt) { base.TouchesEnded (touches, evt); if (evt.Type == UIEventType.Touches) { this.dateField.BecomeFirstResponder(); } } public override bool BecomeFirstResponder() { return this.dateField.BecomeFirstResponder(); } protected override void Dispose (bool disposing) { if (disposing) { this.dateField.Dispose(); this.dateField = null; } base.Dispose (disposing); } protected override void TextUpdated (string newValue) { base.TextUpdated (newValue); this.dateField.Frame = this.CalculateTextFieldFrame(newValue); this.ContentView.BringSubviewToFront(this.dateField); } protected override void ValueUpdated(DateTime newValue) { base.ValueUpdated(newValue); this.dateField.Date = newValue; } private void DateValueChanged(object sender, EventArgs args) { this.Value = (sender as UIDateField).Date; } private void ConfigureCell () { this.SelectionStyle = UITableViewCellSelectionStyle.None; this.dateField = new UIDateField(this.CalculateTextFieldFrame(this.Text)) { AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleLeftMargin, }; this.ContentView.AddSubview(this.dateField); var proxy = new EventProxy<DateInputElementTableViewCell, EventArgs>(this); proxy.Handle = (t,s,o) => { t.Value = ((UIDateField)s).Date; }; this.dateField.ValueChanged += proxy.HandleEvent; } private RectangleF CalculateTextFieldFrame(string textValue) { float margin = 10; var textSize = new RectangleF (margin, 10, this.ContentView.Bounds.Width - (margin * 2), this.ContentView.Bounds.Height - (margin * 2)); if (!String.IsNullOrEmpty(textValue)) { var sz = this.CalculateEntrySize(null); textSize = new RectangleF (sz.Width, (this.ContentView.Bounds.Height - sz.Height) / 2 - 1, sz.Width * 2 - margin, sz.Height); } return textSize; } private SizeF CalculateEntrySize (UITableView tv) { var sz = this.StringSize("W", UIFont.SystemFontOfSize (17)); float w = this.ContentView.Bounds.Width / 3; return new SizeF(w, sz.Height); } } public class DecimalInputElementTableViewCell : ElementTableViewCell<decimal> { private UITextField textField; public DecimalInputElementTableViewCell() : base(UITableViewCellStyle.Default, new NSString("DecimalInputElement")) { this.ConfigureCell(); } public DecimalInputElementTableViewCell(UITableViewCellStyle style, NSString reuseIdentifer) : base(style, reuseIdentifer) { this.ConfigureCell(); } public override void TouchesEnded (NSSet touches, UIEvent evt) { base.TouchesEnded (touches, evt); if (evt.Type == UIEventType.Touches) { this.textField.BecomeFirstResponder(); } } public override bool BecomeFirstResponder() { return this.textField.BecomeFirstResponder(); } protected override void Dispose (bool disposing) { if (disposing) { this.textField.Dispose(); this.textField = null; } base.Dispose (disposing); } protected override void TextUpdated (string newValue) { base.TextUpdated (newValue); this.textField.Frame = this.CalculateTextFieldFrame(newValue); this.ContentView.BringSubviewToFront(this.textField); } protected override void ValueUpdated(decimal newValue) { base.ValueUpdated(newValue); this.textField.Text = string.Format("{0}", newValue); } private void ConfigureCell () { this.SelectionStyle = UITableViewCellSelectionStyle.None; this.textField = new UITextField(this.CalculateTextFieldFrame(this.Text)) { KeyboardType = UIKeyboardType.DecimalPad, AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleLeftMargin, }; this.ContentView.AddSubview(this.textField); var proxy = new EventProxy<DecimalInputElementTableViewCell, EventArgs>(this); proxy.Handle = (t,s,o) => { try { t.Value = Convert.ToDecimal(((UITextField)s).Text); } catch { t.Value = 0; } }; this.textField.Ended += proxy.HandleEvent; } private RectangleF CalculateTextFieldFrame(string textValue) { float margin = 10; var textSize = new RectangleF (margin, 10, this.ContentView.Bounds.Width - (margin * 2), this.ContentView.Bounds.Height - (margin * 2)); if (!String.IsNullOrEmpty(textValue)) { var sz = this.CalculateEntrySize(null); textSize = new RectangleF (sz.Width, (this.ContentView.Bounds.Height - sz.Height) / 2 - 1, sz.Width * 2 - margin, sz.Height); } return textSize; } private SizeF CalculateEntrySize (UITableView tv) { var sz = this.StringSize("W", UIFont.SystemFontOfSize (17)); float w = this.ContentView.Bounds.Width / 3; return new SizeF(w, sz.Height); } } public class CustomElementTableViewCell : ElementTableViewCell<string> { private UIDateField textField; public CustomElementTableViewCell() : base(UITableViewCellStyle.Default, new NSString("CustomElement")) { this.ConfigureCell(); } public CustomElementTableViewCell(UITableViewCellStyle style, NSString reuseIdentifer) : base(style, reuseIdentifer) { this.ConfigureCell(); } public override void TouchesEnded (NSSet touches, UIEvent evt) { base.TouchesEnded (touches, evt); if (evt.Type == UIEventType.Touches) { if (this.textField.CanBecomeFirstResponder) { this.textField.BecomeFirstResponder(); } } } protected override void ValueUpdated(string newValue) { base.ValueUpdated(newValue); } protected override void TextUpdated (string newValue) { base.TextUpdated (newValue); this.textField.Frame = this.CalculateTextFieldFrame(newValue); this.ContentView.BringSubviewToFront(this.textField); } protected override void Dispose (bool disposing) { if (disposing) { this.textField.Dispose(); this.textField = null; } base.Dispose (disposing); } private void ConfigureCell () { this.SelectionStyle = UITableViewCellSelectionStyle.None; this.textField = new UIDateField(this.CalculateTextFieldFrame(this.Text)) { InputAccessoryView = new UILabel(new RectangleF(0, 0, 100, 50)), }; this.textField.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleLeftMargin; this.ContentView.AddSubview(this.textField); } private RectangleF CalculateTextFieldFrame(string textValue) { float margin = 10; var textSize = new RectangleF (margin, 10, this.ContentView.Bounds.Width - (margin * 2), this.ContentView.Bounds.Height - (margin * 2)); if (!String.IsNullOrEmpty(textValue)) { var sz = this.CalculateEntrySize(null); textSize = new RectangleF (sz.Width, (this.ContentView.Bounds.Height - sz.Height) / 2 - 1, sz.Width * 2 - margin, sz.Height); } return textSize; } private SizeF CalculateEntrySize (UITableView tv) { var sz = this.StringSize("W", UIFont.SystemFontOfSize (17)); float w = this.ContentView.Bounds.Width / 3; return new SizeF(w, sz.Height); } } }
// 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.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Buffers.Text { public static partial class Base64 { /// <summary> /// Decode the span of UTF-8 encoded text represented as base 64 into binary data. /// If the input is not a multiple of 4, it will decode as much as it can, to the closest multiple of 4. /// /// <param name="utf8">The input span which contains UTF-8 encoded text in base 64 that needs to be decoded.</param> /// <param name="bytes">The output span which contains the result of the operation, i.e. the decoded binary data.</param> /// <param name="consumed">The number of input bytes consumed during the operation. This can be used to slice the input for subsequent calls, if necessary.</param> /// <param name="written">The number of bytes written into the output span. This can be used to slice the output for subsequent calls, if necessary.</param> /// <param name="isFinalBlock">True (default) when the input span contains the entire data to decode. /// Set to false only if it is known that the input span contains partial data with more data to follow.</param> /// <returns>It returns the OperationStatus enum values: /// - Done - on successful processing of the entire input span /// - DestinationTooSmall - if there is not enough space in the output span to fit the decoded input /// - NeedMoreData - only if isFinalBlock is false and the input is not a multiple of 4, otherwise the partial input would be considered as InvalidData /// - InvalidData - if the input contains bytes outside of the expected base 64 range, or if it contains invalid/more than two padding characters, /// or if the input is incomplete (i.e. not a multiple of 4) and isFinalBlock is true.</returns> /// </summary> public static OperationStatus DecodeFromUtf8(ReadOnlySpan<byte> utf8, Span<byte> bytes, out int consumed, out int written, bool isFinalBlock = true) { ref byte srcBytes = ref utf8.DangerousGetPinnableReference(); ref byte destBytes = ref bytes.DangerousGetPinnableReference(); int srcLength = utf8.Length & ~0x3; // only decode input up to the closest multiple of 4. int destLength = bytes.Length; int sourceIndex = 0; int destIndex = 0; if (utf8.Length == 0) goto DoneExit; ref sbyte decodingMap = ref s_decodingMap[0]; // Last bytes could have padding characters, so process them separately and treat them as valid only if isFinalBlock is true // if isFinalBlock is false, padding characters are considered invalid int skipLastChunk = isFinalBlock ? 4 : 0; int maxSrcLength = 0; if (destLength >= GetMaxDecodedFromUtf8Length(srcLength)) { maxSrcLength = srcLength - skipLastChunk; } else { // This should never overflow since destLength here is less than int.MaxValue / 4 * 3 (i.e. 1610612733) // Therefore, (destLength / 3) * 4 will always be less than 2147483641 maxSrcLength = (destLength / 3) * 4; } while (sourceIndex < maxSrcLength) { int result = Decode(ref Unsafe.Add(ref srcBytes, sourceIndex), ref decodingMap); if (result < 0) goto InvalidExit; WriteThreeLowOrderBytes(ref Unsafe.Add(ref destBytes, destIndex), result); destIndex += 3; sourceIndex += 4; } if (maxSrcLength != srcLength - skipLastChunk) goto DestinationSmallExit; // If input is less than 4 bytes, srcLength == sourceIndex == 0 // If input is not a multiple of 4, sourceIndex == srcLength != 0 if (sourceIndex == srcLength) { if (isFinalBlock) goto InvalidExit; goto NeedMoreExit; } // if isFinalBlock is false, we will never reach this point int i0 = Unsafe.Add(ref srcBytes, srcLength - 4); int i1 = Unsafe.Add(ref srcBytes, srcLength - 3); int i2 = Unsafe.Add(ref srcBytes, srcLength - 2); int i3 = Unsafe.Add(ref srcBytes, srcLength - 1); i0 = Unsafe.Add(ref decodingMap, i0); i1 = Unsafe.Add(ref decodingMap, i1); i0 <<= 18; i1 <<= 12; i0 |= i1; if (i3 != EncodingPad) { i2 = Unsafe.Add(ref decodingMap, i2); i3 = Unsafe.Add(ref decodingMap, i3); i2 <<= 6; i0 |= i3; i0 |= i2; if (i0 < 0) goto InvalidExit; if (destIndex > destLength - 3) goto DestinationSmallExit; WriteThreeLowOrderBytes(ref Unsafe.Add(ref destBytes, destIndex), i0); destIndex += 3; } else if (i2 != EncodingPad) { i2 = Unsafe.Add(ref decodingMap, i2); i2 <<= 6; i0 |= i2; if (i0 < 0) goto InvalidExit; if (destIndex > destLength - 2) goto DestinationSmallExit; Unsafe.Add(ref destBytes, destIndex) = (byte)(i0 >> 16); Unsafe.Add(ref destBytes, destIndex + 1) = (byte)(i0 >> 8); destIndex += 2; } else { if (i0 < 0) goto InvalidExit; if (destIndex > destLength - 1) goto DestinationSmallExit; Unsafe.Add(ref destBytes, destIndex) = (byte)(i0 >> 16); destIndex += 1; } sourceIndex += 4; if (srcLength != utf8.Length) goto InvalidExit; DoneExit: consumed = sourceIndex; written = destIndex; return OperationStatus.Done; DestinationSmallExit: if (srcLength != utf8.Length && isFinalBlock) goto InvalidExit; // if input is not a multiple of 4, and there is no more data, return invalid data instead consumed = sourceIndex; written = destIndex; return OperationStatus.DestinationTooSmall; NeedMoreExit: consumed = sourceIndex; written = destIndex; return OperationStatus.NeedMoreData; InvalidExit: consumed = sourceIndex; written = destIndex; return OperationStatus.InvalidData; } /// <summary> /// Returns the maximum length (in bytes) of the result if you were to deocde base 64 encoded text within a byte span of size "length". /// </summary> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="length"/> is less than 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int GetMaxDecodedFromUtf8Length(int length) { if (length < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); return (length >> 2) * 3; } /// <summary> /// Decode the span of UTF-8 encoded text in base 64 (in-place) into binary data. /// The decoded binary output is smaller than the text data contained in the input (the operation deflates the data). /// If the input is not a multiple of 4, it will not decode any. /// /// <param name="buffer">The input span which contains the base 64 text data that needs to be decoded.</param> /// <param name="written">The number of bytes written into the buffer.</param> /// <returns>It returns the OperationStatus enum values: /// - Done - on successful processing of the entire input span /// - InvalidData - if the input contains bytes outside of the expected base 64 range, or if it contains invalid/more than two padding characters, /// or if the input is incomplete (i.e. not a multiple of 4). /// It does not return DestinationTooSmall since that is not possible for base 64 decoding. /// It does not return NeedMoreData since this method tramples the data in the buffer and /// hence can only be called once with all the data in the buffer.</returns> /// </summary> public static OperationStatus DecodeFromUtf8InPlace(Span<byte> buffer, out int written) { int bufferLength = buffer.Length; int sourceIndex = 0; int destIndex = 0; // only decode input if it is a multiple of 4 if (bufferLength != ((bufferLength >> 2) * 4)) goto InvalidExit; if (bufferLength == 0) goto DoneExit; ref byte bufferBytes = ref buffer.DangerousGetPinnableReference(); ref sbyte decodingMap = ref s_decodingMap[0]; while (sourceIndex < bufferLength - 4) { int result = Decode(ref Unsafe.Add(ref bufferBytes, sourceIndex), ref decodingMap); if (result < 0) goto InvalidExit; WriteThreeLowOrderBytes(ref Unsafe.Add(ref bufferBytes, destIndex), result); destIndex += 3; sourceIndex += 4; } int i0 = Unsafe.Add(ref bufferBytes, bufferLength - 4); int i1 = Unsafe.Add(ref bufferBytes, bufferLength - 3); int i2 = Unsafe.Add(ref bufferBytes, bufferLength - 2); int i3 = Unsafe.Add(ref bufferBytes, bufferLength - 1); i0 = Unsafe.Add(ref decodingMap, i0); i1 = Unsafe.Add(ref decodingMap, i1); i0 <<= 18; i1 <<= 12; i0 |= i1; if (i3 != EncodingPad) { i2 = Unsafe.Add(ref decodingMap, i2); i3 = Unsafe.Add(ref decodingMap, i3); i2 <<= 6; i0 |= i3; i0 |= i2; if (i0 < 0) goto InvalidExit; WriteThreeLowOrderBytes(ref Unsafe.Add(ref bufferBytes, destIndex), i0); destIndex += 3; } else if (i2 != EncodingPad) { i2 = Unsafe.Add(ref decodingMap, i2); i2 <<= 6; i0 |= i2; if (i0 < 0) goto InvalidExit; Unsafe.Add(ref bufferBytes, destIndex) = (byte)(i0 >> 16); Unsafe.Add(ref bufferBytes, destIndex + 1) = (byte)(i0 >> 8); destIndex += 2; } else { if (i0 < 0) goto InvalidExit; Unsafe.Add(ref bufferBytes, destIndex) = (byte)(i0 >> 16); destIndex += 1; } DoneExit: written = destIndex; return OperationStatus.Done; InvalidExit: written = destIndex; return OperationStatus.InvalidData; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int Decode(ref byte encodedBytes, ref sbyte decodingMap) { int i0 = encodedBytes; int i1 = Unsafe.Add(ref encodedBytes, 1); int i2 = Unsafe.Add(ref encodedBytes, 2); int i3 = Unsafe.Add(ref encodedBytes, 3); i0 = Unsafe.Add(ref decodingMap, i0); i1 = Unsafe.Add(ref decodingMap, i1); i2 = Unsafe.Add(ref decodingMap, i2); i3 = Unsafe.Add(ref decodingMap, i3); i0 <<= 18; i1 <<= 12; i2 <<= 6; i0 |= i3; i1 |= i2; i0 |= i1; return i0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void WriteThreeLowOrderBytes(ref byte destination, int value) { destination = (byte)(value >> 16); Unsafe.Add(ref destination, 1) = (byte)(value >> 8); Unsafe.Add(ref destination, 2) = (byte)value; } // Pre-computing this table using a custom string(s_characters) and GenerateDecodingMapAndVerify (found in tests) private static readonly sbyte[] s_decodingMap = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, //62 is placed at index 43 (for +), 63 at index 47 (for /) 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, //52-61 are placed at index 48-57 (for 0-9), 64 at index 61 (for =) -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, //0-25 are placed at index 65-90 (for A-Z) -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, //26-51 are placed at index 97-122 (for a-z) -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // Bytes over 122 ('z') are invalid and cannot be decoded -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // Hence, padding the map with 255, which indicates invalid input -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; } }