context
stringlengths
2.52k
185k
gt
stringclasses
1 value
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2019 Hotcakes Commerce, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #endregion using System; using com.paypal.sdk.profiles; using com.paypal.sdk.services; using com.paypal.soap.api; namespace Hotcakes.PaypalWebServices { /// <summary> /// Summary description for PayPalAPI. /// </summary> [Serializable] public class PayPalAPI { private readonly CallerServices caller; public PayPalAPI(IAPIProfile PayPalProfile) { caller = new CallerServices {APIProfile = PayPalProfile}; } public static CurrencyCodeType GetCurrencyCodeType(string currencyCode) { if (Enum.IsDefined(typeof (CurrencyCodeType), currencyCode)) { return (CurrencyCodeType) Enum.Parse(typeof (CurrencyCodeType), currencyCode, true); } return CurrencyCodeType.USD; } public static CountryCodeType GetCountryCode(string isoCode) { if (Enum.IsDefined(typeof (CountryCodeType), isoCode)) { return (CountryCodeType) Enum.Parse(typeof (CountryCodeType), isoCode, true); } return CountryCodeType.US; } public TransactionSearchResponseType TransactionSearch(DateTime startDate, DateTime endDate) { // Create the request object var concreteRequest = new TransactionSearchRequestType { StartDate = startDate.ToUniversalTime(), EndDate = endDate.AddDays(1).ToUniversalTime(), EndDateSpecified = true }; //end date inclusive return (TransactionSearchResponseType) caller.Call("TransactionSearch", concreteRequest); } public GetTransactionDetailsResponseType GetTransactionDetails(string trxID) { // Create the request object var concreteRequest = new GetTransactionDetailsRequestType {TransactionID = trxID}; return (GetTransactionDetailsResponseType) caller.Call("GetTransactionDetails", concreteRequest); } public RefundTransactionResponseType RefundTransaction(string trxID, string refundType, string amount, CurrencyCodeType storeCurrency) { // Create the request object var concreteRequest = new RefundTransactionRequestType { TransactionID = trxID, RefundType = RefundType.Partial, RefundTypeSpecified = true, Amount = new BasicAmountType { currencyID = storeCurrency, Value = amount } }; return (RefundTransactionResponseType) caller.Call("RefundTransaction", concreteRequest); } public DoDirectPaymentResponseType DoDirectPayment(string paymentAmount, string buyerBillingLastName, string buyerBillingFirstName, string buyerShippingLastName, string buyerShippingFirstName, string buyerBillingAddress1, string buyerBillingAddress2, string buyerBillingCity, string buyerBillingState, string buyerBillingPostalCode, CountryCodeType buyerBillingCountryCode, string creditCardType, string creditCardNumber, string CVV2, int expMonth, int expYear, PaymentActionCodeType paymentAction, string ipAddress, string buyerShippingAddress1, string buyerShippingAddress2, string buyerShippingCity, string buyerShippingState, string buyerShippingPostalCode, CountryCodeType buyerShippingCountryCode, string invoiceId, CurrencyCodeType storeCurrency) { // Create the request object var pp_Request = new DoDirectPaymentRequestType { DoDirectPaymentRequestDetails = new DoDirectPaymentRequestDetailsType { IPAddress = ipAddress, MerchantSessionId = string.Empty, PaymentAction = paymentAction, CreditCard = new CreditCardDetailsType { CreditCardNumber = creditCardNumber } } }; // Create the request details object switch (creditCardType) { case "Visa": pp_Request.DoDirectPaymentRequestDetails.CreditCard.CreditCardType = CreditCardTypeType.Visa; break; case "MasterCard": pp_Request.DoDirectPaymentRequestDetails.CreditCard.CreditCardType = CreditCardTypeType.MasterCard; break; case "Discover": pp_Request.DoDirectPaymentRequestDetails.CreditCard.CreditCardType = CreditCardTypeType.Discover; break; case "Amex": pp_Request.DoDirectPaymentRequestDetails.CreditCard.CreditCardType = CreditCardTypeType.Amex; break; } pp_Request.DoDirectPaymentRequestDetails.CreditCard.CVV2 = CVV2; pp_Request.DoDirectPaymentRequestDetails.CreditCard.ExpMonth = expMonth; pp_Request.DoDirectPaymentRequestDetails.CreditCard.ExpYear = expYear; pp_Request.DoDirectPaymentRequestDetails.CreditCard.ExpMonthSpecified = true; pp_Request.DoDirectPaymentRequestDetails.CreditCard.ExpYearSpecified = true; pp_Request.DoDirectPaymentRequestDetails.CreditCard.CardOwner = new PayerInfoType { Payer = string.Empty, PayerID = string.Empty, PayerStatus = PayPalUserStatusCodeType.unverified, PayerCountry = CountryCodeType.US, Address = new AddressType { Street1 = buyerBillingAddress1, Street2 = buyerBillingAddress2, CityName = buyerBillingCity, StateOrProvince = buyerBillingState, PostalCode = buyerBillingPostalCode, Country = buyerBillingCountryCode, CountrySpecified = true } }; pp_Request.DoDirectPaymentRequestDetails.PaymentDetails = new PaymentDetailsType { ShipToAddress = new AddressType { Name = buyerShippingFirstName + " " + buyerShippingLastName, Street1 = buyerShippingAddress1, Street2 = buyerShippingAddress2, CityName = buyerShippingCity, StateOrProvince = buyerShippingState, PostalCode = buyerShippingPostalCode, Country = buyerShippingCountryCode, CountrySpecified = true } }; pp_Request.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerName = new PersonNameType { FirstName = buyerBillingFirstName, LastName = buyerBillingLastName }; pp_Request.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal = new BasicAmountType(); pp_Request.DoDirectPaymentRequestDetails.PaymentDetails.InvoiceID = invoiceId; pp_Request.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal.currencyID = storeCurrency; pp_Request.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal.Value = paymentAmount; pp_Request.DoDirectPaymentRequestDetails.PaymentDetails.ButtonSource = "HotcakesCommerce_Cart_DP_US"; return (DoDirectPaymentResponseType) caller.Call("DoDirectPayment", pp_Request); } public SetExpressCheckoutResponseType SetExpressCheckout(PaymentDetailsItemType[] itemsDetails, string itemsTotal, string taxTotal, string orderTotal, string returnURL, string cancelURL, PaymentActionCodeType paymentAction, CurrencyCodeType currencyCodeType, SolutionTypeType solutionType, string invoiceId, bool isNonShipping) { // Create the request object var pp_request = new SetExpressCheckoutRequestType { // Create the request details object SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType { CancelURL = cancelURL, ReturnURL = returnURL, NoShipping = isNonShipping ? "1" : "0", SolutionType = solutionType, SolutionTypeSpecified = true } }; //pp_request.SetExpressCheckoutRequestDetails.ReqBillingAddress = (isNonShipping ? "1" : "0"); var paymentDetails = new PaymentDetailsType { InvoiceID = invoiceId, PaymentAction = paymentAction, PaymentActionSpecified = true, PaymentDetailsItem = itemsDetails, ItemTotal = new BasicAmountType { currencyID = currencyCodeType, Value = itemsTotal }, TaxTotal = new BasicAmountType { currencyID = currencyCodeType, Value = taxTotal }, OrderTotal = new BasicAmountType { currencyID = currencyCodeType, Value = orderTotal } }; pp_request.SetExpressCheckoutRequestDetails.PaymentDetails = new[] {paymentDetails}; return (SetExpressCheckoutResponseType) caller.Call("SetExpressCheckout", pp_request); } public SetExpressCheckoutResponseType SetExpressCheckout(PaymentDetailsItemType[] itemsDetails, string itemsTotal, string taxTotal, string shippingTotal, string orderTotal, string returnURL, string cancelURL, PaymentActionCodeType paymentAction, CurrencyCodeType currencyCodeType, SolutionTypeType solutionType, string name, string countryISOCode, string street1, string street2, string city, string region, string postalCode, string phone, string invoiceId, bool isNonShipping) { // Create the request object var pp_request = new SetExpressCheckoutRequestType { SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType { CancelURL = cancelURL, ReturnURL = returnURL, AddressOverride = "1", NoShipping = isNonShipping ? "1" : "0", SolutionType = solutionType, SolutionTypeSpecified = true } }; // Create the request details object //pp_request.SetExpressCheckoutRequestDetails.ReqBillingAddress = (isNonShipping ? "1" : "0"); var paymentDetails = new PaymentDetailsType { InvoiceID = invoiceId, PaymentAction = paymentAction, PaymentActionSpecified = true, PaymentDetailsItem = itemsDetails, ItemTotal = new BasicAmountType { currencyID = currencyCodeType, Value = itemsTotal }, TaxTotal = new BasicAmountType { currencyID = currencyCodeType, Value = taxTotal }, ShippingTotal = new BasicAmountType { currencyID = currencyCodeType, Value = shippingTotal }, OrderTotal = new BasicAmountType { currencyID = currencyCodeType, Value = orderTotal }, ShipToAddress = new AddressType { AddressStatusSpecified = false, AddressOwnerSpecified = false, Street1 = street1, Street2 = street2, CityName = city, StateOrProvince = region, PostalCode = postalCode, CountrySpecified = true, Country = GetCountryCode(countryISOCode), Phone = phone, Name = name } }; pp_request.SetExpressCheckoutRequestDetails.PaymentDetails = new[] {paymentDetails}; return (SetExpressCheckoutResponseType) caller.Call("SetExpressCheckout", pp_request); } public GetExpressCheckoutDetailsResponseType GetExpressCheckoutDetails(string token) { // Create the request object var pp_request = new GetExpressCheckoutDetailsRequestType {Token = token}; return (GetExpressCheckoutDetailsResponseType) caller.Call("GetExpressCheckoutDetails", pp_request); } public DoExpressCheckoutPaymentResponseType DoExpressCheckoutPayment(string token, string payerID, string paymentAmount, PaymentActionCodeType paymentAction, CurrencyCodeType currencyCodeType, string invoiceId) { // Create the request object var pp_request = new DoExpressCheckoutPaymentRequestType { DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType { Token = token, PayerID = payerID } }; // Create the request details object var paymentDetails = new PaymentDetailsType { InvoiceID = invoiceId, PaymentAction = paymentAction, PaymentActionSpecified = true, OrderTotal = new BasicAmountType { currencyID = currencyCodeType, Value = paymentAmount } }; paymentDetails.ButtonSource = "HotcakesCommerce_Cart_EC_US"; pp_request.DoExpressCheckoutPaymentRequestDetails.PaymentDetails = new[] {paymentDetails}; return (DoExpressCheckoutPaymentResponseType) caller.Call("DoExpressCheckoutPayment", pp_request); } public DoVoidResponseType DoVoid(string authorizationId, string note) { var pp_request = new DoVoidRequestType { AuthorizationID = authorizationId, Note = note }; return (DoVoidResponseType) caller.Call("DoVoid", pp_request); } public DoCaptureResponseType DoCapture(string authorizationId, string note, string value, CurrencyCodeType currencyId, string invoiceId) { var pp_request = new DoCaptureRequestType { AuthorizationID = authorizationId, Note = note, Amount = new BasicAmountType { Value = value, currencyID = currencyId }, InvoiceID = invoiceId }; return (DoCaptureResponseType) caller.Call("DoCapture", pp_request); } } }
using System; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.Utility; using Random = UnityEngine.Random; namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof (CharacterController))] [RequireComponent(typeof (AudioSource))] public class FirstPersonController : MonoBehaviour { [SerializeField] private bool m_IsWalking; [SerializeField] private float m_WalkSpeed; [SerializeField] private float m_RunSpeed; [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten; [SerializeField] private float m_JumpSpeed; [SerializeField] private float m_StickToGroundForce; [SerializeField] private float m_GravityMultiplier; [SerializeField] private MouseLook m_MouseLook; [SerializeField] private bool m_UseFovKick; [SerializeField] private FOVKick m_FovKick = new FOVKick(); [SerializeField] private bool m_UseHeadBob; [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob(); [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob(); [SerializeField] private float m_StepInterval; [SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from. [SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground. [SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground. private Camera m_Camera; private bool m_Jump; private float m_YRotation; private Vector2 m_Input; private Vector3 m_MoveDir = Vector3.zero; private CharacterController m_CharacterController; private CollisionFlags m_CollisionFlags; private bool m_PreviouslyGrounded; private Vector3 m_OriginalCameraPosition; private float m_StepCycle; private float m_NextStep; private bool m_Jumping; private AudioSource m_AudioSource; // Use this for initialization private void Start() { m_CharacterController = GetComponent<CharacterController>(); m_Camera = Camera.main; m_OriginalCameraPosition = m_Camera.transform.localPosition; m_FovKick.Setup(m_Camera); m_HeadBob.Setup(m_Camera, m_StepInterval); m_StepCycle = 0f; m_NextStep = m_StepCycle/2f; m_Jumping = false; m_AudioSource = GetComponent<AudioSource>(); m_MouseLook.Init(transform , m_Camera.transform); } // Update is called once per frame private void Update() { RotateView(); // the jump state needs to read here to make sure it is not missed if (!m_Jump) { m_Jump = CrossPlatformInputManager.GetButtonDown("Jump"); } if (!m_PreviouslyGrounded && m_CharacterController.isGrounded) { StartCoroutine(m_JumpBob.DoBobCycle()); PlayLandingSound(); m_MoveDir.y = 0f; m_Jumping = false; } if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded) { m_MoveDir.y = 0f; } m_PreviouslyGrounded = m_CharacterController.isGrounded; } private void PlayLandingSound() { m_AudioSource.clip = m_LandSound; m_AudioSource.Play(); m_NextStep = m_StepCycle + .5f; } private void FixedUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height/2f); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x*speed; m_MoveDir.z = desiredMove.z*speed; if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; if (m_Jump) { m_MoveDir.y = m_JumpSpeed; PlayJumpSound(); m_Jump = false; m_Jumping = true; } } else { m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime); ProgressStepCycle(speed); UpdateCameraPosition(speed); } private void PlayJumpSound() { m_AudioSource.clip = m_JumpSound; m_AudioSource.Play(); } private void ProgressStepCycle(float speed) { if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0)) { m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))* Time.fixedDeltaTime; } if (!(m_StepCycle > m_NextStep)) { return; } m_NextStep = m_StepCycle + m_StepInterval; PlayFootStepAudio(); } private void PlayFootStepAudio() { if (!m_CharacterController.isGrounded) { return; } // pick & play a random footstep sound from the array, // excluding sound at index 0 int n = Random.Range(1, m_FootstepSounds.Length); m_AudioSource.clip = m_FootstepSounds[n]; m_AudioSource.PlayOneShot(m_AudioSource.clip); // move picked sound to index 0 so it's not picked next time m_FootstepSounds[n] = m_FootstepSounds[0]; m_FootstepSounds[0] = m_AudioSource.clip; } private void UpdateCameraPosition(float speed) { Vector3 newCameraPosition; if (!m_UseHeadBob) { return; } if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded) { m_Camera.transform.localPosition = m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten))); newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset(); } else { newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset(); } m_Camera.transform.localPosition = newCameraPosition; } private void GetInput(out float speed) { // Read input float horizontal = CrossPlatformInputManager.GetAxis("Horizontal"); float vertical = 0;// CrossPlatformInputManager.GetAxis("Vertical"); bool waswalking = m_IsWalking; #if !MOBILE_INPUT // On standalone builds, walk/run speed is modified by a key press. // keep track of whether or not the character is walking or running m_IsWalking = !Input.GetKey(KeyCode.LeftShift); #endif // set the desired speed to be walking or running speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed; m_Input = new Vector2(horizontal, vertical); /* // normalize input if it exceeds 1 in combined length: if (m_Input.sqrMagnitude > 1) { m_Input.Normalize(); } */ // handle speed change to give an fov kick // only if the player is going to a run, is running and the fovkick is to be used if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0) { StopAllCoroutines(); StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown()); } } private void RotateView() { m_MouseLook.LookRotation (transform, m_Camera.transform); } private void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; //dont move the rigidbody if the character is on top of it if (m_CollisionFlags == CollisionFlags.Below) { return; } if (body == null || body.isKinematic) { return; } body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using System.Text; using Xunit; public class EncodingTest { // The characters to encode: // Latin Small Letter Z (U+007A) // Latin Small Letter A (U+0061) // Combining Breve (U+0306) // Latin Small Letter AE With Acute (U+01FD) // Greek Small Letter Beta (U+03B2) // a high-surrogate value (U+D8FF) // a low-surrogate value (U+DCFF) private static char[] s_myChars = new char[] { 'z', 'a', '\u0306', '\u01FD', '\u03B2', '\uD8FF', '\uDCFF' }; private static string s_myString = new String(s_myChars); private static byte[] s_leBytes = new byte[] { 0x7A, 0x00, 0x61, 0x00, 0x06, 0x03, 0xFD, 0x01, 0xB2, 0x03, 0xFF, 0xD8, 0xFF, 0xDC }; private static byte[] s_beBytes = new byte[] { 0x00, 0x7A, 0x00, 0x61, 0x03, 0x06, 0x01, 0xFD, 0x03, 0xB2, 0xD8, 0xFF, 0xDC, 0xFF }; private static byte[] s_utf8Bytes = new byte[] { 0x7A, 0x61, 0xCC, 0x86, 0xC7, 0xBD, 0xCE, 0xB2, 0xF1, 0x8F, 0xB3, 0xBF }; private static byte[] s_utf8PreambleBytes = new byte[] { 0xEF, 0xBB, 0xBF }; private static byte[] s_unicodePreambleBytes = new byte[] { 0xFF, 0xFE }; private static byte[] s_unicodeBigEndianPreambleBytes = new byte[] { 0xFE, 0xFF }; private static bool s_IsInitialized = false; static internal void EnsureInitialization() { if (!s_IsInitialized) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); s_IsInitialized = true; } } internal class EncodingId { internal EncodingId(string name, int codepage) { _name = name; _codepage = codepage; } internal string Name { get { return _name; } } internal int Codepage { get { return _codepage; } } private int _codepage; private string _name; } internal class CodePageToWebNameMapping { public CodePageToWebNameMapping(int codePage, string webName) { _codePage = codePage; _webName = webName; } public int CodePage { get { return _codePage; } } public string WebName { get { return _webName; } } private int _codePage; private string _webName; } [Fact] public static void TestDefaultCodePage() { Assert.False(s_IsInitialized); Encoding utf8Encoding = Encoding.GetEncoding(0); Assert.Equal(Encoding.UTF8.CodePage, utf8Encoding.CodePage); Assert.Equal(Encoding.UTF8.WebName, utf8Encoding.WebName); EnsureInitialization(); Encoding encoding = Encoding.GetEncoding(0); Assert.True(encoding.CodePage != 0); Assert.True(encoding.WebName != Encoding.UTF8.WebName); } private static void TestRoundtrippingCodepageEncoding(string encodingName, byte[] bytes, string s) { Encoding enc = Encoding.GetEncoding(encodingName); string resultString = enc.GetString(bytes, 0, bytes.Length); Assert.True(s.Equals(resultString)); byte[] resultBytes = enc.GetBytes(resultString); Assert.Equal(bytes.Length, resultBytes.Length); for (int i = 0; i < bytes.Length; i++) { Assert.True(bytes[i] == resultBytes[i], "encodingName: " + encodingName); } } [Fact] public static void TestSpecificCodepageEncodings() { EnsureInitialization(); byte[] bytes = new byte[] { 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF, 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF }; string unicodeStr = "\x00A0\x00A1\x00A2\x00A3\x00A4\x00A5\x00A6\x00A7\x00A8\x00A9\x00AA\x00AB\x00AC\x00AD\x00AE\x00AF\x00C0\x00C1\x00C2\x00C3\x00C4" + "\x00C5\x00C6\x00C7\x00C8\x00C9\x00CA\x00CB\x00CC\x00CD\x00CE\x00CF"; TestRoundtrippingCodepageEncoding("iso-8859-1", bytes, unicodeStr); bytes = new byte[] { 0xC7, 0xE1, 0xE1, 0xE5, 0x20, 0xC7, 0xCD, 0xCF }; unicodeStr = "\x0627\x0644\x0644\x0647\x0020\x0627\x062D\x062F"; TestRoundtrippingCodepageEncoding("Windows-1256", bytes, unicodeStr); bytes = new byte[] { 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF }; unicodeStr = "\x00D0\x00D1\x00D2\x00D3\x00D4\x00D5\x00D6\x00D7\x00D8\x00D9\x00DA\x00DB\x00DC\x00DD\x00DE\x00DF"; TestRoundtrippingCodepageEncoding("Windows-1252", bytes, unicodeStr); bytes = new byte[] { 0xCD, 0xE2, 0xCD, 0xE3, 0xCD, 0xE4 }; unicodeStr = "\x5916\x8C4C\x5F2F"; TestRoundtrippingCodepageEncoding("GB2312", bytes, unicodeStr); bytes = new byte[] { 0x81, 0x30, 0x89, 0x37, 0x81, 0x30, 0x89, 0x38, 0xA8, 0xA4, 0xA8, 0xA2, 0x81, 0x30, 0x89, 0x39, 0x81, 0x30, 0x8A, 0x30 }; unicodeStr = "\x00DE\x00DF\x00E0\x00E1\x00E2\x00E3"; TestRoundtrippingCodepageEncoding("GB18030", bytes, unicodeStr); bytes = new byte[] { 0x5B, 0x5C, 0x5D, 0x5E, 0x7B, 0x7C, 0x7D, 0x7E }; unicodeStr = "\x005B\x005C\x005D\x005E\x007B\x007C\x007D\x007E"; TestRoundtrippingCodepageEncoding("us-ascii", bytes, unicodeStr); } [Fact] public static void TestCodepageEncoding() { EnsureInitialization(); foreach (var id in s_encodingIdTable) { // Console.WriteLine(id.Name); Encoding enc = Encoding.GetEncoding(id.Name); byte[] bytes = enc.GetBytes("Az"); char[] chars = enc.GetChars(bytes); Assert.True(chars.Length == 2 && chars[0] == 'A' && chars[1] == 'z'); // Encoding.GetEncoding(id.Codepage); } } [Fact] public static void TestDecodingIso2022() { EnsureInitialization(); byte[] japaneseEncodedBuffer = new byte[] { 0xA, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x1B, 0x1, 0x2, 0x3, 0x4, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x0E, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x41, 0x42, 0x0E, 0x25, 0x0F, 0x43 }; string codepageName = "iso-2022-jp"; Decoder jpDecoder = Encoding.GetEncoding(codepageName).GetDecoder(); const int BUFFER_SIZE = 100; char[] buffer = new char[BUFFER_SIZE]; int byteIndex = 0; int charIndex = 0; while (byteIndex < japaneseEncodedBuffer.Length) { int charCount = jpDecoder.GetChars(japaneseEncodedBuffer, byteIndex, 1, buffer, charIndex); if (charCount > 0) { charIndex += charCount; } byteIndex++; } int[] expectedResult = new int[] { 0xA, 0x30CA, 0x30CA, 0x30CA, 0x30CA, 0x1B, 0x1, 0x2, 0x3, 0x4, 0x30CA, 0xFF65, 0xFF8A, 0x41, 0x42, 0xFF65, 0x43}; Assert.True(charIndex == expectedResult.Length); for (int i = 0; i < charIndex; i++) Assert.True(expectedResult[i] == (int)buffer[i]); } [Fact] public static void TestDecodingGB18030() { EnsureInitialization(); string codepageName = "GB18030"; // 54936 codepage byte[] chineseBuffer = new byte[] { 0x41, 0x42, 0x43, 0x81, 0x40, 0x82, 0x80, 0x81, 0x30, 0x82, 0x31, 0x81, 0x20 }; Decoder chineseDecoder = Encoding.GetEncoding(codepageName).GetDecoder(); const int BUFFER_SIZE = 100; char[] buffer = new char[BUFFER_SIZE]; int byteIndex = 0; int charIndex = 0; while (byteIndex < chineseBuffer.Length) { int charCount = chineseDecoder.GetChars(chineseBuffer, byteIndex, 1, buffer, charIndex); if (charCount > 0) { charIndex += charCount; } byteIndex++; } int[] expectedResult = new int[] { 0x41, 0x42, 0x43, 0x4E02, 0x500B, 0x8B, 0x3F, 0x20 }; Assert.True(charIndex == expectedResult.Length); for (int i = 0; i < charIndex; i++) Assert.True(expectedResult[i] == (int)buffer[i]); } [Fact] public static void TestDecodingDBCS() { EnsureInitialization(); string codepageName = "shift_jis"; // 932 codepage byte[] shiftJapaneseBuffer = new byte[] { 0x41, 0x42, 0x43, // Single byte 0x81, 0x42, // Double bytes 0xE0, 0x43, // Double bytes 0x44, 0x45 // Single byte }; Decoder jpDecoder = Encoding.GetEncoding(codepageName).GetDecoder(); const int BUFFER_SIZE = 100; char[] buffer = new char[BUFFER_SIZE]; int byteIndex = 0; int charIndex = 0; while (byteIndex < shiftJapaneseBuffer.Length) { int charCount = jpDecoder.GetChars(shiftJapaneseBuffer, byteIndex, 1, buffer, charIndex); if (charCount > 0) { charIndex += charCount; } byteIndex++; } int[] expectedResult = new int[] { 0x41, 0x42, 0x43, 0x3002, 0x6F86, 0x44, 0x45 }; Assert.True(charIndex == expectedResult.Length); for (int i = 0; i < charIndex; i++) Assert.True(expectedResult[i] == (int)buffer[i]); } [Fact] public static void TestDecodingIso2022KR() { EnsureInitialization(); byte[] koreanEncodedBuffer = new byte[] { 0x0E, 0x21, 0x7E, 0x1B, 0x24, 0x29, 0x43, 0x21, 0x7E, 0x0F, 0x21, 0x7E, 0x1B, 0x24, 0x29, 0x43, 0x21, 0x7E }; string codepageName = "iso-2022-kr"; Decoder krDecoder = Encoding.GetEncoding(codepageName).GetDecoder(); const int BUFFER_SIZE = 100; char[] buffer = new char[BUFFER_SIZE]; int byteIndex = 0; int charIndex = 0; while (byteIndex < koreanEncodedBuffer.Length) { int charCount = krDecoder.GetChars(koreanEncodedBuffer, byteIndex, 1, buffer, charIndex); if (charCount > 0) { charIndex += charCount; } byteIndex++; } int[] expectedResult = new int[] { 0xFFE2, 0xFFE2, 0x21, 0x7E, 0x21, 0x7E }; Assert.True(charIndex == expectedResult.Length); for (int i = 0; i < charIndex; i++) Assert.True(expectedResult[i] == (int)buffer[i]); } [Fact] public static void TestDecoding2312HZ() { EnsureInitialization(); byte[] hzEncodedBuffer = new byte[] { 0x7E, 0x42, 0x7E, 0x7E, 0x7E, 0x7B, 0x21, 0x7E, 0x7E, 0x7D, 0x42, 0x42, 0x7E, 0xA, 0x43, 0x43 }; string codepageName = "hz-gb-2312"; Decoder krDecoder = Encoding.GetEncoding(codepageName).GetDecoder(); const int BUFFER_SIZE = 100; char[] buffer = new char[BUFFER_SIZE]; int byteIndex = 0; int charIndex = 0; while (byteIndex < hzEncodedBuffer.Length) { int charCount = krDecoder.GetChars(hzEncodedBuffer, byteIndex, 1, buffer, charIndex); if (charCount > 0) { charIndex += charCount; } byteIndex++; } int[] expectedResult = new int[] { 0x7E, 0x42, 0x7E, 0x3013, 0x42, 0x42, 0x43, 0x43, }; Assert.True(charIndex == expectedResult.Length); for (int i = 0; i < charIndex; i++) Assert.True(expectedResult[i] == (int)buffer[i]); } [Fact] public static void TestEudcEncoding() { EnsureInitialization(); Encoding.GetEncoding(51932); // new EncodingId("csEUCPkdFmtJapanese", 51932), } [Fact] public static void TestCodePageToWebNameMappings() { EnsureInitialization(); foreach (var mapping in s_codePageToWebNameTable) { var encoding = Encoding.GetEncoding(mapping.CodePage); Assert.True(string.Equals(mapping.WebName, encoding.WebName, StringComparison.OrdinalIgnoreCase)); } } [Fact] public static void TestEncodingDisplayNames() { CultureInfo originalUICulture = CultureInfo.CurrentUICulture; try { CultureInfo.CurrentUICulture = new CultureInfo("en-US"); EnsureInitialization(); foreach (var mapping in s_codePageToWebNameTable) { var encoding = Encoding.GetEncoding(mapping.CodePage); string name = encoding.EncodingName; if (string.IsNullOrEmpty(name)) { Assert.True(false, "failed to get the display name of the encoding: " + encoding.WebName); } for (int i = 0; i < name.Length; ++i) { int ch = (int)name[i]; if (ch > 127) { Assert.True(false, string.Format("English name '{0}' for encoding '{1}' contains non-ASCII character: {2}", name, encoding.WebName, ch)); } } } } finally { CultureInfo.CurrentUICulture = originalUICulture; } } private static EncodingId[] s_encodingIdTable = new EncodingId[] { new EncodingId("437", 437), new EncodingId("arabic", 28596), new EncodingId("asmo-708", 708), new EncodingId("big5", 950), new EncodingId("big5-hkscs", 950), new EncodingId("ccsid00858", 858), new EncodingId("ccsid00924", 20924), new EncodingId("ccsid01140", 1140), new EncodingId("ccsid01141", 1141), new EncodingId("ccsid01142", 1142), new EncodingId("ccsid01143", 1143), new EncodingId("ccsid01144", 1144), new EncodingId("ccsid01145", 1145), new EncodingId("ccsid01146", 1146), new EncodingId("ccsid01147", 1147), new EncodingId("ccsid01148", 1148), new EncodingId("ccsid01149", 1149), new EncodingId("chinese", 936), new EncodingId("cn-big5", 950), new EncodingId("cn-gb", 936), new EncodingId("cp00858", 858), new EncodingId("cp00924", 20924), new EncodingId("cp01140", 1140), new EncodingId("cp01141", 1141), new EncodingId("cp01142", 1142), new EncodingId("cp01143", 1143), new EncodingId("cp01144", 1144), new EncodingId("cp01145", 1145), new EncodingId("cp01146", 1146), new EncodingId("cp01147", 1147), new EncodingId("cp01148", 1148), new EncodingId("cp01149", 1149), new EncodingId("cp037", 37), new EncodingId("cp1025", 21025), new EncodingId("cp1026", 1026), new EncodingId("cp1256", 1256), new EncodingId("cp273", 20273), new EncodingId("cp278", 20278), new EncodingId("cp280", 20280), new EncodingId("cp284", 20284), new EncodingId("cp285", 20285), new EncodingId("cp290", 20290), new EncodingId("cp297", 20297), new EncodingId("cp420", 20420), new EncodingId("cp423", 20423), new EncodingId("cp424", 20424), new EncodingId("cp437", 437), new EncodingId("cp500", 500), new EncodingId("cp50227", 50227), new EncodingId("cp850", 850), new EncodingId("cp852", 852), new EncodingId("cp855", 855), new EncodingId("cp857", 857), new EncodingId("cp858", 858), new EncodingId("cp860", 860), new EncodingId("cp861", 861), new EncodingId("cp862", 862), new EncodingId("cp863", 863), new EncodingId("cp864", 864), new EncodingId("cp865", 865), new EncodingId("cp866", 866), new EncodingId("cp869", 869), new EncodingId("cp870", 870), new EncodingId("cp871", 20871), new EncodingId("cp875", 875), new EncodingId("cp880", 20880), new EncodingId("cp905", 20905), new EncodingId("csbig5", 950), new EncodingId("cseuckr", 51949), new EncodingId("cseucpkdfmtjapanese", 51932), new EncodingId("csgb2312", 936), new EncodingId("csgb231280", 936), new EncodingId("csibm037", 37), new EncodingId("csibm1026", 1026), new EncodingId("csibm273", 20273), new EncodingId("csibm277", 20277), new EncodingId("csibm278", 20278), new EncodingId("csibm280", 20280), new EncodingId("csibm284", 20284), new EncodingId("csibm285", 20285), new EncodingId("csibm290", 20290), new EncodingId("csibm297", 20297), new EncodingId("csibm420", 20420), new EncodingId("csibm423", 20423), new EncodingId("csibm424", 20424), new EncodingId("csibm500", 500), new EncodingId("csibm870", 870), new EncodingId("csibm871", 20871), new EncodingId("csibm880", 20880), new EncodingId("csibm905", 20905), new EncodingId("csibmthai", 20838), new EncodingId("csiso2022jp", 50221), new EncodingId("csiso2022kr", 50225), new EncodingId("csiso58gb231280", 936), new EncodingId("csisolatin2", 28592), new EncodingId("csisolatin3", 28593), new EncodingId("csisolatin4", 28594), new EncodingId("csisolatin5", 28599), new EncodingId("csisolatin9", 28605), new EncodingId("csisolatinarabic", 28596), new EncodingId("csisolatincyrillic", 28595), new EncodingId("csisolatingreek", 28597), new EncodingId("csisolatinhebrew", 28598), new EncodingId("cskoi8r", 20866), new EncodingId("csksc56011987", 949), new EncodingId("cspc8codepage437", 437), new EncodingId("csshiftjis", 932), new EncodingId("cswindows31j", 932), new EncodingId("cyrillic", 28595), new EncodingId("din_66003", 20106), new EncodingId("dos-720", 720), new EncodingId("dos-862", 862), new EncodingId("dos-874", 874), new EncodingId("ebcdic-cp-ar1", 20420), new EncodingId("ebcdic-cp-be", 500), new EncodingId("ebcdic-cp-ca", 37), new EncodingId("ebcdic-cp-ch", 500), new EncodingId("ebcdic-cp-dk", 20277), new EncodingId("ebcdic-cp-es", 20284), new EncodingId("ebcdic-cp-fi", 20278), new EncodingId("ebcdic-cp-fr", 20297), new EncodingId("ebcdic-cp-gb", 20285), new EncodingId("ebcdic-cp-gr", 20423), new EncodingId("ebcdic-cp-he", 20424), new EncodingId("ebcdic-cp-is", 20871), new EncodingId("ebcdic-cp-it", 20280), new EncodingId("ebcdic-cp-nl", 37), new EncodingId("ebcdic-cp-no", 20277), new EncodingId("ebcdic-cp-roece", 870), new EncodingId("ebcdic-cp-se", 20278), new EncodingId("ebcdic-cp-tr", 20905), new EncodingId("ebcdic-cp-us", 37), new EncodingId("ebcdic-cp-wt", 37), new EncodingId("ebcdic-cp-yu", 870), new EncodingId("ebcdic-cyrillic", 20880), new EncodingId("ebcdic-de-273+euro", 1141), new EncodingId("ebcdic-dk-277+euro", 1142), new EncodingId("ebcdic-es-284+euro", 1145), new EncodingId("ebcdic-fi-278+euro", 1143), new EncodingId("ebcdic-fr-297+euro", 1147), new EncodingId("ebcdic-gb-285+euro", 1146), new EncodingId("ebcdic-international-500+euro", 1148), new EncodingId("ebcdic-is-871+euro", 1149), new EncodingId("ebcdic-it-280+euro", 1144), new EncodingId("ebcdic-jp-kana", 20290), new EncodingId("ebcdic-latin9--euro", 20924), new EncodingId("ebcdic-no-277+euro", 1142), new EncodingId("ebcdic-se-278+euro", 1143), new EncodingId("ebcdic-us-37+euro", 1140), new EncodingId("ecma-114", 28596), new EncodingId("ecma-118", 28597), new EncodingId("elot_928", 28597), new EncodingId("euc-cn", 51936), new EncodingId("euc-jp", 51932), new EncodingId("euc-kr", 51949), new EncodingId("extended_unix_code_packed_format_for_japanese", 51932), new EncodingId("gb18030", 54936), new EncodingId("gb2312", 936), new EncodingId("gb2312-80", 936), new EncodingId("gb231280", 936), new EncodingId("gbk", 936), new EncodingId("gb_2312-80", 936), new EncodingId("german", 20106), new EncodingId("greek", 28597), new EncodingId("greek8", 28597), new EncodingId("hebrew", 28598), new EncodingId("hz-gb-2312", 52936), new EncodingId("ibm-thai", 20838), new EncodingId("ibm00858", 858), new EncodingId("ibm00924", 20924), new EncodingId("ibm01047", 1047), new EncodingId("ibm01140", 1140), new EncodingId("ibm01141", 1141), new EncodingId("ibm01142", 1142), new EncodingId("ibm01143", 1143), new EncodingId("ibm01144", 1144), new EncodingId("ibm01145", 1145), new EncodingId("ibm01146", 1146), new EncodingId("ibm01147", 1147), new EncodingId("ibm01148", 1148), new EncodingId("ibm01149", 1149), new EncodingId("ibm037", 37), new EncodingId("ibm1026", 1026), new EncodingId("ibm273", 20273), new EncodingId("ibm277", 20277), new EncodingId("ibm278", 20278), new EncodingId("ibm280", 20280), new EncodingId("ibm284", 20284), new EncodingId("ibm285", 20285), new EncodingId("ibm290", 20290), new EncodingId("ibm297", 20297), new EncodingId("ibm420", 20420), new EncodingId("ibm423", 20423), new EncodingId("ibm424", 20424), new EncodingId("ibm437", 437), new EncodingId("ibm500", 500), new EncodingId("ibm737", 737), new EncodingId("ibm775", 775), new EncodingId("ibm850", 850), new EncodingId("ibm852", 852), new EncodingId("ibm855", 855), new EncodingId("ibm857", 857), new EncodingId("ibm860", 860), new EncodingId("ibm861", 861), new EncodingId("ibm862", 862), new EncodingId("ibm863", 863), new EncodingId("ibm864", 864), new EncodingId("ibm865", 865), new EncodingId("ibm866", 866), new EncodingId("ibm869", 869), new EncodingId("ibm870", 870), new EncodingId("ibm871", 20871), new EncodingId("ibm880", 20880), new EncodingId("ibm905", 20905), new EncodingId("irv", 20105), new EncodingId("iso-2022-jp", 50220), new EncodingId("iso-2022-jpeuc", 51932), new EncodingId("iso-2022-kr", 50225), new EncodingId("iso-2022-kr-7", 50225), new EncodingId("iso-2022-kr-7bit", 50225), new EncodingId("iso-2022-kr-8", 51949), new EncodingId("iso-2022-kr-8bit", 51949), new EncodingId("iso-8859-11", 874), new EncodingId("iso-8859-13", 28603), new EncodingId("iso-8859-15", 28605), new EncodingId("iso-8859-2", 28592), new EncodingId("iso-8859-3", 28593), new EncodingId("iso-8859-4", 28594), new EncodingId("iso-8859-5", 28595), new EncodingId("iso-8859-6", 28596), new EncodingId("iso-8859-7", 28597), new EncodingId("iso-8859-8", 28598), new EncodingId("iso-8859-8 visual", 28598), new EncodingId("iso-8859-8-i", 38598), new EncodingId("iso-8859-9", 28599), new EncodingId("iso-ir-101", 28592), new EncodingId("iso-ir-109", 28593), new EncodingId("iso-ir-110", 28594), new EncodingId("iso-ir-126", 28597), new EncodingId("iso-ir-127", 28596), new EncodingId("iso-ir-138", 28598), new EncodingId("iso-ir-144", 28595), new EncodingId("iso-ir-148", 28599), new EncodingId("iso-ir-149", 949), new EncodingId("iso-ir-58", 936), new EncodingId("iso8859-2", 28592), new EncodingId("iso_8859-15", 28605), new EncodingId("iso_8859-2", 28592), new EncodingId("iso_8859-2:1987", 28592), new EncodingId("iso_8859-3", 28593), new EncodingId("iso_8859-3:1988", 28593), new EncodingId("iso_8859-4", 28594), new EncodingId("iso_8859-4:1988", 28594), new EncodingId("iso_8859-5", 28595), new EncodingId("iso_8859-5:1988", 28595), new EncodingId("iso_8859-6", 28596), new EncodingId("iso_8859-6:1987", 28596), new EncodingId("iso_8859-7", 28597), new EncodingId("iso_8859-7:1987", 28597), new EncodingId("iso_8859-8", 28598), new EncodingId("iso_8859-8:1988", 28598), new EncodingId("iso_8859-9", 28599), new EncodingId("iso_8859-9:1989", 28599), new EncodingId("johab", 1361), new EncodingId("koi", 20866), new EncodingId("koi8", 20866), new EncodingId("koi8-r", 20866), new EncodingId("koi8-ru", 21866), new EncodingId("koi8-u", 21866), new EncodingId("koi8r", 20866), new EncodingId("korean", 949), new EncodingId("ks-c-5601", 949), new EncodingId("ks-c5601", 949), new EncodingId("ksc5601", 949), new EncodingId("ksc_5601", 949), new EncodingId("ks_c_5601", 949), new EncodingId("ks_c_5601-1987", 949), new EncodingId("ks_c_5601-1989", 949), new EncodingId("ks_c_5601_1987", 949), new EncodingId("l2", 28592), new EncodingId("l3", 28593), new EncodingId("l4", 28594), new EncodingId("l5", 28599), new EncodingId("l9", 28605), new EncodingId("latin2", 28592), new EncodingId("latin3", 28593), new EncodingId("latin4", 28594), new EncodingId("latin5", 28599), new EncodingId("latin9", 28605), new EncodingId("logical", 28598), new EncodingId("macintosh", 10000), new EncodingId("ms_kanji", 932), new EncodingId("norwegian", 20108), new EncodingId("ns_4551-1", 20108), new EncodingId("pc-multilingual-850+euro", 858), new EncodingId("sen_850200_b", 20107), new EncodingId("shift-jis", 932), new EncodingId("shift_jis", 932), new EncodingId("sjis", 932), new EncodingId("swedish", 20107), new EncodingId("tis-620", 874), new EncodingId("visual", 28598), new EncodingId("windows-1250", 1250), new EncodingId("windows-1251", 1251), new EncodingId("windows-1252", 1252), new EncodingId("windows-1253", 1253), new EncodingId("windows-1254", 1254), new EncodingId("windows-1255", 1255), new EncodingId("windows-1256", 1256), new EncodingId("windows-1257", 1257), new EncodingId("windows-1258", 1258), new EncodingId("windows-874", 874), new EncodingId("x-ansi", 1252), new EncodingId("x-chinese-cns", 20000), new EncodingId("x-chinese-eten", 20002), new EncodingId("x-cp1250", 1250), new EncodingId("x-cp1251", 1251), new EncodingId("x-cp20001", 20001), new EncodingId("x-cp20003", 20003), new EncodingId("x-cp20004", 20004), new EncodingId("x-cp20005", 20005), new EncodingId("x-cp20261", 20261), new EncodingId("x-cp20269", 20269), new EncodingId("x-cp20936", 20936), new EncodingId("x-cp20949", 20949), new EncodingId("x-cp50227", 50227), new EncodingId("x-ebcdic-koreanextended", 20833), new EncodingId("x-euc", 51932), new EncodingId("x-euc-cn", 51936), new EncodingId("x-euc-jp", 51932), new EncodingId("x-europa", 29001), new EncodingId("x-ia5", 20105), new EncodingId("x-ia5-german", 20106), new EncodingId("x-ia5-norwegian", 20108), new EncodingId("x-ia5-swedish", 20107), new EncodingId("x-iscii-as", 57006), new EncodingId("x-iscii-be", 57003), new EncodingId("x-iscii-de", 57002), new EncodingId("x-iscii-gu", 57010), new EncodingId("x-iscii-ka", 57008), new EncodingId("x-iscii-ma", 57009), new EncodingId("x-iscii-or", 57007), new EncodingId("x-iscii-pa", 57011), new EncodingId("x-iscii-ta", 57004), new EncodingId("x-iscii-te", 57005), new EncodingId("x-mac-arabic", 10004), new EncodingId("x-mac-ce", 10029), new EncodingId("x-mac-chinesesimp", 10008), new EncodingId("x-mac-chinesetrad", 10002), new EncodingId("x-mac-croatian", 10082), new EncodingId("x-mac-cyrillic", 10007), new EncodingId("x-mac-greek", 10006), new EncodingId("x-mac-hebrew", 10005), new EncodingId("x-mac-icelandic", 10079), new EncodingId("x-mac-japanese", 10001), new EncodingId("x-mac-korean", 10003), new EncodingId("x-mac-romanian", 10010), new EncodingId("x-mac-thai", 10021), new EncodingId("x-mac-turkish", 10081), new EncodingId("x-mac-ukrainian", 10017), new EncodingId("x-ms-cp932", 932), new EncodingId("x-sjis", 932), new EncodingId("x-x-big5", 950) }; private static readonly CodePageToWebNameMapping[] s_codePageToWebNameTable = new[] { new CodePageToWebNameMapping(37, "ibm037"), new CodePageToWebNameMapping(437, "ibm437"), new CodePageToWebNameMapping(500, "ibm500"), new CodePageToWebNameMapping(708, "asmo-708"), new CodePageToWebNameMapping(720, "dos-720"), new CodePageToWebNameMapping(737, "ibm737"), new CodePageToWebNameMapping(775, "ibm775"), new CodePageToWebNameMapping(850, "ibm850"), new CodePageToWebNameMapping(852, "ibm852"), new CodePageToWebNameMapping(855, "ibm855"), new CodePageToWebNameMapping(857, "ibm857"), new CodePageToWebNameMapping(858, "ibm00858"), new CodePageToWebNameMapping(860, "ibm860"), new CodePageToWebNameMapping(861, "ibm861"), new CodePageToWebNameMapping(862, "dos-862"), new CodePageToWebNameMapping(863, "ibm863"), new CodePageToWebNameMapping(864, "ibm864"), new CodePageToWebNameMapping(865, "ibm865"), new CodePageToWebNameMapping(866, "cp866"), new CodePageToWebNameMapping(869, "ibm869"), new CodePageToWebNameMapping(870, "ibm870"), new CodePageToWebNameMapping(874, "windows-874"), new CodePageToWebNameMapping(875, "cp875"), new CodePageToWebNameMapping(932, "shift_jis"), new CodePageToWebNameMapping(936, "gb2312"), new CodePageToWebNameMapping(949, "ks_c_5601-1987"), new CodePageToWebNameMapping(950, "big5"), new CodePageToWebNameMapping(1026, "ibm1026"), new CodePageToWebNameMapping(1047, "ibm01047"), new CodePageToWebNameMapping(1140, "ibm01140"), new CodePageToWebNameMapping(1141, "ibm01141"), new CodePageToWebNameMapping(1142, "ibm01142"), new CodePageToWebNameMapping(1143, "ibm01143"), new CodePageToWebNameMapping(1144, "ibm01144"), new CodePageToWebNameMapping(1145, "ibm01145"), new CodePageToWebNameMapping(1146, "ibm01146"), new CodePageToWebNameMapping(1147, "ibm01147"), new CodePageToWebNameMapping(1148, "ibm01148"), new CodePageToWebNameMapping(1149, "ibm01149"), new CodePageToWebNameMapping(1250, "windows-1250"), new CodePageToWebNameMapping(1251, "windows-1251"), new CodePageToWebNameMapping(1252, "windows-1252"), new CodePageToWebNameMapping(1253, "windows-1253"), new CodePageToWebNameMapping(1254, "windows-1254"), new CodePageToWebNameMapping(1255, "windows-1255"), new CodePageToWebNameMapping(1256, "windows-1256"), new CodePageToWebNameMapping(1257, "windows-1257"), new CodePageToWebNameMapping(1258, "windows-1258"), new CodePageToWebNameMapping(1361, "johab"), new CodePageToWebNameMapping(10000, "macintosh"), new CodePageToWebNameMapping(10001, "x-mac-japanese"), new CodePageToWebNameMapping(10002, "x-mac-chinesetrad"), new CodePageToWebNameMapping(10003, "x-mac-korean"), new CodePageToWebNameMapping(10004, "x-mac-arabic"), new CodePageToWebNameMapping(10005, "x-mac-hebrew"), new CodePageToWebNameMapping(10006, "x-mac-greek"), new CodePageToWebNameMapping(10007, "x-mac-cyrillic"), new CodePageToWebNameMapping(10008, "x-mac-chinesesimp"), new CodePageToWebNameMapping(10010, "x-mac-romanian"), new CodePageToWebNameMapping(10017, "x-mac-ukrainian"), new CodePageToWebNameMapping(10021, "x-mac-thai"), new CodePageToWebNameMapping(10029, "x-mac-ce"), new CodePageToWebNameMapping(10079, "x-mac-icelandic"), new CodePageToWebNameMapping(10081, "x-mac-turkish"), new CodePageToWebNameMapping(10082, "x-mac-croatian"), new CodePageToWebNameMapping(20000, "x-chinese-cns"), new CodePageToWebNameMapping(20001, "x-cp20001"), new CodePageToWebNameMapping(20002, "x-chinese-eten"), new CodePageToWebNameMapping(20003, "x-cp20003"), new CodePageToWebNameMapping(20004, "x-cp20004"), new CodePageToWebNameMapping(20005, "x-cp20005"), new CodePageToWebNameMapping(20105, "x-ia5"), new CodePageToWebNameMapping(20106, "x-ia5-german"), new CodePageToWebNameMapping(20107, "x-ia5-swedish"), new CodePageToWebNameMapping(20108, "x-ia5-norwegian"), new CodePageToWebNameMapping(20261, "x-cp20261"), new CodePageToWebNameMapping(20269, "x-cp20269"), new CodePageToWebNameMapping(20273, "ibm273"), new CodePageToWebNameMapping(20277, "ibm277"), new CodePageToWebNameMapping(20278, "ibm278"), new CodePageToWebNameMapping(20280, "ibm280"), new CodePageToWebNameMapping(20284, "ibm284"), new CodePageToWebNameMapping(20285, "ibm285"), new CodePageToWebNameMapping(20290, "ibm290"), new CodePageToWebNameMapping(20297, "ibm297"), new CodePageToWebNameMapping(20420, "ibm420"), new CodePageToWebNameMapping(20423, "ibm423"), new CodePageToWebNameMapping(20424, "ibm424"), new CodePageToWebNameMapping(20833, "x-ebcdic-koreanextended"), new CodePageToWebNameMapping(20838, "ibm-thai"), new CodePageToWebNameMapping(20866, "koi8-r"), new CodePageToWebNameMapping(20871, "ibm871"), new CodePageToWebNameMapping(20880, "ibm880"), new CodePageToWebNameMapping(20905, "ibm905"), new CodePageToWebNameMapping(20924, "ibm00924"), new CodePageToWebNameMapping(20932, "euc-jp"), new CodePageToWebNameMapping(20936, "x-cp20936"), new CodePageToWebNameMapping(20949, "x-cp20949"), new CodePageToWebNameMapping(21025, "cp1025"), new CodePageToWebNameMapping(21866, "koi8-u"), new CodePageToWebNameMapping(28592, "iso-8859-2"), new CodePageToWebNameMapping(28593, "iso-8859-3"), new CodePageToWebNameMapping(28594, "iso-8859-4"), new CodePageToWebNameMapping(28595, "iso-8859-5"), new CodePageToWebNameMapping(28596, "iso-8859-6"), new CodePageToWebNameMapping(28597, "iso-8859-7"), new CodePageToWebNameMapping(28598, "iso-8859-8"), new CodePageToWebNameMapping(28599, "iso-8859-9"), new CodePageToWebNameMapping(28603, "iso-8859-13"), new CodePageToWebNameMapping(28605, "iso-8859-15"), new CodePageToWebNameMapping(38598, "iso-8859-8-i"), new CodePageToWebNameMapping(50220, "iso-2022-jp"), new CodePageToWebNameMapping(50221, "csiso2022jp"), new CodePageToWebNameMapping(50222, "iso-2022-jp"), new CodePageToWebNameMapping(50225, "iso-2022-kr"), new CodePageToWebNameMapping(50227, "x-cp50227"), new CodePageToWebNameMapping(51932, "euc-jp"), new CodePageToWebNameMapping(51936, "euc-cn"), new CodePageToWebNameMapping(51949, "euc-kr"), new CodePageToWebNameMapping(52936, "hz-gb-2312"), new CodePageToWebNameMapping(54936, "gb18030"), new CodePageToWebNameMapping(57002, "x-iscii-de"), new CodePageToWebNameMapping(57003, "x-iscii-be"), new CodePageToWebNameMapping(57004, "x-iscii-ta"), new CodePageToWebNameMapping(57005, "x-iscii-te"), new CodePageToWebNameMapping(57006, "x-iscii-as"), new CodePageToWebNameMapping(57007, "x-iscii-or"), new CodePageToWebNameMapping(57008, "x-iscii-ka"), new CodePageToWebNameMapping(57009, "x-iscii-ma"), new CodePageToWebNameMapping(57010, "x-iscii-gu"), new CodePageToWebNameMapping(57011, "x-iscii-pa") }; }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog { using System; using System.Collections.Generic; using System.ComponentModel; #if !NET35 && !NET40 using System.Threading.Tasks; #endif using JetBrains.Annotations; using NLog.Internal; /// <summary> /// Provides logging interface and utility functions. /// </summary> [CLSCompliant(true)] public partial class Logger : ILogger { internal static readonly Type DefaultLoggerType = typeof(Logger); private TargetWithFilterChain[] _targetsByLevel = TargetWithFilterChain.NoTargetsByLevel; private Logger _contextLogger; private ThreadSafeDictionary<string, object> _contextProperties; private volatile bool _isTraceEnabled; private volatile bool _isDebugEnabled; private volatile bool _isInfoEnabled; private volatile bool _isWarnEnabled; private volatile bool _isErrorEnabled; private volatile bool _isFatalEnabled; /// <summary> /// Initializes a new instance of the <see cref="Logger"/> class. /// </summary> protected internal Logger() { _contextLogger = this; } /// <summary> /// Occurs when logger configuration changes. /// </summary> public event EventHandler<EventArgs> LoggerReconfigured; /// <summary> /// Gets the name of the logger. /// </summary> public string Name { get; private set; } /// <summary> /// Gets the factory that created this logger. /// </summary> public LogFactory Factory { get; private set; } /// <summary> /// Collection of context properties for the Logger. The logger will append it for all log events /// </summary> /// <remarks> /// It is recommended to use <see cref="WithProperty(string, object)"/> for modifying context properties /// when same named logger is used at multiple locations or shared by different thread contexts. /// </remarks> public IDictionary<string, object> Properties => _contextProperties ?? System.Threading.Interlocked.CompareExchange(ref _contextProperties, CreateContextPropertiesDictionary(null), null) ?? _contextProperties; /// <summary> /// Gets a value indicating whether logging is enabled for the specified level. /// </summary> /// <param name="level">Log level to be checked.</param> /// <returns>A value of <see langword="true" /> if logging is enabled for the specified level, otherwise it returns <see langword="false" />.</returns> public bool IsEnabled(LogLevel level) { return GetTargetsForLevelSafe(level) != null; } /// <summary> /// Creates new logger that automatically appends the specified property to all log events (without changing current logger) /// /// With <see cref="Properties"/> property, all properties can be enumerated. /// </summary> /// <param name="propertyKey">Property Name</param> /// <param name="propertyValue">Property Value</param> /// <returns>New Logger object that automatically appends specified property</returns> public Logger WithProperty(string propertyKey, object propertyValue) { if (string.IsNullOrEmpty(propertyKey)) throw new ArgumentException(nameof(propertyKey)); Logger newLogger = Factory.CreateNewLogger(GetType()) ?? new Logger(); newLogger.Initialize(Name, _targetsByLevel, Factory); newLogger._contextProperties = CreateContextPropertiesDictionary(_contextProperties); newLogger._contextProperties[propertyKey] = propertyValue; newLogger._contextLogger = _contextLogger; // Use the GetTargetsForLevel() of the parent Logger return newLogger; } /// <summary> /// Updates the specified context property for the current logger. The logger will append it for all log events. /// /// With <see cref="Properties"/> property, all properties can be enumerated (or updated). /// </summary> /// <remarks> /// It is highly recommended to ONLY use <see cref="WithProperty(string, object)"/> for modifying context properties. /// This method will affect all locations/contexts that makes use of the same named logger object. And can cause /// unexpected surprises at multiple locations and other thread contexts. /// </remarks> /// <param name="propertyKey">Property Name</param> /// <param name="propertyValue">Property Value</param> public void SetProperty(string propertyKey, object propertyValue) { if (string.IsNullOrEmpty(propertyKey)) throw new ArgumentException(nameof(propertyKey)); Properties[propertyKey] = propertyValue; } private static ThreadSafeDictionary<string, object> CreateContextPropertiesDictionary(ThreadSafeDictionary<string, object> contextProperties) { contextProperties = contextProperties != null ? new ThreadSafeDictionary<string, object>(contextProperties) : new ThreadSafeDictionary<string, object>(); return contextProperties; } /// <summary> /// Updates the <see cref="ScopeContext"/> with provided property /// </summary> /// <param name="propertyName">Name of property</param> /// <param name="propertyValue">Value of property</param> /// <returns>A disposable object that removes the properties from logical context scope on dispose.</returns> /// <remarks><see cref="ScopeContext"/> property-dictionary-keys are case-insensitive</remarks> public IDisposable PushScopeProperty(string propertyName, object propertyValue) { return ScopeContext.PushProperty(propertyName, propertyValue); } /// <summary> /// Updates the <see cref="ScopeContext"/> with provided property /// </summary> /// <param name="propertyName">Name of property</param> /// <param name="propertyValue">Value of property</param> /// <returns>A disposable object that removes the properties from logical context scope on dispose.</returns> /// <remarks><see cref="ScopeContext"/> property-dictionary-keys are case-insensitive</remarks> public IDisposable PushScopeProperty<TValue>(string propertyName, TValue propertyValue) { return ScopeContext.PushProperty(propertyName, propertyValue); } #if !NET35 && !NET40 /// <summary> /// Updates the <see cref="ScopeContext"/> with provided properties /// </summary> /// <param name="scopeProperties">Properties being added to the scope dictionary</param> /// <returns>A disposable object that removes the properties from logical context scope on dispose.</returns> /// <remarks><see cref="ScopeContext"/> property-dictionary-keys are case-insensitive</remarks> public IDisposable PushScopeProperties(IReadOnlyCollection<KeyValuePair<string, object>> scopeProperties) { return ScopeContext.PushProperties(scopeProperties); } /// <summary> /// Updates the <see cref="ScopeContext"/> with provided properties /// </summary> /// <param name="scopeProperties">Properties being added to the scope dictionary</param> /// <returns>A disposable object that removes the properties from logical context scope on dispose.</returns> /// <remarks><see cref="ScopeContext"/> property-dictionary-keys are case-insensitive</remarks> public IDisposable PushScopeProperties<TValue>(IReadOnlyCollection<KeyValuePair<string, TValue>> scopeProperties) { return ScopeContext.PushProperties(scopeProperties); } #endif /// <summary> /// Pushes new state on the logical context scope stack /// </summary> /// <param name="nestedState">Value to added to the scope stack</param> /// <returns>A disposable object that pops the nested scope state on dispose.</returns> public IDisposable PushScopeNested<T>(T nestedState) { return ScopeContext.PushNestedState(nestedState); } /// <summary> /// Pushes new state on the logical context scope stack /// </summary> /// <param name="nestedState">Value to added to the scope stack</param> /// <returns>A disposable object that pops the nested scope state on dispose.</returns> public IDisposable PushScopeNested(object nestedState) { return ScopeContext.PushNestedState(nestedState); } /// <summary> /// Writes the specified diagnostic message. /// </summary> /// <param name="logEvent">Log event.</param> public void Log(LogEventInfo logEvent) { var targetsForLevel = GetTargetsForLevelSafe(logEvent.Level); if (targetsForLevel != null) { if (logEvent.LoggerName is null) logEvent.LoggerName = Name; if (logEvent.FormatProvider is null) logEvent.FormatProvider = Factory.DefaultCultureInfo; WriteToTargets(logEvent, targetsForLevel); } } /// <summary> /// Writes the specified diagnostic message. /// </summary> /// <param name="wrapperType">The name of the type that wraps Logger.</param> /// <param name="logEvent">Log event.</param> public void Log(Type wrapperType, LogEventInfo logEvent) { var targetsForLevel = GetTargetsForLevelSafe(logEvent.Level); if (targetsForLevel != null) { if (logEvent.LoggerName is null) logEvent.LoggerName = Name; if (logEvent.FormatProvider is null) logEvent.FormatProvider = Factory.DefaultCultureInfo; WriteToTargets(wrapperType, logEvent, targetsForLevel); } } #region Log() overloads /// <overloads> /// Writes the diagnostic message at the specified level using the specified format provider and format parameters. /// </overloads> /// <summary> /// Writes the diagnostic message at the specified level. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="level">The log level.</param> /// <param name="value">The value to be written.</param> public void Log<T>(LogLevel level, T value) { if (IsEnabled(level)) { WriteToTargets(level, Factory.DefaultCultureInfo, value); } } /// <summary> /// Writes the diagnostic message at the specified level. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">The value to be written.</param> public void Log<T>(LogLevel level, IFormatProvider formatProvider, T value) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, value); } } /// <summary> /// Writes the diagnostic message at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> public void Log(LogLevel level, LogMessageGenerator messageFunc) { if (IsEnabled(level)) { if (messageFunc is null) { throw new ArgumentNullException(nameof(messageFunc)); } WriteToTargets(level, messageFunc()); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified parameters and formatting them with the supplied format provider. /// </summary> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, IFormatProvider formatProvider, [Localizable(false)] string message, params object[] args) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, args); } } /// <summary> /// Writes the diagnostic message at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">Log message.</param> public void Log(LogLevel level, [Localizable(false)] string message) { if (IsEnabled(level)) { WriteToTargets(level, message); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified parameters. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, [Localizable(false)] string message, params object[] args) { if (IsEnabled(level)) { WriteToTargets(level, message, args); } } /// <summary> /// Writes the diagnostic message and exception at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, Exception exception, [Localizable(false)] string message, params object[] args) { if (IsEnabled(level)) { WriteToTargets(level, exception, message, args); } } /// <summary> /// Writes the diagnostic message and exception at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, Exception exception, IFormatProvider formatProvider, [Localizable(false)] string message, params object[] args) { if (IsEnabled(level)) { WriteToTargets(level, exception, formatProvider, message, args); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified parameter and formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [MessageTemplateFormatMethod("message")] public void Log<TArgument>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)] string message, TArgument argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified parameter. /// </summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [MessageTemplateFormatMethod("message")] public void Log<TArgument>(LogLevel level, [Localizable(false)] string message, TArgument argument) { if (IsEnabled(level)) { WriteToTargets(level, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified arguments formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [MessageTemplateFormatMethod("message")] public void Log<TArgument1, TArgument2>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)] string message, TArgument1 argument1, TArgument2 argument2) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[] { argument1, argument2 }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified parameters. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [MessageTemplateFormatMethod("message")] public void Log<TArgument1, TArgument2>(LogLevel level, [Localizable(false)] string message, TArgument1 argument1, TArgument2 argument2) { if (IsEnabled(level)) { WriteToTargets(level, message, new object[] { argument1, argument2 }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified arguments formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [MessageTemplateFormatMethod("message")] public void Log<TArgument1, TArgument2, TArgument3>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[] { argument1, argument2, argument3 }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified parameters. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [MessageTemplateFormatMethod("message")] public void Log<TArgument1, TArgument2, TArgument3>(LogLevel level, [Localizable(false)] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3) { if (IsEnabled(level)) { WriteToTargets(level, message, new object[] { argument1, argument2, argument3 }); } } private LogEventInfo PrepareLogEventInfo(LogEventInfo logEvent) { if (_contextProperties != null) { foreach (var property in _contextProperties) { if (!logEvent.Properties.ContainsKey(property.Key)) { logEvent.Properties[property.Key] = property.Value; } } } return logEvent; } #endregion /// <summary> /// Runs the provided action. If the action throws, the exception is logged at <c>Error</c> level. The exception is not propagated outside of this method. /// </summary> /// <param name="action">Action to execute.</param> public void Swallow(Action action) { try { action(); } catch (Exception e) { Error(e); } } /// <summary> /// Runs the provided function and returns its result. If an exception is thrown, it is logged at <c>Error</c> level. /// The exception is not propagated outside of this method; a default value is returned instead. /// </summary> /// <typeparam name="T">Return type of the provided function.</typeparam> /// <param name="func">Function to run.</param> /// <returns>Result returned by the provided function or the default value of type <typeparamref name="T"/> in case of exception.</returns> public T Swallow<T>(Func<T> func) { return Swallow(func, default(T)); } /// <summary> /// Runs the provided function and returns its result. If an exception is thrown, it is logged at <c>Error</c> level. /// The exception is not propagated outside of this method; a fallback value is returned instead. /// </summary> /// <typeparam name="T">Return type of the provided function.</typeparam> /// <param name="func">Function to run.</param> /// <param name="fallback">Fallback value to return in case of exception.</param> /// <returns>Result returned by the provided function or fallback value in case of exception.</returns> public T Swallow<T>(Func<T> func, T fallback) { try { return func(); } catch (Exception e) { Error(e); return fallback; } } #if !NET35 && !NET40 /// <summary> /// Logs an exception is logged at <c>Error</c> level if the provided task does not run to completion. /// </summary> /// <param name="task">The task for which to log an error if it does not run to completion.</param> /// <remarks>This method is useful in fire-and-forget situations, where application logic does not depend on completion of task. This method is avoids C# warning CS4014 in such situations.</remarks> public async void Swallow(Task task) { try { await task.ConfigureAwait(false); } catch (Exception e) { Error(e); } } /// <summary> /// Returns a task that completes when a specified task to completes. If the task does not run to completion, an exception is logged at <c>Error</c> level. The returned task always runs to completion. /// </summary> /// <param name="task">The task for which to log an error if it does not run to completion.</param> /// <returns>A task that completes in the <see cref="TaskStatus.RanToCompletion"/> state when <paramref name="task"/> completes.</returns> public async Task SwallowAsync(Task task) { try { await task.ConfigureAwait(false); } catch (Exception e) { Error(e); } } /// <summary> /// Runs async action. If the action throws, the exception is logged at <c>Error</c> level. The exception is not propagated outside of this method. /// </summary> /// <param name="asyncAction">Async action to execute.</param> public async Task SwallowAsync(Func<Task> asyncAction) { try { await asyncAction().ConfigureAwait(false); } catch (Exception e) { Error(e); } } /// <summary> /// Runs the provided async function and returns its result. If the task does not run to completion, an exception is logged at <c>Error</c> level. /// The exception is not propagated outside of this method; a default value is returned instead. /// </summary> /// <typeparam name="TResult">Return type of the provided function.</typeparam> /// <param name="asyncFunc">Async function to run.</param> /// <returns>A task that represents the completion of the supplied task. If the supplied task ends in the <see cref="TaskStatus.RanToCompletion"/> state, the result of the new task will be the result of the supplied task; otherwise, the result of the new task will be the default value of type <typeparamref name="TResult"/>.</returns> public async Task<TResult> SwallowAsync<TResult>(Func<Task<TResult>> asyncFunc) { return await SwallowAsync(asyncFunc, default(TResult)).ConfigureAwait(false); } /// <summary> /// Runs the provided async function and returns its result. If the task does not run to completion, an exception is logged at <c>Error</c> level. /// The exception is not propagated outside of this method; a fallback value is returned instead. /// </summary> /// <typeparam name="TResult">Return type of the provided function.</typeparam> /// <param name="asyncFunc">Async function to run.</param> /// <param name="fallback">Fallback value to return if the task does not end in the <see cref="TaskStatus.RanToCompletion"/> state.</param> /// <returns>A task that represents the completion of the supplied task. If the supplied task ends in the <see cref="TaskStatus.RanToCompletion"/> state, the result of the new task will be the result of the supplied task; otherwise, the result of the new task will be the fallback value.</returns> public async Task<TResult> SwallowAsync<TResult>(Func<Task<TResult>> asyncFunc, TResult fallback) { try { return await asyncFunc().ConfigureAwait(false); } catch (Exception e) { Error(e); return fallback; } } #endif internal void Initialize(string name, TargetWithFilterChain[] targetsByLevel, LogFactory factory) { Name = name; Factory = factory; SetConfiguration(targetsByLevel); } private void WriteToTargets(LogLevel level, string message, object[] args) { WriteToTargets(level, Factory.DefaultCultureInfo, message, args); } private void WriteToTargets(LogLevel level, IFormatProvider formatProvider, string message, object[] args) { var targetsForLevel = GetTargetsForLevel(level); if (targetsForLevel != null) { var logEvent = LogEventInfo.Create(level, Name, formatProvider, message, args); WriteToTargets(logEvent, targetsForLevel); } } private void WriteToTargets(LogLevel level, string message) { var targetsForLevel = GetTargetsForLevel(level); if (targetsForLevel != null) { // please note that this overload calls the overload of LogEventInfo.Create with object[] parameter on purpose - // to avoid unnecessary string.Format (in case of calling Create(LogLevel, string, IFormatProvider, object)) var logEvent = LogEventInfo.Create(level, Name, Factory.DefaultCultureInfo, message, (object[])null); WriteToTargets(logEvent, targetsForLevel); } } private void WriteToTargets<T>(LogLevel level, IFormatProvider formatProvider, T value) { var targetsForLevel = GetTargetsForLevel(level); if (targetsForLevel != null) { var logEvent = LogEventInfo.Create(level, Name, formatProvider, value); WriteToTargets(logEvent, targetsForLevel); } } private void WriteToTargets(LogLevel level, Exception ex, string message, object[] args) { var targetsForLevel = GetTargetsForLevel(level); if (targetsForLevel != null) { // Translate Exception with missing LogEvent message as log single value var logEvent = message is null && ex != null && !(args?.Length > 0) ? LogEventInfo.Create(level, Name, ExceptionMessageFormatProvider.Instance, ex) : LogEventInfo.Create(level, Name, ex, Factory.DefaultCultureInfo, message, args); WriteToTargets(logEvent, targetsForLevel); } } private void WriteToTargets(LogLevel level, Exception ex, IFormatProvider formatProvider, string message, object[] args) { var targetsForLevel = GetTargetsForLevel(level); if (targetsForLevel != null) { var logEvent = LogEventInfo.Create(level, Name, ex, formatProvider, message, args); WriteToTargets(logEvent, targetsForLevel); } } private void WriteToTargets([NotNull] LogEventInfo logEvent, [NotNull] TargetWithFilterChain targetsForLevel) { try { LoggerImpl.Write(DefaultLoggerType, targetsForLevel, PrepareLogEventInfo(logEvent), Factory); } catch (Exception ex) { #if DEBUG if (ex.MustBeRethrownImmediately()) throw; // Throwing exceptions here might crash the entire application (.NET 2.0 behavior) #endif if (Factory.ThrowExceptions || LogManager.ThrowExceptions) throw; Common.InternalLogger.Error(ex, "Failed to write LogEvent"); } } private void WriteToTargets(Type wrapperType, [NotNull] LogEventInfo logEvent, [NotNull] TargetWithFilterChain targetsForLevel) { try { LoggerImpl.Write(wrapperType ?? DefaultLoggerType, targetsForLevel, PrepareLogEventInfo(logEvent), Factory); } catch (Exception ex) { #if DEBUG if (ex.MustBeRethrownImmediately()) throw; // Throwing exceptions here might crash the entire application (.NET 2.0 behavior) #endif if (Factory.ThrowExceptions || LogManager.ThrowExceptions) throw; Common.InternalLogger.Error(ex, "Failed to write LogEvent"); } } internal void SetConfiguration(TargetWithFilterChain[] targetsByLevel) { _targetsByLevel = targetsByLevel; // pre-calculate 'enabled' flags _isTraceEnabled = IsEnabled(LogLevel.Trace); _isDebugEnabled = IsEnabled(LogLevel.Debug); _isInfoEnabled = IsEnabled(LogLevel.Info); _isWarnEnabled = IsEnabled(LogLevel.Warn); _isErrorEnabled = IsEnabled(LogLevel.Error); _isFatalEnabled = IsEnabled(LogLevel.Fatal); OnLoggerReconfigured(EventArgs.Empty); } private TargetWithFilterChain GetTargetsForLevelSafe(LogLevel level) { if (level is null) { throw new InvalidOperationException("Log level must be defined"); } return GetTargetsForLevel(level); } private TargetWithFilterChain GetTargetsForLevel(LogLevel level) { if (ReferenceEquals(_contextLogger, this)) return _targetsByLevel[level.Ordinal]; else return _contextLogger.GetTargetsForLevel(level); // Use the GetTargetsForLevel() of the parent Logger } /// <summary> /// Raises the event when the logger is reconfigured. /// </summary> /// <param name="e">Event arguments</param> protected virtual void OnLoggerReconfigured(EventArgs e) { LoggerReconfigured?.Invoke(this, e); } } }
using System; using System.Linq.Expressions; using System.Reflection; using FluentNHibernate.Conventions.Inspections; using FluentNHibernate.MappingModel; using FluentNHibernate.Testing.DomainModel; using FluentNHibernate.Utils; using NUnit.Framework; namespace FluentNHibernate.Testing.ConventionsTests.Inspection { [TestFixture, Category("Inspection DSL")] public class ColumnInspectorMapsToColumnMapping { private ColumnMapping mapping; private IColumnInspector inspector; [SetUp] public void CreateDsl() { mapping = new ColumnMapping(); inspector = new ColumnInspector(typeof(Record), mapping); } [Test] public void CheckMapped() { mapping.Check = "chk"; inspector.Check.ShouldEqual("chk"); } [Test] public void CheckIsSet() { mapping.Check = "chk"; inspector.IsSet(Prop(x => x.Check)) .ShouldBeTrue(); } [Test] public void CheckIsNotSet() { inspector.IsSet(Prop(x => x.Check)) .ShouldBeFalse(); } [Test] public void DefaultMapped() { mapping.Default = "value"; inspector.Default.ShouldEqual("value"); } [Test] public void DefaultIsSet() { mapping.Default = "value"; inspector.IsSet(Prop(x => x.Default)) .ShouldBeTrue(); } [Test] public void DefaultIsNotSet() { inspector.IsSet(Prop(x => x.Default)) .ShouldBeFalse(); } [Test] public void IndexMapped() { mapping.Index = "ix"; inspector.Index.ShouldEqual("ix"); } [Test] public void IndexIsSet() { mapping.Index = "ix"; inspector.IsSet(Prop(x => x.Index)) .ShouldBeTrue(); } [Test] public void IndexIsNotSet() { inspector.IsSet(Prop(x => x.Index)) .ShouldBeFalse(); } [Test] public void LengthMapped() { mapping.Length = 100; inspector.Length.ShouldEqual(100); } [Test] public void LengthIsSet() { mapping.Length = 100; inspector.IsSet(Prop(x => x.Length)) .ShouldBeTrue(); } [Test] public void LengthIsNotSet() { inspector.IsSet(Prop(x => x.Length)) .ShouldBeFalse(); } [Test] public void NameMapped() { mapping.Name = "name"; inspector.Name.ShouldEqual("name"); } [Test] public void NameIsSet() { mapping.Name = "name"; inspector.IsSet(Prop(x => x.Name)) .ShouldBeTrue(); } [Test] public void NameIsNotSet() { inspector.IsSet(Prop(x => x.Name)) .ShouldBeFalse(); } [Test] public void NotNullMapped() { mapping.NotNull = true; inspector.NotNull.ShouldBeTrue(); } [Test] public void NotNullIsSet() { mapping.NotNull = true; inspector.IsSet(Prop(x => x.NotNull)) .ShouldBeTrue(); } [Test] public void NotNullIsNotSet() { inspector.IsSet(Prop(x => x.NotNull)) .ShouldBeFalse(); } [Test] public void PrecisionMapped() { mapping.Precision = 10; inspector.Precision.ShouldEqual(10); } [Test] public void PrecisionIsSet() { mapping.Precision = 10; inspector.IsSet(Prop(x => x.Precision)) .ShouldBeTrue(); } [Test] public void PrecisionIsNotSet() { inspector.IsSet(Prop(x => x.Precision)) .ShouldBeFalse(); } [Test] public void ScaleMapped() { mapping.Scale = 10; inspector.Scale.ShouldEqual(10); } [Test] public void ScaleIsSet() { mapping.Scale = 10; inspector.IsSet(Prop(x => x.Scale)) .ShouldBeTrue(); } [Test] public void ScaleIsNotSet() { inspector.IsSet(Prop(x => x.Scale)) .ShouldBeFalse(); } [Test] public void SqlTypeMapped() { mapping.SqlType = "type"; inspector.SqlType.ShouldEqual("type"); } [Test] public void SqlTypeIsSet() { mapping.SqlType = "type"; inspector.IsSet(Prop(x => x.SqlType)) .ShouldBeTrue(); } [Test] public void SqlTypeIsNotSet() { inspector.IsSet(Prop(x => x.SqlType)) .ShouldBeFalse(); } [Test] public void UniqueMapped() { mapping.Unique = true; inspector.Unique.ShouldBeTrue(); } [Test] public void UniqueIsSet() { mapping.Unique = true; inspector.IsSet(Prop(x => x.Unique)) .ShouldBeTrue(); } [Test] public void UniqueIsNotSet() { inspector.IsSet(Prop(x => x.Unique)) .ShouldBeFalse(); } [Test] public void UniqueKeyMapped() { mapping.UniqueKey = "key"; inspector.UniqueKey.ShouldEqual("key"); } [Test] public void UniqueKeyIsSet() { mapping.UniqueKey = "key"; inspector.IsSet(Prop(x => x.UniqueKey)) .ShouldBeTrue(); } [Test] public void UniqueKeyIsNotSet() { inspector.IsSet(Prop(x => x.UniqueKey)) .ShouldBeFalse(); } private PropertyInfo Prop(Expression<Func<IColumnInspector, object>> propertyExpression) { return ReflectionHelper.GetProperty(propertyExpression); } } }
// 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. //----------------------------------------------------------------------------- // // Description: // TaskHelper implements some common functions for all the WCP tasks // to call. // //------------------------------------------------------------------------------ using System; using System.IO; using System.Collections; using System.Text; using System.Runtime.InteropServices; using System.Globalization; using System.Diagnostics; using System.Reflection; using System.Resources; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.Build.Tasks; using MS.Utility; using System.Collections.Generic; namespace MS.Internal.Tasks { #region BaseTask class //<summary> // TaskHelper which implements some helper methods. //</summary> internal static class TaskHelper { //------------------------------------------------------ // // Internal Helper Methods // //------------------------------------------------------ #region Internal Methods // <summary> // Output the Logo information to the logger for a given task // (Console or registered Loggers). // </summary> internal static void DisplayLogo(TaskLoggingHelper log, string taskName) { string acPath = Assembly.GetExecutingAssembly().Location; FileVersionInfo acFileVersionInfo = FileVersionInfo.GetVersionInfo(acPath); string avalonFileVersion = acFileVersionInfo.FileVersion; log.LogMessage(MessageImportance.Low,Environment.NewLine); log.LogMessageFromResources(MessageImportance.Low, SRID.TaskLogo, taskName, avalonFileVersion); log.LogMessageFromResources(MessageImportance.Low, SRID.TaskRight); log.LogMessage(MessageImportance.Low, Environment.NewLine); } // <summary> // Create the full file path with the right root path // </summary> // <param name="thePath">The original file path</param> // <param name="rootPath">The root path</param> // <returns>The new fullpath</returns> internal static string CreateFullFilePath(string thePath, string rootPath) { // make it an absolute path if not already so if ( !Path.IsPathRooted(thePath) ) { thePath = rootPath + thePath; } // get rid of '..' and '.' if any thePath = Path.GetFullPath(thePath); return thePath; } // <summary> // This helper returns the "relative" portion of a path // to a given "root" // - both paths need to be rooted // - if no match > return empty string // E.g.: path1 = C:\foo\bar\ // path2 = C:\foo\bar\baz // // return value = "baz" // </summary> internal static string GetRootRelativePath(string path1, string path2) { string relPath = ""; string fullpath1; string fullpath2; string sourceDir = Directory.GetCurrentDirectory() + "\\"; // make sure path1 and Path2 are both full path // so that they can be compared on right base. fullpath1 = CreateFullFilePath (path1, sourceDir); fullpath2 = CreateFullFilePath (path2, sourceDir); if (fullpath2.StartsWith(fullpath1, StringComparison.OrdinalIgnoreCase)) { relPath = fullpath2.Substring (fullpath1.Length); } return relPath; } // <summary> // Convert a string to a Boolean value using exactly the same rules as // MSBuild uses when it assigns project properties to Boolean CLR properties // in a task class. // </summary> // <param name="str">The string value to convert</param> // <returns>true if str is "true", "yes", or "on" (case-insensitive), // otherwise false.</returns> internal static bool BooleanStringValue(string str) { bool isBoolean = false; if (str != null && str.Length > 0) { str = str.ToLower(CultureInfo.InvariantCulture); if (str.Equals("true") || str.Equals("yes") || str.Equals("on")) { isBoolean = true; } } return isBoolean; } // <summary> // return a lower case string // </summary> // <param name="str"></param> // <returns></returns> internal static string GetLowerString(string str) { string lowerStr = null; if (str != null && str.Length > 0) { lowerStr = str.ToLower(CultureInfo.InvariantCulture); } return lowerStr; } // // Check if the passed string stands for a valid culture name. // internal static bool IsValidCultureName(string name) { bool bValid = true; try { // // If the passed name is empty or null, we still want // to treat it as valid culture name. // It means no satellite assembly will be generated, all the // resource images will go to the main assembly. // if (name != null && name.Length > 0) { CultureInfo cl; cl = new CultureInfo(name); // if CultureInfo instance cannot be created for the given name, // treat it as invalid culture name. if (cl == null) bValid = false; } } catch (ArgumentException) { bValid = false; } return bValid; } internal static string GetWholeExceptionMessage(Exception exception) { Exception e = exception; string message = e.Message; while (e.InnerException != null) { Exception eInner = e.InnerException; if (e.Message.IndexOf(eInner.Message, StringComparison.Ordinal) == -1) { message += ", "; message += eInner.Message; } e = eInner; } if (message != null && message.EndsWith(".", StringComparison.Ordinal) == false) { message += "."; } return message; } // // Helper to create CompilerWrapper. // internal static CompilerWrapper CreateCompilerWrapper(bool fInSeparateDomain, ref AppDomain appDomain) { return new CompilerWrapper(); } #endregion Internal Methods } #endregion TaskHelper class }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.HSSF.UserModel { using System; using NPOI.HSSF.Model; using NPOI.SS.Formula.PTG; using NPOI.SS.Formula; using NPOI.SS.UserModel; using System.Text; using NPOI.SS.Util; using System.Globalization; using NPOI.HSSF.Record; /** * * @author Josh Micich */ public class DVConstraint : IDataValidationConstraint { /* package */ public class FormulaPair { private Ptg[] _formula1; private Ptg[] _formula2; public FormulaPair(Ptg[] formula1, Ptg[] formula2) { _formula1 = formula1; _formula2 = formula2; } public Ptg[] Formula1 { get { return _formula1; } } public Ptg[] Formula2 { get { return _formula2; } } } // convenient access to ValidationType namespace //private static ValidationType VT = null; private int _validationType; private int _operator; private String[] _explicitListValues; private String _formula1; private String _formula2; private Double _value1; private Double _value2; private DVConstraint(int validationType, int comparisonOperator, String formulaA, String formulaB, Double value1, Double value2, String[] excplicitListValues) { _validationType = validationType; _operator = comparisonOperator; _formula1 = formulaA; _formula2 = formulaB; _value1 = value1; _value2 = value2; _explicitListValues = excplicitListValues; } /** * Creates a list constraint */ private DVConstraint(String listFormula, String[] excplicitListValues) : this(ValidationType.LIST, OperatorType.IGNORED, listFormula, null, Double.NaN, Double.NaN, excplicitListValues) { ; } /** * Creates a number based data validation constraint. The text values entered for expr1 and expr2 * can be either standard Excel formulas or formatted number values. If the expression starts * with '=' it is Parsed as a formula, otherwise it is Parsed as a formatted number. * * @param validationType one of {@link NPOI.SS.UserModel.DataValidationConstraint.ValidationType#ANY}, * {@link NPOI.SS.UserModel.DataValidationConstraint.ValidationType#DECIMAL}, * {@link NPOI.SS.UserModel.DataValidationConstraint.ValidationType#INTEGER}, * {@link NPOI.SS.UserModel.DataValidationConstraint.ValidationType#TEXT_LENGTH} * @param comparisonOperator any constant from {@link NPOI.SS.UserModel.DataValidationConstraint.OperatorType} enum * @param expr1 date formula (when first char is '=') or formatted number value * @param expr2 date formula (when first char is '=') or formatted number value */ public static DVConstraint CreateNumericConstraint(int validationType, int comparisonOperator, String expr1, String expr2) { switch (validationType) { case ValidationType.ANY: if (expr1 != null || expr2 != null) { throw new ArgumentException("expr1 and expr2 must be null for validation type 'any'"); } break; case ValidationType.DECIMAL: case ValidationType.INTEGER: case ValidationType.TEXT_LENGTH: if (expr1 == null) { throw new ArgumentException("expr1 must be supplied"); } OperatorType.ValidateSecondArg(comparisonOperator, expr2); break; default: throw new ArgumentException("Validation Type (" + validationType + ") not supported with this method"); } // formula1 and value1 are mutually exclusive String formula1 = GetFormulaFromTextExpression(expr1); Double value1 = formula1 == null ? ConvertNumber(expr1) : double.NaN; // formula2 and value2 are mutually exclusive String formula2 = GetFormulaFromTextExpression(expr2); Double value2 = formula2 == null ? ConvertNumber(expr2) : double.NaN; return new DVConstraint(validationType, comparisonOperator, formula1, formula2, value1, value2, null); } public static DVConstraint CreateFormulaListConstraint(String listFormula) { return new DVConstraint(listFormula, null); } public static DVConstraint CreateExplicitListConstraint(String[] explicitListValues) { return new DVConstraint(null, explicitListValues); } /** * Creates a time based data validation constraint. The text values entered for expr1 and expr2 * can be either standard Excel formulas or formatted time values. If the expression starts * with '=' it is Parsed as a formula, otherwise it is Parsed as a formatted time. To parse * formatted times, two formats are supported: "HH:MM" or "HH:MM:SS". This is contrary to * Excel which uses the default time format from the OS. * * @param comparisonOperator constant from {@link NPOI.SS.UserModel.DataValidationConstraint.OperatorType} enum * @param expr1 date formula (when first char is '=') or formatted time value * @param expr2 date formula (when first char is '=') or formatted time value */ public static DVConstraint CreateTimeConstraint(int comparisonOperator, String expr1, String expr2) { if (expr1 == null) { throw new ArgumentException("expr1 must be supplied"); } OperatorType.ValidateSecondArg(comparisonOperator, expr1); // formula1 and value1 are mutually exclusive String formula1 = GetFormulaFromTextExpression(expr1); Double value1 = formula1 == null ? ConvertTime(expr1) : Double.NaN; // formula2 and value2 are mutually exclusive String formula2 = GetFormulaFromTextExpression(expr2); Double value2 = formula2 == null ? ConvertTime(expr2) : Double.NaN; return new DVConstraint(ValidationType.TIME, comparisonOperator, formula1, formula2, value1, value2, null); } /** * Creates a date based data validation constraint. The text values entered for expr1 and expr2 * can be either standard Excel formulas or formatted date values. If the expression starts * with '=' it is Parsed as a formula, otherwise it is Parsed as a formatted date (Excel uses * the same convention). To parse formatted dates, a date format needs to be specified. This * is contrary to Excel which uses the default short date format from the OS. * * @param comparisonOperator constant from {@link NPOI.SS.UserModel.DataValidationConstraint.OperatorType} enum * @param expr1 date formula (when first char is '=') or formatted date value * @param expr2 date formula (when first char is '=') or formatted date value * @param dateFormat ignored if both expr1 and expr2 are formulas. Default value is "YYYY/MM/DD" * otherwise any other valid argument for <c>SimpleDateFormat</c> can be used * @see <a href='http://java.sun.com/j2se/1.5.0/docs/api/java/text/DateFormat.html'>SimpleDateFormat</a> */ public static DVConstraint CreateDateConstraint(int comparisonOperator, String expr1, String expr2, String dateFormat) { if (expr1 == null) { throw new ArgumentException("expr1 must be supplied"); } OperatorType.ValidateSecondArg(comparisonOperator, expr2); SimpleDateFormat df = dateFormat == null ? null : new SimpleDateFormat(dateFormat); // formula1 and value1 are mutually exclusive String formula1 = GetFormulaFromTextExpression(expr1); Double value1 = formula1 == null ? ConvertDate(expr1, df) : Double.NaN; // formula2 and value2 are mutually exclusive String formula2 = GetFormulaFromTextExpression(expr2); Double value2 = formula2 == null ? ConvertDate(expr2, df) : Double.NaN; return new DVConstraint(ValidationType.DATE, comparisonOperator, formula1, formula2, value1, value2, null); } /** * Distinguishes formula expressions from simple value expressions. This logic is only * required by a few factory methods in this class that create data validation constraints * from more or less the same parameters that would have been entered in the Excel UI. The * data validation dialog box uses the convention that formulas begin with '='. Other methods * in this class follow the POI convention (formulas and values are distinct), so the '=' * convention is not used there. * * @param textExpr a formula or value expression * @return all text After '=' if textExpr begins with '='. Otherwise <code>null</code> if textExpr does not begin with '=' */ private static String GetFormulaFromTextExpression(String textExpr) { if (textExpr == null) { return null; } if (textExpr.Length < 1) { throw new ArgumentException("Empty string is not a valid formula/value expression"); } if (textExpr[0] == '=') { return textExpr.Substring(1); } return null; } /** * @return <code>null</code> if numberStr is <code>null</code> */ private static Double ConvertNumber(String numberStr) { if (numberStr == null) { return Double.NaN; } try { return double.Parse(numberStr, CultureInfo.CurrentCulture); } catch (FormatException) { throw new InvalidOperationException("The supplied text '" + numberStr + "' could not be parsed as a number"); } } /** * @return <code>null</code> if timeStr is <code>null</code> */ private static Double ConvertTime(String timeStr) { if (timeStr == null) { return Double.NaN; } return HSSFDateUtil.ConvertTime(timeStr); } /** * @param dateFormat pass <code>null</code> for default YYYYMMDD * @return <code>null</code> if timeStr is <code>null</code> */ private static Double ConvertDate(String dateStr, SimpleDateFormat dateFormat) { if (dateStr == null) { return Double.NaN; } DateTime dateVal; if (dateFormat == null) { dateVal = HSSFDateUtil.ParseYYYYMMDDDate(dateStr); } else { try { dateVal = DateTime.Parse(dateStr, CultureInfo.CurrentCulture); } catch (FormatException e) { throw new InvalidOperationException("Failed to parse date '" + dateStr + "' using specified format '" + dateFormat + "'", e); } } return HSSFDateUtil.GetExcelDate(dateVal); } public static DVConstraint CreateCustomFormulaConstraint(String formula) { if (formula == null) { throw new ArgumentException("formula must be supplied"); } return new DVConstraint(ValidationType.FORMULA, OperatorType.IGNORED, formula, null, double.NaN, double.NaN, null); } /* (non-Javadoc) * @see NPOI.HSSF.UserModel.DataValidationConstraint#getValidationType() */ public int GetValidationType() { return _validationType; } /** * Convenience method * @return <c>true</c> if this constraint is a 'list' validation */ public bool IsListValidationType { get { return _validationType == ValidationType.LIST; } } /** * Convenience method * @return <c>true</c> if this constraint is a 'list' validation with explicit values */ public bool IsExplicitList { get { return _validationType == ValidationType.LIST && _explicitListValues != null; } } public int Operator { get { return _operator; } set { _operator = value; } } public String[] ExplicitListValues { get { return _explicitListValues; } set { if (_validationType != ValidationType.LIST) { throw new InvalidOperationException("Cannot setExplicitListValues on non-list constraint"); } _formula1 = null; _explicitListValues = value; } } /* (non-Javadoc) * @see NPOI.HSSF.UserModel.DataValidationConstraint#getFormula1() */ public String Formula1 { get { return _formula1; } set { _value1 = double.NaN; _explicitListValues = null; _formula1 = value; } } /* (non-Javadoc) * @see NPOI.HSSF.UserModel.DataValidationConstraint#getFormula2() */ public String Formula2 { get { return _formula2; } set { _value2 = double.NaN; _formula2 = value; } } /** * @return the numeric value for expression 1. May be <c>null</c> */ public Double Value1 { get { return _value1; } set { _formula1 = null; _value1 = value; } } /** * @return the numeric value for expression 2. May be <c>null</c> */ public Double Value2 { get { return _value2; } set { _formula2 = null; _value2 = value; } } /** * @return both Parsed formulas (for expression 1 and 2). */ /* package */ public FormulaPair CreateFormulas(HSSFSheet sheet) { Ptg[] formula1; Ptg[] formula2; if (IsListValidationType) { formula1 = CreateListFormula(sheet); formula2 = Ptg.EMPTY_PTG_ARRAY; } else { formula1 = ConvertDoubleFormula(_formula1, _value1, sheet); formula2 = ConvertDoubleFormula(_formula2, _value2, sheet); } return new FormulaPair(formula1, formula2); } private Ptg[] CreateListFormula(HSSFSheet sheet) { if (_explicitListValues == null) { IWorkbook wb = sheet.Workbook; // formula is Parsed with slightly different RVA rules: (root node type must be 'reference') return HSSFFormulaParser.Parse(_formula1, (HSSFWorkbook)wb, FormulaType.DataValidationList, wb.GetSheetIndex(sheet)); // To do: Excel places restrictions on the available operations within a list formula. // Some things like union and intersection are not allowed. } // explicit list was provided StringBuilder sb = new StringBuilder(_explicitListValues.Length * 16); for (int i = 0; i < _explicitListValues.Length; i++) { if (i > 0) { sb.Append('\0'); // list delimiter is the nul char } sb.Append(_explicitListValues[i]); } return new Ptg[] { new StringPtg(sb.ToString()), }; } /** * @return The Parsed token array representing the formula or value specified. * Empty array if both formula and value are <code>null</code> */ private static Ptg[] ConvertDoubleFormula(String formula, Double value, HSSFSheet sheet) { if (formula == null) { if (double.IsNaN(value)) { return Ptg.EMPTY_PTG_ARRAY; } return new Ptg[] { new NumberPtg(value), }; } if (!double.IsNaN(value)) { throw new InvalidOperationException("Both formula and value cannot be present"); } IWorkbook wb = sheet.Workbook; return HSSFFormulaParser.Parse(formula, (HSSFWorkbook)wb, FormulaType.Cell, wb.GetSheetIndex(sheet)); } internal static DVConstraint CreateDVConstraint(DVRecord dvRecord, IFormulaRenderingWorkbook book) { switch (dvRecord.DataType) { case ValidationType.ANY: return new DVConstraint(ValidationType.ANY, dvRecord.ConditionOperator, null, null, double.NaN, double.NaN, null); case ValidationType.INTEGER: case ValidationType.DECIMAL: case ValidationType.DATE: case ValidationType.TIME: case ValidationType.TEXT_LENGTH: FormulaValuePair pair1 = toFormulaString(dvRecord.Formula1, book); FormulaValuePair pair2 = toFormulaString(dvRecord.Formula2, book); return new DVConstraint(dvRecord.DataType, dvRecord.ConditionOperator, pair1.formula(), pair2.formula(), pair1.Value, pair2.Value, null); case ValidationType.LIST: if (dvRecord.ListExplicitFormula) { String values = toFormulaString(dvRecord.Formula1, book).AsString(); if (values.StartsWith("\"")) { values = values.Substring(1); } if (values.EndsWith("\"")) { values = values.Substring(0, values.Length - 1); } String[] explicitListValues = values.Split("\0".ToCharArray()); return CreateExplicitListConstraint(explicitListValues); } else { String listFormula = toFormulaString(dvRecord.Formula1, book).AsString(); return CreateFormulaListConstraint(listFormula); } case ValidationType.FORMULA: return CreateCustomFormulaConstraint(toFormulaString(dvRecord.Formula1, book).AsString()); default: throw new InvalidOperationException(string.Format("validationType={0}", dvRecord.DataType)); } } private class FormulaValuePair { internal String _formula; internal String _value; public String formula() { return _formula; } public Double Value { get { if (_value == null) { return double.NaN; } return double.Parse(_value); } } public String AsString() { if (_formula != null) { return _formula; } if (_value != null) { return _value; } return null; } } private static FormulaValuePair toFormulaString(Ptg[] ptgs, IFormulaRenderingWorkbook book) { FormulaValuePair pair = new FormulaValuePair(); if (ptgs != null && ptgs.Length > 0) { String aString = FormulaRenderer.ToFormulaString(book, ptgs); if (ptgs.Length == 1 && ptgs[0].GetType() == typeof(NumberPtg)) { pair._value = aString; } else { pair._formula = aString; } } return pair; } } }
using DevExpress.DXBinding.Native; using DevExpress.Mvvm.Native; using DevExpress.Mvvm.UI; using DevExpress.Xpf.Core.Native; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Windows; using System.Windows.Data; using System.Windows.Input; using System.Windows.Markup; using System.Xaml; namespace DevExpress.Xpf.DXBinding { public abstract class DXMarkupExtensionBase : MarkupExtension { internal static bool? IsInDesingModeCore = null; protected static bool IsInDesignMode() { if(IsInDesingModeCore != null) return IsInDesingModeCore.Value; DependencyPropertyDescriptor property = DependencyPropertyDescriptor.FromProperty(DesignerProperties.IsInDesignModeProperty, typeof(FrameworkElement)); return (bool)property.Metadata.DefaultValue; } protected static string GetTargetPropertyName(object targetProperty) { return (targetProperty as DependencyProperty).With(x => x.Name) ?? (targetProperty as PropertyInfo).With(x => x.Name) ?? (targetProperty as MethodBase).With(x => x.Name) ?? (targetProperty as EventInfo).With(x => x.Name); } protected static Type GetTargetPropertyType(object targetProperty) { return (targetProperty as DependencyProperty).With(x => x.PropertyType) ?? (targetProperty as PropertyInfo).With(x => x.PropertyType) ?? (targetProperty as EventInfo).With(x => x.EventHandlerType); } protected static bool IsInSetter(IProvideValueTarget targetProvider) { if(targetProvider == null) return false; return targetProvider.TargetObject is Setter; } protected static bool IsInTemplate(IProvideValueTarget targetProvider) { if(targetProvider == null) return false; return targetProvider.TargetObject.GetType().FullName == "System.Windows.SharedDp"; } protected static bool IsInBinding(IProvideValueTarget targetProvider) { if(targetProvider == null) return false; return targetProvider.TargetObject is BindingBase; } IServiceProvider serviceProvider; IProvideValueTarget targetProvider; IXamlTypeResolver xamlTypeResolver; IXamlSchemaContextProvider xamlSchemaContextProvider; protected IServiceProvider ServiceProvider { get { return serviceProvider; } } protected IProvideValueTarget TargetProvider { get { if(targetProvider != null) return targetProvider; if(serviceProvider == null) return null; return targetProvider = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget)); } } protected IXamlTypeResolver XamlTypeResolver { get { if(xamlTypeResolver != null) return xamlTypeResolver; if(serviceProvider == null) return null; return xamlTypeResolver = (IXamlTypeResolver)serviceProvider.GetService(typeof(IXamlTypeResolver)); } } protected IXamlSchemaContextProvider XamlSchemaContextProvider { get { if (xamlSchemaContextProvider != null) return xamlSchemaContextProvider; if (serviceProvider == null) return null; return xamlSchemaContextProvider = (IXamlSchemaContextProvider)serviceProvider.GetService(typeof(IXamlSchemaContextProvider)); } } public sealed override object ProvideValue(IServiceProvider serviceProvider) { try { this.serviceProvider = serviceProvider; return ProvideValueCore(); } finally { this.serviceProvider = null; this.targetProvider = null; this.xamlTypeResolver = null; this.xamlSchemaContextProvider = null; } } protected abstract object ProvideValueCore(); } public enum DXBindingResolvingMode { LegacyStaticTyping, DynamicTyping } public abstract class DXBindingBase : DXMarkupExtensionBase { protected Binding CreateBinding(Operand operand, BindingMode mode) { var path = operand != null && !string.IsNullOrEmpty(operand.Path) ? operand.Path : "."; Binding res = new Binding(); res.Mode = mode; try { res.Path = new PropertyPath(path); } catch (Exception e) { ErrorHandler.Report(e.Message, false); } if (operand == null) return res; try { switch(operand.Source) { case Operand.RelativeSource.Context: break; case Operand.RelativeSource.Ancestor: res.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor) { AncestorType = operand.AncestorType, AncestorLevel = operand.AncestorLevel, }; break; case Operand.RelativeSource.Self: res.RelativeSource = new RelativeSource(RelativeSourceMode.Self); break; case Operand.RelativeSource.Parent: res.RelativeSource = new RelativeSource(RelativeSourceMode.TemplatedParent); break; case Operand.RelativeSource.Element: res.ElementName = operand.ElementName; break; case Operand.RelativeSource.Resource: res.Source = GetStaticResource(operand.ResourceName); break; case Operand.RelativeSource.Reference: res.Source = new Reference(operand.ReferenceName).ProvideValue(ServiceProvider); break; default: throw new InvalidOperationException(); } } catch (Exception e) { ErrorHandler.Report(e.Message, false); } return res; } object GetStaticResource(string resourceName) { object res; if (staticResources != null) staticResources.TryGetValue(resourceName, out res); else res = new StaticResourceExtension(resourceName).ProvideValue(ServiceProvider); return res; } Dictionary<string, object> staticResources; internal readonly IErrorHandler ErrorHandler; internal readonly ITypeResolver TypeResolver; protected internal string TargetPropertyName { get; private set; } protected internal string TargetObjectName { get; private set; } protected internal Type TargetPropertyType { get; private set; } bool IsInitialized { get; set; } public static DXBindingResolvingMode DefaultResolvingMode { get; set; } public DXBindingResolvingMode? ResolvingMode { get; set; } protected DXBindingResolvingMode ActualResolvingMode { get { return ResolvingMode ?? DefaultResolvingMode; } } static DXBindingBase() { DefaultResolvingMode = DXBindingResolvingMode.DynamicTyping; } public bool CatchExceptions { get { return ErrorHandler.CatchAllExceptions; } set { ErrorHandler.CatchAllExceptions = value; } } public DXBindingBase() { ErrorHandler = new IErrorHandlerImpl(this); TypeResolver = new ITypeResolverImpl(this); } protected override object ProvideValueCore() { CheckTargetProvider(); if(XamlTypeResolver != null && !((ITypeResolverImpl)TypeResolver).IsInitialized) { ((ITypeResolverImpl)TypeResolver).SetXamlTypeResolver(XamlTypeResolver); IsInitialized = true; Init(); } if (IsInTemplate(TargetProvider)) { CollectStaticResources(); return this; } InitTargetProperties(); CheckTargetObject(); if(!IsInitialized) Init(); var res = GetProvidedValue(); ((ITypeResolverImpl)TypeResolver).ClearXamlTypeResolver(); return res; } protected abstract void Init(); protected abstract object GetProvidedValue(); void InitTargetProperties() { if(TargetProvider.TargetObject is Setter) { Setter setter = (Setter)TargetProvider.TargetObject; if(setter.Property != null) { TargetPropertyName = GetTargetPropertyName(setter.Property); TargetPropertyType = GetTargetPropertyType(setter.Property); } } else { TargetObjectName = TargetProvider.TargetObject.GetType().Name; TargetPropertyName = GetTargetPropertyName(TargetProvider.TargetProperty); TargetPropertyType = GetTargetPropertyType(TargetProvider.TargetProperty); } } void CollectStaticResources() { if (XamlSchemaContextProvider == null) return; var operands = GetOperands(); if (operands == null) return; staticResources = operands .Where(x => x.Source == Operand.RelativeSource.Resource) .Select(x => x.ResourceName) .Distinct() .ToDictionary(x => x, x => new StaticResourceExtension(x).ProvideValue(ServiceProvider)); } protected abstract IEnumerable<Operand> GetOperands(); protected abstract void Error_Report(string msg); protected abstract void Error_Throw(string msg, Exception innerException); protected virtual void CheckTargetProvider() { if(TargetProvider == null) ErrorHandler.Throw(ErrorHelper.Err001(this), null); if(TargetProvider.TargetObject == null || TargetProvider.TargetProperty == null) ErrorHandler.Throw(ErrorHelper.Err002(this), null); } protected virtual void CheckTargetObject() { if(IsInSetter(TargetProvider)) return; if(TargetPropertyType == typeof(BindingBase)) return; if(TargetProvider.TargetObject is Style && TargetProvider.TargetObject is ITypedStyle) return; if(!(TargetProvider.TargetObject is DependencyObject) || !(TargetProvider.TargetProperty is DependencyProperty)) ErrorHandler.Throw(ErrorHelper.Err002(this), null); } class IErrorHandlerImpl : ErrorHandlerBase { readonly DXBindingBase owner; public IErrorHandlerImpl(DXBindingBase owner) { this.owner = owner; } protected override void ReportCore(string msg) { if(msg == null || IsInDesignMode()) return; owner.Error_Report(msg); } protected override void ThrowCore(string msg, Exception innerException) { owner.Error_Throw(msg, innerException); } } class ITypeResolverImpl : ITypeResolver { readonly DXBindingBase owner; public ITypeResolverImpl(DXBindingBase owner) { this.owner = owner; } public bool IsInitialized { get { return this.xamlTypeResolver != null; } } public void SetXamlTypeResolver(IXamlTypeResolver xamlTypeResolver) { this.xamlTypeResolver = xamlTypeResolver; } public void ClearXamlTypeResolver() { this.xamlTypeResolver = null; } IXamlTypeResolver xamlTypeResolver; Dictionary<string, Type> typeCache = new Dictionary<string, Type>(); Type ITypeResolver.ResolveType(string type) { if(typeCache.ContainsKey(type)) return typeCache[type]; if(IsInDesignMode()) { owner.ErrorHandler.SetError(); return null; } try { var res = xamlTypeResolver.Resolve(type); typeCache.Add(type, res); return res; } catch(Exception e) { owner.ErrorHandler.Throw(ErrorHelper.Err004(type), e); return null; } } } internal class DXBindingConverterBase : IMultiValueConverter, IValueConverter { protected readonly IErrorHandler errorHandler; public DXBindingConverterBase(DXBindingBase owner) { this.errorHandler = owner.ErrorHandler; } object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture) { return ((IMultiValueConverter)this).Convert(new object[] { value }, targetType, parameter, culture); } object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return ((IMultiValueConverter)this).ConvertBack(value, new Type[] { targetType }, parameter, culture).First(); } object IMultiValueConverter.Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { if(!CanConvert(values)) return Binding.DoNothing; object res = Convert(values, targetType); res = CoerceAfterConvert(res, targetType, parameter, culture); return ConvertToTargetType(res, targetType); } object[] IMultiValueConverter.ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { value = CoerceBeforeConvertBack(value, targetTypes, parameter, culture); object[] res = ConvertBack(value, targetTypes); res = CoerceAfterConvertBack(res, targetTypes, parameter, culture); for(int i = 0; i < res.Count(); i++) res[i] = ConvertToTargetType(res[i], targetTypes[i]); return res.ToArray(); } protected virtual bool CanConvert(object[] values) { return !ValuesContainUnsetValue(values); } protected virtual object Convert(object[] values, Type targetType) { return values; } protected virtual object[] ConvertBack(object value, Type[] targetTypes) { throw new NotImplementedException(); } protected virtual object CoerceAfterConvert(object value, Type targetType, object parameter, CultureInfo culture) { return value; } protected virtual object CoerceBeforeConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { return value; } protected virtual object[] CoerceAfterConvertBack(object[] value, Type[] targetTypes, object parameter, CultureInfo culture) { return value; } public static bool ValuesContainUnsetValue(object[] values) { foreach(object v in values) { if(v == DependencyProperty.UnsetValue) return true; } return false; } static object ConvertToTargetType(object value, Type targetType) { if (value == Binding.DoNothing) return value; if(value != null && targetType == typeof(string) && !(value is string)) value = value.ToString(); return value; } } } public sealed class DXBindingExtension : DXBindingBase { public string BindingGroupName { get; set; } public object TargetNullValue { get; set; } public bool NotifyOnSourceUpdated { get; set; } public bool NotifyOnTargetUpdated { get; set; } public bool NotifyOnValidationError { get; set; } internal static UpdateSourceTrigger? DefaultUpdateSourceTrigger = null; public UpdateSourceTrigger UpdateSourceTrigger { get; set; } public bool ValidatesOnDataErrors { get; set; } public bool ValidatesOnExceptions { get; set; } public string Expr { get; set; } public string BackExpr { get; set; } public BindingMode Mode { get; set; } bool isFallbackValueSet = false; object fallbackValue = DependencyProperty.UnsetValue; public object FallbackValue { get { return fallbackValue; } set { fallbackValue = value; isFallbackValueSet = true; } } public IValueConverter Converter { get; set; } [TypeConverter(typeof(CultureInfoIetfLanguageTagConverter))] public CultureInfo ConverterCulture { get; set; } public object ConverterParameter { get; set; } public bool AllowUnsetValue { get; set; } BindingMode ActualMode { get; set; } BindingTreeInfo TreeInfo { get; set; } IBindingCalculator Calculator { get; set; } public DXBindingExtension() : this(string.Empty) { } public DXBindingExtension(string expr) { Expr = expr; UpdateSourceTrigger = DefaultUpdateSourceTrigger ?? UpdateSourceTrigger.Default; Mode = BindingMode.Default; BindingGroupName = string.Empty; AllowUnsetValue = false; } protected override void Error_Report(string msg) { DXBindingException.Report(this, msg); } protected override void Error_Throw(string msg, Exception innerException) { DXBindingException.Throw(this, msg, innerException); } protected override object ProvideValueCore() { var targetProperty = TargetProvider.With(x => x.TargetProperty as DependencyProperty); var targetObject = TargetProvider.With(x => x.TargetObject as DependencyObject); PropertyMetadata metadata = targetProperty != null && targetObject != null ? targetProperty.GetMetadata(targetObject) : null; if(Mode != BindingMode.Default || metadata == null) { ActualMode = Mode; } else { if(!(metadata is FrameworkPropertyMetadata)) ActualMode = BindingMode.OneWay; else if(((FrameworkPropertyMetadata)metadata).BindsTwoWayByDefault) ActualMode = BindingMode.TwoWay; else ActualMode = BindingMode.OneWay; } return base.ProvideValueCore(); } protected override void Init() { TreeInfo = new BindingTreeInfo(Expr, BackExpr, ErrorHandler); if(ActualResolvingMode == DXBindingResolvingMode.LegacyStaticTyping) Calculator = new BindingCalculator(TreeInfo, FallbackValue); else Calculator = new BindingCalculatorDynamic(TreeInfo, FallbackValue); Calculator.Init(TypeResolver); } protected override object GetProvidedValue() { if(Mode == BindingMode.Default && TreeInfo.IsEmptyBackExpr() && Calculator.Operands.Count() == 0) ActualMode = BindingMode.OneWay; if((ActualMode == BindingMode.TwoWay || ActualMode == BindingMode.OneWayToSource) && TreeInfo.IsEmptyBackExpr()) { if(TreeInfo.IsSimpleExpr()) Calculator.Operands.FirstOrDefault().Do(x => x.SetMode(true)); else ErrorHandler.Throw(ErrorHelper.Err101_TwoWay(), null); } if(IsInSetter(TargetProvider) || TargetPropertyType == typeof(BindingBase)) return CreateBinding(); return CreateBinding().ProvideValue(ServiceProvider); } protected override IEnumerable<Operand> GetOperands() { return Calculator != null ? Calculator.Operands : null; } BindingBase CreateBinding() { if(Calculator.Operands.Count() == 0) { var binding = CreateBinding(null, ActualMode); SetBindingProperties(binding, true); binding.Source = Calculator.Resolve(null); binding.Converter = Converter; binding.ConverterParameter = ConverterParameter; binding.ConverterCulture = ConverterCulture; return binding; } if(Calculator.Operands.Count() == 1) { var binding = CreateBinding(Calculator.Operands.First(), ActualMode); SetBindingProperties(binding, true); binding.Converter = CreateConverter(); binding.ConverterParameter = ConverterParameter; binding.ConverterCulture = ConverterCulture; return binding; } if(Calculator.Operands.Count() > 1) { var binding = new MultiBinding() { Mode = ActualMode }; SetBindingProperties(binding, true); binding.Converter = CreateConverter(); binding.ConverterParameter = ConverterParameter; binding.ConverterCulture = ConverterCulture; foreach(var op in Calculator.Operands) { BindingMode mode = ActualMode == BindingMode.OneTime ? BindingMode.OneTime : BindingMode.OneWay; if(op.IsTwoWay) { if(ActualMode == BindingMode.Default) mode = BindingMode.Default; mode = ActualMode == BindingMode.OneWayToSource ? BindingMode.OneWayToSource : BindingMode.TwoWay; } var subBinding = CreateBinding(op, mode); SetBindingProperties(subBinding, false); binding.Bindings.Add(subBinding); } return binding; } throw new NotImplementedException(); } void SetBindingProperties(BindingBase binding, bool isRootBinding) { if(isRootBinding) { if(isFallbackValueSet) binding.FallbackValue = FallbackValue; if(!string.IsNullOrEmpty(BindingGroupName)) binding.BindingGroupName = BindingGroupName; if(TargetNullValue != null) binding.TargetNullValue = TargetNullValue; } if(binding is Binding) { var b = (Binding)binding; b.NotifyOnSourceUpdated = NotifyOnSourceUpdated; b.NotifyOnTargetUpdated = NotifyOnTargetUpdated; b.NotifyOnValidationError = NotifyOnValidationError; b.UpdateSourceTrigger = UpdateSourceTrigger; b.ValidatesOnDataErrors = ValidatesOnDataErrors; b.ValidatesOnExceptions = ValidatesOnExceptions; } else { var b = (MultiBinding)binding; b.NotifyOnSourceUpdated = NotifyOnSourceUpdated; b.NotifyOnTargetUpdated = NotifyOnTargetUpdated; b.NotifyOnValidationError = NotifyOnValidationError; b.UpdateSourceTrigger = UpdateSourceTrigger; b.ValidatesOnDataErrors = ValidatesOnDataErrors; b.ValidatesOnExceptions = ValidatesOnExceptions; } } DXBindingConverterBase CreateConverter() { if(ActualResolvingMode == DXBindingResolvingMode.LegacyStaticTyping) return new DXBindingConverter(this, (BindingCalculator)Calculator); return new DXBindingConverterDynamic(this, (BindingCalculatorDynamic)Calculator, AllowUnsetValue); } class DXBindingConverter : DXBindingConverterBase { readonly BindingTreeInfo treeInfo; readonly BindingCalculator calculator; readonly IValueConverter externalConverter; Type backConversionType; bool isBackConversionInitialized = false; public DXBindingConverter(DXBindingExtension owner, BindingCalculator calculator) : base(owner) { this.treeInfo = owner.TreeInfo; this.calculator = calculator; this.backConversionType = owner.TargetPropertyType; this.externalConverter = owner.Converter; } protected override object Convert(object[] values, Type targetType) { if(backConversionType == null) backConversionType = targetType; errorHandler.ClearError(); return calculator.Resolve(values); } protected override object[] ConvertBack(object value, Type[] targetTypes) { if(treeInfo.IsEmptyBackExpr() && !treeInfo.IsSimpleExpr()) errorHandler.Throw(ErrorHelper.Err101_TwoWay(), null); if(!isBackConversionInitialized) { Type valueType = value.Return(x => x.GetType(), () => null); var backExprType = valueType ?? backConversionType; if(backExprType == null) errorHandler.Throw(ErrorHelper.Err104(), null); calculator.InitBack(valueType ?? backConversionType); isBackConversionInitialized = true; } List<object> res = new List<object>(); foreach(var op in calculator.Operands) { if(!op.IsTwoWay || op.BackConverter == null) res.Add(value); else res.Add(op.BackConverter(new object[] { value })); } return res.ToArray(); } protected override object CoerceAfterConvert(object value, Type targetType, object parameter, CultureInfo culture) { if(externalConverter != null) return externalConverter.Convert(value, targetType, parameter, culture); if(value == DependencyProperty.UnsetValue && targetType == typeof(string)) value = null; else value = ObjectToObjectConverter.Coerce(value, targetType, true); return base.CoerceAfterConvert(value, targetType, parameter, culture); } protected override object CoerceBeforeConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { if(externalConverter != null) { var t = targetTypes != null && targetTypes.Count() == 1 ? targetTypes[0] : backConversionType; return externalConverter.ConvertBack(value, t, parameter, culture); } return base.CoerceBeforeConvertBack(value, targetTypes, parameter, culture); } } class DXBindingConverterDynamic : DXBindingConverterBase { readonly BindingTreeInfo treeInfo; readonly BindingCalculatorDynamic calculator; readonly IValueConverter externalConverter; readonly bool allowUnsetValue; public DXBindingConverterDynamic(DXBindingExtension owner, BindingCalculatorDynamic calculator, bool allowUnsetValue) : base(owner) { this.treeInfo = owner.TreeInfo; this.calculator = calculator; this.externalConverter = owner.Converter; this.allowUnsetValue = allowUnsetValue; } List<WeakReference> valueRefs; protected override object Convert(object[] values, Type targetType) { errorHandler.ClearError(); this.valueRefs = values.Select(x => new WeakReference(x)).ToList(); return calculator.Resolve(values); } protected override object[] ConvertBack(object value, Type[] targetTypes) { if (treeInfo.IsEmptyBackExpr() && !treeInfo.IsSimpleExpr()) errorHandler.Throw(ErrorHelper.Err101_TwoWay(), null); if (treeInfo.IsEmptyBackExpr()) return Enumerable.Range(0, calculator.Operands.Count()).Select(x => value).ToArray(); var values = valueRefs.Select(x => x.Target).ToArray(); var res = calculator.ResolveBack(values, value).ToArray(); return res; } protected override object CoerceAfterConvert(object value, Type targetType, object parameter, CultureInfo culture) { if (externalConverter != null) return externalConverter.Convert(value, targetType, parameter, culture); if (value == Binding.DoNothing) return value; if (value == DependencyProperty.UnsetValue && targetType == typeof(string)) value = null; else value = ObjectToObjectConverter.Coerce(value, targetType, true); return base.CoerceAfterConvert(value, targetType, parameter, culture); } protected override object CoerceBeforeConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { if (externalConverter != null) { var t = targetTypes != null && targetTypes.Count() == 1 ? targetTypes[0] : null; return externalConverter.ConvertBack(value, t, parameter, culture); } return base.CoerceBeforeConvertBack(value, targetTypes, parameter, culture); } protected override object[] CoerceAfterConvertBack(object[] value, Type[] targetTypes, object parameter, CultureInfo culture) { for(int i = 0; i < value.Count(); i++) value[i] = ObjectToObjectConverter.Coerce(value[i], targetTypes[i], true); return base.CoerceAfterConvertBack(value, targetTypes, parameter, culture); } protected override bool CanConvert(object[] values) { return allowUnsetValue || !ValuesContainUnsetValue(values); } } } public sealed class DXCommandExtension : DXBindingBase { public string Execute { get; set; } public string CanExecute { get; set; } public bool FallbackCanExecute { get; set; } CommandTreeInfo TreeInfo { get; set; } ICommandCalculator Calculator { get; set; } public DXCommandExtension() : this(string.Empty) { } public DXCommandExtension(string execute) { Execute = execute; } protected override void Error_Report(string msg) { DXCommandException.Report(this, msg); } protected override void Error_Throw(string msg, Exception innerException) { DXCommandException.Throw(this, msg, innerException); } protected override void Init() { TreeInfo = new CommandTreeInfo(Execute, CanExecute, ErrorHandler); if (ActualResolvingMode == DXBindingResolvingMode.LegacyStaticTyping) Calculator = new CommandCalculator(TreeInfo, FallbackCanExecute); else Calculator = new CommandCalculatorDynamic(TreeInfo, FallbackCanExecute); Calculator.Init(TypeResolver); } protected override object GetProvidedValue() { if(IsInSetter(TargetProvider)) return CreateBinding(); return CreateBinding().ProvideValue(ServiceProvider); } protected override IEnumerable<Operand> GetOperands() { return Calculator != null ? Calculator.Operands : null; } BindingBase CreateBinding() { if(Calculator.Operands.Count() == 0) { var binding = CreateBinding(null, BindingMode.OneWay); SetBindingProperties(binding, true); binding.Source = null; binding.Converter = CreateConverter(true); return binding; } if(Calculator.Operands.Count() == 1) { var binding = CreateBinding(Calculator.Operands.First(), BindingMode.OneWay); SetBindingProperties(binding, true); binding.Converter = CreateConverter(false); return binding; } if(Calculator.Operands.Count() > 1) { var binding = new MultiBinding() { Mode = BindingMode.OneWay }; SetBindingProperties(binding, true); binding.Converter = CreateConverter(false); foreach(var op in Calculator.Operands) { var subBinding = CreateBinding(op, BindingMode.OneWay); SetBindingProperties(subBinding, false); binding.Bindings.Add(subBinding); } return binding; } throw new NotImplementedException(); } void SetBindingProperties(BindingBase binding, bool isRootBinding) { if(binding is Binding) { var b = (Binding)binding; b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; } else { var b = (MultiBinding)binding; b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; } } DXCommandConverter CreateConverter(bool isEmpty) { return new DXCommandConverter(this, isEmpty); } class DXCommandConverter : DXBindingConverterBase { readonly ICommandCalculator calculator; readonly bool fallbackCanExecute; readonly bool isEmpty; public DXCommandConverter(DXCommandExtension owner, bool isEmpty) : base(owner) { this.calculator = owner.Calculator; this.fallbackCanExecute = owner.FallbackCanExecute; this.isEmpty = isEmpty; } protected override object Convert(object[] values, Type targetType) { return new Command(errorHandler, calculator, fallbackCanExecute, isEmpty, values); } protected override bool CanConvert(object[] values) { return true; } } class Command : ICommand { readonly WeakReference errorHandler; readonly WeakReference calculator; readonly WeakReference[] values; readonly bool fallbackCanExecute; readonly bool isEmpty; IErrorHandler ErrorHandler { get { return (IErrorHandler)errorHandler.Target; } } ICommandCalculator Calculator { get { return (ICommandCalculator)calculator.Target; } } object[] Values { get { return isEmpty ? null : values.Select(x => x.Target).ToArray(); } } bool IsAlive { get { bool res = errorHandler.IsAlive && calculator.IsAlive; if(isEmpty) return res; return res && !values.Any(x => !x.IsAlive); } } public Command(IErrorHandler errorHandler, ICommandCalculator calculator, bool fallbackCanExecute, bool isEmpty, object[] values) { this.errorHandler = new WeakReference(errorHandler); this.calculator = new WeakReference(calculator); this.fallbackCanExecute = fallbackCanExecute; this.isEmpty = isEmpty; this.values = values.Select(x => new WeakReference(x)).ToArray(); } void ICommand.Execute(object parameter) { if(!IsAlive) return; ErrorHandler.ClearError(); if(!isEmpty && DXBindingConverterBase.ValuesContainUnsetValue(Values)) return; Calculator.Execute(Values, parameter); } bool ICommand.CanExecute(object parameter) { if(!IsAlive) return fallbackCanExecute; ErrorHandler.ClearError(); if(!isEmpty && DXBindingConverterBase.ValuesContainUnsetValue(Values)) return fallbackCanExecute; return Calculator.CanExecute(Values, parameter); } event EventHandler ICommand.CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } } } public sealed class DXEventExtension : DXBindingBase { public string Handler { get; set; } EventTreeInfo TreeInfo { get; set; } IEventCalculator Calculator { get; set; } public DXEventExtension() : this(string.Empty) { } public DXEventExtension(string expr) { Handler = expr; } protected override void Error_Report(string msg) { DXEventException.Report(this, msg); } protected override void Error_Throw(string msg, Exception innerException) { DXEventException.Throw(this, msg, innerException); } protected override void CheckTargetProvider() { base.CheckTargetProvider(); if(IsInSetter(TargetProvider)) ErrorHandler.Throw(ErrorHelper.Err003(this), null); } protected override void CheckTargetObject() { if(!(TargetProvider.TargetObject is DependencyObject)) ErrorHandler.Throw(ErrorHelper.Err002(this), null); if(TargetProvider.TargetProperty is EventInfo) return; if(TargetProvider.TargetProperty is MethodInfo) { MethodInfo m = (MethodInfo)TargetProvider.TargetProperty; if(m.Name.StartsWith("Add") && m.Name.EndsWith("Handler")) return; } ErrorHandler.Throw(ErrorHelper.Err002(this), null); } protected override void Init() { TreeInfo = new EventTreeInfo(Handler, ErrorHandler); if(ActualResolvingMode == DXBindingResolvingMode.LegacyStaticTyping) Calculator = new EventCalculator(TreeInfo); else Calculator = new EventCalculatorDynamic(TreeInfo); Calculator.Init(TypeResolver); } protected override object GetProvidedValue() { var eventBinder = new EventBinder(this, GetEventHandlerType(), CreateBinding()); return eventBinder.GetEventHandler(); } protected override IEnumerable<Operand> GetOperands() { return Calculator != null ? Calculator.Operands : null; } Type GetEventHandlerType() { if(TargetProvider.TargetProperty is EventInfo) return ((EventInfo)TargetProvider.TargetProperty).EventHandlerType; MethodInfo m = (MethodInfo)TargetProvider.TargetProperty; return m.GetParameters().ElementAt(1).ParameterType; } BindingBase CreateBinding() { if(Calculator.Operands.Count() == 0) { var binding = CreateBinding(null, BindingMode.OneTime); binding.Source = null; binding.Converter = new EventConverter(this, true); return binding; } if(Calculator.Operands.Count() == 1) { var binding = CreateBinding(Calculator.Operands.First(), BindingMode.OneTime); binding.Converter = new EventConverter(this, false); return binding; } if(Calculator.Operands.Count() > 1) { var binding = new MultiBinding() { Mode = BindingMode.OneTime }; foreach(var op in Calculator.Operands) { var subBinding = CreateBinding(op, BindingMode.OneTime); binding.Bindings.Add(subBinding); } binding.Converter = new EventConverter(this, false); return binding; } throw new NotImplementedException(); } class EventBinder { readonly IErrorHandler errorHandler; readonly IEventCalculator calculator; readonly WeakReference targetObject; readonly string handler; readonly Type targetType; readonly string targetPropertyName; readonly Type targetPropertyType; readonly Type eventHandlerType; DependencyProperty dataProperty; static object locker = new object(); static long dataPropertyIndex = 0; static Dictionary<Tuple<Type, string>, DependencyProperty> propertiesCache = new Dictionary<Tuple<Type, string>, DependencyProperty>(); DependencyObject TargetObject { get { return (DependencyObject)targetObject.Target; } } bool IsAlive { get { return targetObject.IsAlive; } } public EventBinder(DXEventExtension owner, Type eventHandlerType, BindingBase binding) { lock (locker) { this.errorHandler = owner.ErrorHandler; this.calculator = owner.Calculator; var target = (DependencyObject)owner.TargetProvider.TargetObject; this.targetObject = new WeakReference(target); this.handler = owner.Handler; this.targetType = target.GetType(); this.targetPropertyName = owner.TargetPropertyName; this.targetPropertyType = owner.TargetPropertyType; this.eventHandlerType = eventHandlerType; var dataPropertyInfo = Tuple.Create(target.GetType(), owner.Handler); if (!propertiesCache.TryGetValue(dataPropertyInfo, out dataProperty)) { dataProperty = DependencyProperty.Register( "Tag" + dataPropertyIndex++.ToString(), typeof(object), dataPropertyInfo.Item1); propertiesCache[dataPropertyInfo] = dataProperty; } BindCore(binding); } } public Delegate GetEventHandler() { var eventSubscriber = new DevExpress.Mvvm.UI.Interactivity.Internal.EventTriggerEventSubscriber(OnEvent); return eventSubscriber.CreateEventHandler(eventHandlerType); } object[] GetBoundEventData() { if(!IsAlive) return null; var res = (IEnumerable<object>)TargetObject.GetValue(dataProperty); if (res == null) { var expr = BindingOperations.GetBindingExpression(TargetObject, dataProperty); if(expr != null && expr.Status == BindingStatus.Unattached) { var b = BindingOperations.GetBinding(TargetObject, dataProperty); BindCore(b); res = (IEnumerable<object>)TargetObject.GetValue(dataProperty); } } return res == null ? null : res.ToArray(); } void OnEvent(object sender, object eventArgs) { var data = GetBoundEventData(); errorHandler.ClearError(); calculator.Event(data, sender, eventArgs); } void BindCore(BindingBase binding) { if (TargetObject == null) return; try { BindingOperations.SetBinding(TargetObject, dataProperty, binding); } catch (Exception e) { string message = "DXEvent cannot set binding on data property. " + Environment.NewLine + "Expr: " + handler + Environment.NewLine + "TargetProperty: " + targetPropertyName + Environment.NewLine + "TargetPropertyType: " + targetPropertyType.ToString() + Environment.NewLine + "TargetObjectType: " + targetType + Environment.NewLine + "DataProperty: " + dataProperty.Name; throw new DXEventException(targetPropertyName, targetType.ToString(), handler, message, e); } } } class EventConverter : DXBindingConverterBase { readonly bool isEmpty; public EventConverter(DXEventExtension owner, bool isEmpty) : base(owner) { this.isEmpty = isEmpty; } protected override object Convert(object[] values, Type targetType) { return isEmpty ? null : new List<object>(values ?? new object[] { }); } } } public abstract class DXBindingExceptionBase<TSelf, TOwner> : Exception where TSelf : DXBindingExceptionBase<TSelf, TOwner> where TOwner : DXBindingBase { public string TargetPropertyName { get; private set; } public string TargetObjectType { get; private set; } protected DXBindingExceptionBase(TOwner owner, string message, Exception innerException) : this(owner.TargetPropertyName, owner.TargetObjectName, message, innerException) { } protected DXBindingExceptionBase(string targetPropertyName, string targetObjectType, string message, Exception innerException) : base(message, innerException) { TargetPropertyName = targetPropertyName; TargetObjectType = targetObjectType; } protected abstract string Report(string message); public static void Throw(TOwner owner, string message, Exception innerException) { throw (TSelf)Activator.CreateInstance(typeof(TSelf), owner, message, innerException); } public static void Report(TOwner owner, string message) { var ex = (TSelf)Activator.CreateInstance(typeof(TSelf), owner, message, null); PresentationTraceSources.DataBindingSource.TraceEvent(TraceEventType.Error, 40, ex.Report(message)); } } public sealed class DXBindingException : DXBindingExceptionBase<DXBindingException, DXBindingExtension> { public string Expr { get; private set; } public string BackExpr { get; private set; } public DXBindingException(DXBindingExtension owner, string message, Exception innerException) : base(owner, message, innerException) { Expr = owner.Expr; BackExpr = owner.BackExpr; } protected override string Report(string message) { return ErrorHelper.ReportBindingError(message, Expr, BackExpr); } } public sealed class DXCommandException : DXBindingExceptionBase<DXCommandException, DXCommandExtension> { public string Execute { get; private set; } public string CanExecute { get; private set; } public DXCommandException(DXCommandExtension owner, string message, Exception innerException) : base(owner, message, innerException) { Execute = owner.Execute; CanExecute = owner.CanExecute; } protected override string Report(string message) { return ErrorHelper.ReportCommandError(message, Execute, CanExecute); } } public sealed class DXEventException : DXBindingExceptionBase<DXEventException, DXEventExtension> { public string Handler { get; private set; } public DXEventException(DXEventExtension owner, string message, Exception innerException) : this(owner.TargetPropertyName, owner.TargetObjectName, owner.Handler, message, innerException) { } public DXEventException(string targetPropertyName, string targetObjectType, string handler, string message, Exception innerException) : base(targetPropertyName, targetObjectType, message, innerException) { Handler = handler; } protected override string Report(string message) { return ErrorHelper.ReportEventError(message, Handler); } } } namespace DevExpress.Xpf.Core.Native { public interface ITypedStyle { } }
using System; using System.IO; using System.Linq; using System.Threading; using System.Collections.Generic; using System.Threading.Tasks; namespace ModernHttpClient { // This is a hacked up version of http://stackoverflow.com/a/3879246/5728 class ConcatenatingStream : Stream { readonly CancellationTokenSource cts = new CancellationTokenSource(); readonly Action onDispose; readonly Action<Exception> exceptionMapper; long position; bool closeStreams; int isEnding = 0; Task blockUntil; IEnumerator<Stream> iterator; Stream current; Stream Current { get { lock(this) { if (current != null) return current; if (iterator == null) throw new ObjectDisposedException(GetType().Name); if (iterator.MoveNext()) { current = iterator.Current; } } return current; } } public ConcatenatingStream(IEnumerable<Func<Stream>> source, bool closeStreams, Action<Exception> exceptionMapper, Task blockUntil = null, Action onDispose = null) { if (source == null) throw new ArgumentNullException("source"); iterator = source.Select(x => x()).GetEnumerator(); this.closeStreams = closeStreams; this.blockUntil = blockUntil; this.onDispose = onDispose; this.exceptionMapper = exceptionMapper; } public override bool CanRead { get { return true; } } public override bool CanWrite { get { return false; } } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override void WriteByte(byte value) { throw new NotSupportedException(); } public override bool CanSeek { get { return false; } } public override bool CanTimeout { get { return false; } } public override void SetLength(long value) { throw new NotSupportedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void Flush() { } public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { return position; } set { if (value != this.position) throw new NotSupportedException(); } } public override async Task<int> ReadAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken) { try { return await InternalReadAsync(buffer, offset, count, cancellationToken); } catch(Exception e) { if(exceptionMapper != null) exceptionMapper(e); throw e; } } public async Task<int> InternalReadAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken) { int result = 0; if (blockUntil != null) { await blockUntil.ContinueWith(_ => {}, cancellationToken); } while (count > 0) { if (cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(); } if (cts.IsCancellationRequested) { throw new OperationCanceledException(); } Stream stream = Current; if (stream == null) break; var thisCount = await stream.ReadAsync(buffer, offset, count); result += thisCount; count -= thisCount; offset += thisCount; if (thisCount == 0) EndOfStream(); } if (cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(); } if (cts.IsCancellationRequested) { throw new OperationCanceledException(); } position += result; return result; } public override int Read (byte[] buffer, int offset, int count) { try { return readInternal(buffer, offset, count); } catch (Exception e) { if(exceptionMapper != null) exceptionMapper(e); throw e; } } int readInternal(byte[] buffer, int offset, int count, CancellationToken ct = default(CancellationToken)) { int result = 0; if (blockUntil != null) { blockUntil.Wait(cts.Token); } while (count > 0) { if (ct.IsCancellationRequested) { throw new OperationCanceledException(); } if (cts.IsCancellationRequested) { throw new OperationCanceledException(); } Stream stream = Current; if (stream == null) break; var thisCount = stream.Read(buffer, offset, count); result += thisCount; count -= thisCount; offset += thisCount; if (thisCount == 0) EndOfStream(); } position += result; return result; } protected override void Dispose(bool disposing) { if (Interlocked.CompareExchange(ref isEnding, 1, 0) == 1) { return; } if (disposing) { cts.Cancel(); lock(this) { while (Current != null) { EndOfStream(); } iterator.Dispose(); iterator = null; current = null; } if (onDispose != null) onDispose(); } base.Dispose(disposing); } void EndOfStream() { lock(this) { if (closeStreams && current != null) { current.Close(); current.Dispose(); } current = null; } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; [AddComponentMenu("DudeWorld/Damageable")] [RequireComponent(typeof(Dude))] public class Damageable : MonoBehaviour { public int maxHealth = 100; public int team = 0; public float armor = 0.0f; public float invincibilityDuration = 1.0f; public GameObject hitEffect; public GameObject blockEffect; public bool invincibleWhenHit = false; public bool directionalBlock = false; private int health = 100; private float backstabAngle = 0.4f; private bool invincible = false; private Dude dude; private SwordzDude swordz; public int Health { get; private set; } // last thing that attacked me public GameObject attacker { get; private set; } // what killed me... pretty much always null unless I just got killed public GameObject killer { get; private set; } void Awake() { health = maxHealth; dude = GetComponent<Dude>(); swordz = GetComponent<SwordzDude>(); } public void OnShot(DamageEvent d) { // heal bullet! if(d.damage < 0) { // heal my own team, do nothing to other people if(d.team == team) { AddHealth(-d.damage); } return; } if(d.team == team || invincible) return; Vector3 attackVec = Vector3.zero; if(d.owner != null) { Vector3 ownerPos = d.owner.transform.position; // bring them to the same y level as us, to make sure we don't knock them up over terrain ownerPos.y = transform.position.y; attackVec = (transform.position - ownerPos).normalized; } if(d.knockback > 0.0f) { Vector3 forceVec; // for melee weapons, knockback should be from the attacker /* if(d.owner != null) forceVec = (transform.position - d.owner.transform.position).normalized; else // for ranged weapons, knockback should come form the bullet forceVec = (transform.position - d. .position).normalized; */ dude.AddForce(attackVec * d.knockback); } // certain effects bypass blocking, so we apply them now /* var bypassEffects = new string[] { "OnWeakened" }; if(d.effects.Count > 0) { foreach(var effect in bypassEffects) { if(d.effects.ContainsKey(effect)) { gameObject.SendMessage(effect, d.effects[effect], SendMessageOptions.DontRequireReceiver); d.effects.Remove(effect); } } } */ // calculate angle-affected stuff var angle = Vector3.Dot(attackVec, transform.forward); // see if I'm blocking in the correct direction if(dude.blocking) { if(directionalBlock && angle > 0.0f) { // not blocking in the right direction! } else { Instantiate(blockEffect, transform.position, transform.rotation); gameObject.BroadcastMessage("OnShotBlocked", d); return; } } // start calculating bonus damage, etc. ////////////////////////// /* if(d.damage > 0) { // backstab if(swordz.status.stunned || angle > backstabAngle) { d.damage *= 2; Debug.Log("CRITICAL HIT! " + d.damage + " - " + angle); } } */ d.damage -= (int)(d.damage * armor); // no more damage calculation below this point /////////////////// // handle armor //swordz.armor; // the hit has officially caused damage, we're spawning an effect //////// if(hitEffect != null && d.damage > 0) { //var blood = Instantiate(hitEffect, Util.flatten(transform.position), transform.rotation) as GameObject; var blood = Instantiate(hitEffect, transform.position, transform.rotation) as GameObject; } // calculate inflicted damage... if this is a killing blow we only count damage inflicted to kill int inflicted = Mathf.Min(health, d.damage); attacker = d.owner; health -= d.damage; if(health <= 0) { killer = d.owner; gameObject.BroadcastMessage("OnKill", killer); } else if(health > maxHealth) { health = maxHealth; } // record metrics // send special effects foreach(KeyValuePair<string, object> pair in d.effects) { gameObject.SendMessage(pair.Key, pair.Value, SendMessageOptions.DontRequireReceiver); } // report to the owner that the hit was successful // FIXME: I am screwing with damage here 'cause it's just a lot easier than copying d.damage = inflicted; if(d.owner != null) d.owner.BroadcastMessage("OnShotHit", d, SendMessageOptions.DontRequireReceiver); //if(!invincibleWhenHit) // gameObject.SendMessage("OnInterrupt"); if(invincibleWhenHit && d.damage > 0 && health > 0) StartCoroutine("doInvincible", invincibilityDuration); if(gameObject.CompareTag("Player") && d.damage > 0) { /* GameObject director = GameObject.FindGameObjectWithTag("Director"); if(director != null) director.SendMessage("OnPlayerHit", d); */ } } IEnumerator doInvincible(float delay) { var graphics = transform.Find("graphics"); invincible = true; graphics.BroadcastMessage("StartEffect"); yield return new WaitForSeconds(delay); invincible = false; graphics.BroadcastMessage("StopEffect"); } /* public void OnTriggerEnter(Collider other) { Debug.Log("oof! I bumped into a " + other.gameObject.name); } */ public int GetHealth() { return health; } public void AddHealth(int hp) { /* // heals! var heals = Resources.Load("Effects/effect_heal"); Instantiate(heals, transform.position, transform.rotation); */ health += hp; if(health > maxHealth) health = maxHealth; } }
using System; using System.Collections.Generic; using System.CodeDom; using System.Configuration; namespace Thinktecture.Tools.Web.Services.CodeGeneration { /// <summary> /// This class represents the generated code tree. /// </summary> /// <remarks> /// This is a customized data structure that is optimized for WSCF /// code generation purposes. It provides faster access to service contracts, /// service types, client types, message contracts and data contracts. Furthermore /// this class provides the common operations for adding new types and substituting /// one type with another. /// An instance of this class is handed over to each ICodeDecorator. /// </remarks> public sealed class ExtendedCodeDomTree { private readonly CodeNamespace codeNamespace; #region Constructors /// <summary> /// Creates a new instance of GeneratedCode class. /// </summary> /// <param name="codeNamespace">The <see cref="codeNamespace"/> containing the code to be wrapped.</param> /// <param name="codeLanguage">The language the code was generated for.</param> /// <param name="configuration">The configuration associated with the generated code.</param> /// <remarks> /// This class can only be initialized by CodeFactory. /// Therefore this constructor is marked as internal. /// </remarks> internal ExtendedCodeDomTree(CodeNamespace codeNamespace, CodeLanguage codeLanguage, Configuration configuration) { this.codeNamespace = codeNamespace; CodeLanguauge = codeLanguage; Configuration = configuration; ServiceContracts = new FilteredTypes(codeNamespace); ServiceTypes = new FilteredTypes(codeNamespace); ClientTypes = new FilteredTypes(codeNamespace); DataContracts = new FilteredTypes(codeNamespace); MessageContracts = new FilteredTypes(codeNamespace); UnfilteredTypes = new FilteredTypes(codeNamespace); TextFiles = new List<TextFile>(); ParseAndFilterCodeNamespace(); } #endregion #region Public properties /// <summary> /// Gets the service contracts. /// </summary> public FilteredTypes ServiceContracts { get; private set; } /// <summary> /// Gets the service types. /// </summary> public FilteredTypes ServiceTypes { get; private set; } /// <summary> /// Gets the client types. /// </summary> public FilteredTypes ClientTypes { get; private set; } /// <summary> /// Gets the data contracts. /// </summary> public FilteredTypes DataContracts { get; private set; } /// <summary> /// Gets the message contracts. /// </summary> public FilteredTypes MessageContracts { get; private set; } /// <summary> /// Gets the unfiltered types. /// </summary> public FilteredTypes UnfilteredTypes { get; private set; } /// <summary> /// Gets the language the code was generated for. /// </summary> public CodeLanguage CodeLanguauge { get; private set; } /// <summary> /// Gets the generated configuration object. /// </summary> public Configuration Configuration { get; private set; } /// <summary> /// Gets or sets the text files. /// </summary> public List<TextFile> TextFiles { get; private set; } #endregion #region Public methods /// <summary> /// Gets the modified CodeDom CodeNamespace instance without additional wrappers. /// This instance can be used with standard code generation APIs to emit the final /// code. /// </summary> public CodeNamespace UnwrapCodeDomTree() { foreach (CodeTypeDeclaration ctd in codeNamespace.Types) { // Unwrap the members. for (int j = 0; j < ctd.Members.Count; j++) { CodeTypeMemberExtension memberExt = ctd.Members[j] as CodeTypeMemberExtension; if (memberExt != null) { ctd.Members[j] = memberExt.ExtendedObject; } } } return codeNamespace; } /// <summary> /// Substitutes one type by another. /// </summary> /// <param name="oldType">Name of the type to substitute.</param> /// <param name="newType">CodeTypeDeclaration of the new type.</param> public void SubstituteType(string oldType, CodeTypeDeclaration newType) { throw new NotImplementedException(); } #endregion /// <summary> /// This method contains the core implementation for generating the GeneratedCode /// instance. /// </summary> /// <remarks> /// This method decorates every type found in codeNamespace with a CodeTypeMemberExtension. /// And then it sends each type through series of ITypeFilters to figure out whether the type /// is a service contract, service type, client type, message contract or data contract. /// </remarks> private void ParseAndFilterCodeNamespace() { ITypeFilter dataContractTypeFilter = new DataContractTypeFilter(); ITypeFilter messageContractTypeFilter = new MessageContractTypeFilter(); ITypeFilter serviceContractTypeFilter = new ServiceContractTypeFilter(); ITypeFilter clientTypeTypeFilter = new ClientTypeTypeFilter(); ITypeFilter serviceTypeTypeFilter = new ServiceTypeTypeFilter(); for (int i = 0; i < codeNamespace.Types.Count; i++) { // Take a reference to the current CodeTypeDeclaration. CodeTypeDeclaration ctd = codeNamespace.Types[i]; // Create a new instance of CodeTypeMemberExtension to wrap // the current CodeTypeDeclaration. CodeTypeExtension typeExtension = new CodeTypeExtension(ctd); // Also wrap the inner CodeTypeMember(s) ExtendTypeMembers(typeExtension); // Here we execute the type filters in the highest to lowest probability order. if (dataContractTypeFilter.IsMatching(typeExtension)) { typeExtension.Kind = CodeTypeKind.DataContract; DataContracts.Add(typeExtension); continue; } if (messageContractTypeFilter.IsMatching(typeExtension)) { typeExtension.Kind = CodeTypeKind.MessageContract; MessageContracts.Add(typeExtension); continue; } if (serviceContractTypeFilter.IsMatching(typeExtension)) { typeExtension.Kind = CodeTypeKind.ServiceContract; ServiceContracts.Add(typeExtension); continue; } if (clientTypeTypeFilter.IsMatching(typeExtension)) { typeExtension.Kind = CodeTypeKind.ClientType; ClientTypes.Add(typeExtension); continue; } if (serviceTypeTypeFilter.IsMatching(typeExtension)) { typeExtension.Kind = CodeTypeKind.ServiceType; ServiceTypes.Add(typeExtension); continue; } UnfilteredTypes.Add(typeExtension); } } /// <summary> /// This methods adds CodeTypeMemberExtension to all CodeTypeMembers in a /// given type. /// </summary> private static void ExtendTypeMembers(CodeTypeExtension typeExtension) { CodeTypeDeclaration type = (CodeTypeDeclaration)typeExtension.ExtendedObject; for (int i = 0; i < type.Members.Count; i++) { CodeTypeMember member = type.Members[i]; CodeTypeMemberExtension memberExtension = new CodeTypeMemberExtension(member, typeExtension); // Add the member to the correct filtered collection. if (memberExtension.Kind == CodeTypeMemberKind.Field) { typeExtension.Fields.Add(memberExtension); } else if (memberExtension.Kind == CodeTypeMemberKind.Property) { typeExtension.Properties.Add(memberExtension); } else if (memberExtension.Kind == CodeTypeMemberKind.Method) { typeExtension.Methods.Add(memberExtension); } else if (memberExtension.Kind == CodeTypeMemberKind.Constructor || memberExtension.Kind == CodeTypeMemberKind.StaticConstructor) { typeExtension.Constructors.Add(memberExtension); } else if (memberExtension.Kind == CodeTypeMemberKind.Event) { typeExtension.Events.Add(memberExtension); } else { typeExtension.Unknown.Add(memberExtension); } // Finally update the collection item reference. type.Members[i] = memberExtension; } } } }
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Wtwd.PublishSubscribe.Client; using Wtwd.PublishSubscribe.Service; using Wtwd.PublishSubscribe.Service.Hubs; using Xunit; namespace Wtwd.PublishSubscribe.IntegrationTests { public class PublishSubscribeHubTests : IDisposable { private readonly TestServer _testServer; public PublishSubscribeHubTests() { var webHostBuilder = new WebHostBuilder().UseStartup(typeof(Startup)); //ConfigureServices(services => //{ // services.AddSignalR(); //}) //.Configure(app => //{ // app.UseSignalR(routes => // { // routes.MapHub<PublishSubscribeHub>("/PublishSubscribe"); // }); //}); _testServer = new TestServer(webHostBuilder); } [Fact] public async Task WhenConnectedTwice_ThenInvalidOperationExceptionIsThrown() { // Arrange IPublishSubscribeHubClient client = new PublishSubscribeHubClient(new Uri("http://test/"), CreateLogger()); using (var httpClient = _testServer.CreateClient()) { // Act await client.ConnectAsync(httpClient); // Assert await Assert.ThrowsAsync<InvalidOperationException>(async () => await client.ConnectAsync(httpClient)); } } [Fact] public async Task WhenDisconectAndNeverConnectedBefore_ThenItDoesNotFail() { // Arrange IPublishSubscribeHubClient client = new PublishSubscribeHubClient(new Uri("http://test/"), CreateLogger()); using (var httpClient = _testServer.CreateClient()) { // Act await client.DisconnectAsync(); // Assert } } [Fact] public async Task WhenConnectedAndDisconectTwice_ThenItDoesNotFail() { // Arrange IPublishSubscribeHubClient client = new PublishSubscribeHubClient(new Uri("http://test/"), CreateLogger()); using (var httpClient = _testServer.CreateClient()) { // Act await client.ConnectAsync(httpClient); await client.DisconnectAsync(); await client.DisconnectAsync(); // Assert } } [Fact] public async Task WhenClientSubscribeToTopic_ThenCanRecieveSimpleTypeMessages() { // Arrange string topic = "anyTopic"; string content = "Hi, how do you do?"; bool messageReceived = false; string contentReceived = string.Empty; Action<string> handler = (param) => { messageReceived = true; contentReceived = param; }; IPublishSubscribeHubClient client = new PublishSubscribeHubClient(new Uri("http://test/"), CreateLogger()); using (var httpClient = _testServer.CreateClient()) { // Act await client.ConnectAsync(httpClient); await client.SubscribeAsync(topic, handler); await client.SendAsync(topic, content); // Not good but needed... await Task.Delay(50); await client.UnSubscribeAsync(topic); await client.DisconnectAsync(); // Assert Assert.True(messageReceived); Assert.Equal(content, contentReceived); } } [Fact] public async Task WhenClientSubscribeToTopic_ThenCanRecieveComplexTypeMessages() { // Arrange string topic = "anyTopic"; DateTime content = DateTime.MaxValue; bool messageReceived = false; DateTime contentReceived = DateTime.MinValue; Action<DateTime> handler = (param) => { messageReceived = true; contentReceived = param; }; IPublishSubscribeHubClient client = new PublishSubscribeHubClient(new Uri("http://test/"), CreateLogger()); using (var httpClient = _testServer.CreateClient()) { // Act await client.ConnectAsync(httpClient); await client.SubscribeAsync(topic, handler); await client.SendAsync(topic, content); // Not good but needed... await Task.Delay(50); await client.UnSubscribeAsync(topic); await client.DisconnectAsync(); // Assert Assert.True(messageReceived); Assert.Equal(content, contentReceived); } } [Fact] public async Task WhenClientSubscribeAnsUnsubscribeToTopic_ThenDoNotRecieveMessages() { // Arrange string topic = "anyTopic"; string content = "Hi, how do you do?"; bool messageReceived = false; string contentReceived = string.Empty; Action<string> handler = (obj) => { messageReceived = true; contentReceived = obj; }; IPublishSubscribeHubClient client = new PublishSubscribeHubClient(new Uri("http://test/"), CreateLogger()); using (var httpClient = _testServer.CreateClient()) { // Act await client.ConnectAsync(httpClient); await client.SubscribeAsync(topic, handler); // Not good but needed... await Task.Delay(50); await client.UnSubscribeAsync(topic); await client.SendAsync(topic, content); await client.DisconnectAsync(); // Assert Assert.False(messageReceived); Assert.Equal(string.Empty, contentReceived); } } [Fact] public async Task WhenTwoClientsSubscribeExpectingDifferentTypes_HandlerWithWrongTypeIsNotExecuted() { // Arrange string topic = "anyTopic"; TimeSpan content_1 = new TimeSpan(12345); var handler_1_executed = false; var handler_2_executed = false; Action<TimeSpan> handler_1 = (obj) => { handler_1_executed = true; }; Action<int> handler_2 = (obj) => { handler_1_executed = true; }; IPublishSubscribeHubClient client_1 = new PublishSubscribeHubClient(new Uri("http://test/"), CreateLogger()); IPublishSubscribeHubClient client_2 = new PublishSubscribeHubClient(new Uri("http://test/"), CreateLogger()); using (var httpClient_1 = _testServer.CreateClient()) { await client_1.ConnectAsync(httpClient_1); await client_1.SubscribeAsync(topic, handler_1); using (var httpClient_2 = _testServer.CreateClient()) { await client_2.ConnectAsync(httpClient_2); await client_2.SubscribeAsync(topic, handler_2); await client_1.SendAsync(topic, content_1); // Not good but needed... await Task.Delay(50); await client_2.UnSubscribeAsync(topic); await client_2.DisconnectAsync(); } await client_1.UnSubscribeAsync(topic); await client_1.DisconnectAsync(); // Assert Assert.True(handler_1_executed); Assert.False(handler_2_executed); } } public void Dispose() { if (_testServer != null) { _testServer.Dispose(); } } private static ILogger<PublishSubscribeHubClient> CreateLogger() { var loggerFactory = new LoggerFactory(); loggerFactory.AddConsole(LogLevel.Trace); var logger = loggerFactory.CreateLogger<PublishSubscribeHubClient>(); return logger; } } }
// 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 Internal.IL; using Internal.TypeSystem; using Internal.Text; using ILCompiler.DependencyAnalysis; using Debug = System.Diagnostics.Debug; namespace ILCompiler { /// <summary> /// Captures information required to generate a ReadyToRun helper to create a delegate type instance /// pointing to a specific target method. /// </summary> public sealed class DelegateCreationInfo { private enum TargetKind { CanonicalEntrypoint, ExactCallableAddress, InterfaceDispatch, VTableLookup, MethodHandle, } private TargetKind _targetKind; /// <summary> /// Gets the node corresponding to the method that initializes the delegate. /// </summary> public IMethodNode Constructor { get; } public MethodDesc TargetMethod { get; } private bool TargetMethodIsUnboxingThunk { get { return TargetMethod.OwningType.IsValueType && !TargetMethod.Signature.IsStatic; } } public bool TargetNeedsVTableLookup => _targetKind == TargetKind.VTableLookup; public bool NeedsVirtualMethodUseTracking { get { return _targetKind == TargetKind.VTableLookup || _targetKind == TargetKind.InterfaceDispatch; } } public bool NeedsRuntimeLookup { get { switch (_targetKind) { case TargetKind.VTableLookup: return false; case TargetKind.CanonicalEntrypoint: case TargetKind.ExactCallableAddress: case TargetKind.InterfaceDispatch: case TargetKind.MethodHandle: return TargetMethod.IsRuntimeDeterminedExactMethod; default: Debug.Assert(false); return false; } } } // None of the data structures that support shared generics have been ported to the JIT // codebase which makes this a huge PITA. Not including the method for JIT since nobody // uses it in that mode anyway. #if !SUPPORT_JIT public GenericLookupResult GetLookupKind(NodeFactory factory) { Debug.Assert(NeedsRuntimeLookup); switch (_targetKind) { case TargetKind.ExactCallableAddress: return factory.GenericLookup.MethodEntry(TargetMethod, TargetMethodIsUnboxingThunk); case TargetKind.InterfaceDispatch: return factory.GenericLookup.VirtualMethodAddress(TargetMethod); default: Debug.Assert(false); return null; } } #endif /// <summary> /// Gets the node representing the target method of the delegate if no runtime lookup is needed. /// </summary> public ISymbolNode GetTargetNode(NodeFactory factory) { Debug.Assert(!NeedsRuntimeLookup); switch (_targetKind) { case TargetKind.CanonicalEntrypoint: return factory.CanonicalEntrypoint(TargetMethod, TargetMethodIsUnboxingThunk); case TargetKind.ExactCallableAddress: return factory.ExactCallableAddress(TargetMethod, TargetMethodIsUnboxingThunk); case TargetKind.InterfaceDispatch: return factory.InterfaceDispatchCell(TargetMethod); case TargetKind.MethodHandle: return factory.RuntimeMethodHandle(TargetMethod); case TargetKind.VTableLookup: Debug.Assert(false, "Need to do runtime lookup"); return null; default: Debug.Assert(false); return null; } } /// <summary> /// Gets an optional node passed as an additional argument to the constructor. /// </summary> public IMethodNode Thunk { get; } private DelegateCreationInfo(IMethodNode constructor, MethodDesc targetMethod, TargetKind targetKind, IMethodNode thunk = null) { Constructor = constructor; TargetMethod = targetMethod; _targetKind = targetKind; Thunk = thunk; } /// <summary> /// Constructs a new instance of <see cref="DelegateCreationInfo"/> set up to construct a delegate of type /// '<paramref name="delegateType"/>' pointing to '<paramref name="targetMethod"/>'. /// </summary> public static DelegateCreationInfo Create(TypeDesc delegateType, MethodDesc targetMethod, NodeFactory factory, bool followVirtualDispatch) { TypeSystemContext context = delegateType.Context; DefType systemDelegate = context.GetWellKnownType(WellKnownType.MulticastDelegate).BaseType; int paramCountTargetMethod = targetMethod.Signature.Length; if (!targetMethod.Signature.IsStatic) { paramCountTargetMethod++; } DelegateInfo delegateInfo = context.GetDelegateInfo(delegateType.GetTypeDefinition()); int paramCountDelegateClosed = delegateInfo.Signature.Length + 1; bool closed = false; if (paramCountDelegateClosed == paramCountTargetMethod) { closed = true; } else { Debug.Assert(paramCountDelegateClosed == paramCountTargetMethod + 1); } if (targetMethod.Signature.IsStatic) { MethodDesc invokeThunk; MethodDesc initMethod; if (!closed) { // Open delegate to a static method if (targetMethod.IsNativeCallable) { // If target method is native callable, create a reverse PInvoke delegate initMethod = systemDelegate.GetKnownMethod("InitializeReversePInvokeThunk", null); invokeThunk = delegateInfo.Thunks[DelegateThunkKind.ReversePinvokeThunk]; // You might hit this when the delegate is generic: you need to make the delegate non-generic. // If the code works on Project N, it's because the delegate is used in connection with // AddrOf intrinsic (please validate that). We don't have the necessary AddrOf expansion in // the codegen to make this work without actually constructing the delegate. You can't construct // the delegate if it's generic, even on Project N. // TODO: Make this throw something like "TypeSystemException.InvalidProgramException"? Debug.Assert(invokeThunk != null, "Delegate with a non-native signature for a NativeCallable method"); } else { initMethod = systemDelegate.GetKnownMethod("InitializeOpenStaticThunk", null); invokeThunk = delegateInfo.Thunks[DelegateThunkKind.OpenStaticThunk]; } } else { // Closed delegate to a static method (i.e. delegate to an extension method that locks the first parameter) invokeThunk = delegateInfo.Thunks[DelegateThunkKind.ClosedStaticThunk]; initMethod = systemDelegate.GetKnownMethod("InitializeClosedStaticThunk", null); } var instantiatedDelegateType = delegateType as InstantiatedType; if (instantiatedDelegateType != null) invokeThunk = context.GetMethodForInstantiatedType(invokeThunk, instantiatedDelegateType); return new DelegateCreationInfo( factory.MethodEntrypoint(initMethod), targetMethod, TargetKind.ExactCallableAddress, factory.MethodEntrypoint(invokeThunk)); } else { if (!closed) throw new NotImplementedException("Open instance delegates"); string initializeMethodName = "InitializeClosedInstance"; MethodDesc targetCanonMethod = targetMethod.GetCanonMethodTarget(CanonicalFormKind.Specific); TargetKind kind; if (targetMethod.HasInstantiation) { if (targetMethod.IsVirtual) { initializeMethodName = "InitializeClosedInstanceWithGVMResolution"; kind = TargetKind.MethodHandle; } else { if (targetMethod != targetCanonMethod) { // Closed delegates to generic instance methods need to be constructed through a slow helper that // checks for the fat function pointer case (function pointer + instantiation argument in a single // pointer) and injects an invocation thunk to unwrap the fat function pointer as part of // the invocation if necessary. initializeMethodName = "InitializeClosedInstanceSlow"; } kind = TargetKind.ExactCallableAddress; } } else { if (followVirtualDispatch && targetMethod.IsVirtual) { if (targetMethod.OwningType.IsInterface) { kind = TargetKind.InterfaceDispatch; initializeMethodName = "InitializeClosedInstanceToInterface"; } else { kind = TargetKind.VTableLookup; targetMethod = targetMethod.GetCanonMethodTarget(CanonicalFormKind.Specific); } } else { kind = TargetKind.CanonicalEntrypoint; targetMethod = targetMethod.GetCanonMethodTarget(CanonicalFormKind.Specific); } } return new DelegateCreationInfo( factory.MethodEntrypoint(systemDelegate.GetKnownMethod(initializeMethodName, null)), targetMethod, kind); } } public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append("__DelegateCtor_"); if (TargetNeedsVTableLookup) sb.Append("FromVtbl_"); Constructor.AppendMangledName(nameMangler, sb); sb.Append("__"); sb.Append(nameMangler.GetMangledMethodName(TargetMethod)); if (Thunk != null) { sb.Append("__"); Thunk.AppendMangledName(nameMangler, sb); } } public override bool Equals(object obj) { var other = obj as DelegateCreationInfo; return other != null && Constructor == other.Constructor && TargetMethod == other.TargetMethod && _targetKind == other._targetKind && Thunk == other.Thunk; } public override int GetHashCode() { return Constructor.GetHashCode() ^ TargetMethod.GetHashCode(); } } }
namespace Moritz { partial class MoritzForm1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.QuitButton = new System.Windows.Forms.Button(); this.PreferencesButton = new System.Windows.Forms.Button(); this.LoadScoreSettingsButton = new System.Windows.Forms.Button(); this.KrystalsEditorButton = new System.Windows.Forms.Button(); this.AssistantComposerPanel = new System.Windows.Forms.Panel(); this.AssistantComposerLabel = new System.Windows.Forms.Label(); this.KrystalsEditorPanel = new System.Windows.Forms.Panel(); this.KrystalsEditorLabel = new System.Windows.Forms.Label(); this.panel1 = new System.Windows.Forms.Panel(); this.AboutButton = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.AssistantComposerPanel.SuspendLayout(); this.KrystalsEditorPanel.SuspendLayout(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // QuitButton // this.QuitButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(64)))), ((int)(((byte)(0))))); this.QuitButton.Location = new System.Drawing.Point(105, 281); this.QuitButton.Name = "QuitButton"; this.QuitButton.Size = new System.Drawing.Size(113, 31); this.QuitButton.TabIndex = 2; this.QuitButton.Text = "quit"; this.QuitButton.UseVisualStyleBackColor = true; this.QuitButton.Click += new System.EventHandler(this.QuitButton_Click); // // PreferencesButton // this.PreferencesButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(64)))), ((int)(((byte)(0))))); this.PreferencesButton.Location = new System.Drawing.Point(31, 30); this.PreferencesButton.Name = "PreferencesButton"; this.PreferencesButton.Size = new System.Drawing.Size(113, 31); this.PreferencesButton.TabIndex = 0; this.PreferencesButton.Text = "preferences"; this.PreferencesButton.UseVisualStyleBackColor = true; this.PreferencesButton.Click += new System.EventHandler(this.PreferencesButton_Click); // // LoadScoreSettingsButton // this.LoadScoreSettingsButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(64)))), ((int)(((byte)(0))))); this.LoadScoreSettingsButton.Location = new System.Drawing.Point(92, 30); this.LoadScoreSettingsButton.Name = "LoadScoreSettingsButton"; this.LoadScoreSettingsButton.Size = new System.Drawing.Size(113, 31); this.LoadScoreSettingsButton.TabIndex = 0; this.LoadScoreSettingsButton.Text = "load settings"; this.LoadScoreSettingsButton.UseVisualStyleBackColor = true; this.LoadScoreSettingsButton.Click += new System.EventHandler(this.LoadScoreSettingsButton_Click); // // KrystalsEditorButton // this.KrystalsEditorButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(64)))), ((int)(((byte)(0))))); this.KrystalsEditorButton.Location = new System.Drawing.Point(92, 30); this.KrystalsEditorButton.Name = "KrystalsEditorButton"; this.KrystalsEditorButton.Size = new System.Drawing.Size(113, 31); this.KrystalsEditorButton.TabIndex = 0; this.KrystalsEditorButton.Text = "open"; this.KrystalsEditorButton.UseVisualStyleBackColor = true; this.KrystalsEditorButton.Click += new System.EventHandler(this.KrystalsEditorButton_Click); // // AssistantComposerPanel // this.AssistantComposerPanel.BackColor = System.Drawing.Color.Honeydew; this.AssistantComposerPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.AssistantComposerPanel.Controls.Add(this.AssistantComposerLabel); this.AssistantComposerPanel.Controls.Add(this.LoadScoreSettingsButton); this.AssistantComposerPanel.Location = new System.Drawing.Point(12, 99); this.AssistantComposerPanel.Name = "AssistantComposerPanel"; this.AssistantComposerPanel.Size = new System.Drawing.Size(294, 80); this.AssistantComposerPanel.TabIndex = 0; // // AssistantComposerLabel // this.AssistantComposerLabel.AutoSize = true; this.AssistantComposerLabel.Font = new System.Drawing.Font("Verdana", 9F); this.AssistantComposerLabel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(64)))), ((int)(((byte)(0))))); this.AssistantComposerLabel.Location = new System.Drawing.Point(82, 8); this.AssistantComposerLabel.Name = "AssistantComposerLabel"; this.AssistantComposerLabel.Size = new System.Drawing.Size(133, 14); this.AssistantComposerLabel.TabIndex = 0; this.AssistantComposerLabel.Text = "Assistant Composer"; // // KrystalsEditorPanel // this.KrystalsEditorPanel.BackColor = System.Drawing.Color.Honeydew; this.KrystalsEditorPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.KrystalsEditorPanel.Controls.Add(this.KrystalsEditorLabel); this.KrystalsEditorPanel.Controls.Add(this.KrystalsEditorButton); this.KrystalsEditorPanel.Location = new System.Drawing.Point(12, 185); this.KrystalsEditorPanel.Name = "KrystalsEditorPanel"; this.KrystalsEditorPanel.Size = new System.Drawing.Size(294, 80); this.KrystalsEditorPanel.TabIndex = 2; // // KrystalsEditorLabel // this.KrystalsEditorLabel.AutoSize = true; this.KrystalsEditorLabel.Font = new System.Drawing.Font("Verdana", 9F); this.KrystalsEditorLabel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(64)))), ((int)(((byte)(0))))); this.KrystalsEditorLabel.Location = new System.Drawing.Point(99, 8); this.KrystalsEditorLabel.Name = "KrystalsEditorLabel"; this.KrystalsEditorLabel.Size = new System.Drawing.Size(98, 14); this.KrystalsEditorLabel.TabIndex = 0; this.KrystalsEditorLabel.Text = "Krystals Editor"; // // panel1 // this.panel1.BackColor = System.Drawing.Color.Honeydew; this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panel1.Controls.Add(this.AboutButton); this.panel1.Controls.Add(this.label1); this.panel1.Controls.Add(this.PreferencesButton); this.panel1.Location = new System.Drawing.Point(12, 12); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(294, 80); this.panel1.TabIndex = 3; // // AboutButton // this.AboutButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(64)))), ((int)(((byte)(0))))); this.AboutButton.Location = new System.Drawing.Point(154, 30); this.AboutButton.Name = "AboutButton"; this.AboutButton.Size = new System.Drawing.Size(113, 31); this.AboutButton.TabIndex = 2; this.AboutButton.Text = "about Moritz"; this.AboutButton.UseVisualStyleBackColor = true; this.AboutButton.Click += new System.EventHandler(this.AboutButton_Click); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Verdana", 9F); this.label1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(64)))), ((int)(((byte)(0))))); this.label1.Location = new System.Drawing.Point(125, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(45, 14); this.label1.TabIndex = 0; this.label1.Text = "Moritz"; // // MoritzForm1 // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(255)))), ((int)(((byte)(245))))); this.ClientSize = new System.Drawing.Size(319, 328); this.ControlBox = false; this.Controls.Add(this.panel1); this.Controls.Add(this.KrystalsEditorPanel); this.Controls.Add(this.QuitButton); this.Controls.Add(this.AssistantComposerPanel); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.Name = "MoritzForm1"; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Moritz v3"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MoritzForm1_FormClosing); this.AssistantComposerPanel.ResumeLayout(false); this.AssistantComposerPanel.PerformLayout(); this.KrystalsEditorPanel.ResumeLayout(false); this.KrystalsEditorPanel.PerformLayout(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button QuitButton; private System.Windows.Forms.Button PreferencesButton; private System.Windows.Forms.Button LoadScoreSettingsButton; private System.Windows.Forms.Button KrystalsEditorButton; private System.Windows.Forms.Panel AssistantComposerPanel; private System.Windows.Forms.Label AssistantComposerLabel; private System.Windows.Forms.Panel KrystalsEditorPanel; private System.Windows.Forms.Label KrystalsEditorLabel; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Button AboutButton; private System.Windows.Forms.Label label1; } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// ConnectionPolicyTargetResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Voice.V1.ConnectionPolicy { public class ConnectionPolicyTargetResource : Resource { private static Request BuildCreateRequest(CreateConnectionPolicyTargetOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Voice, "/v1/ConnectionPolicies/" + options.PathConnectionPolicySid + "/Targets", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// create /// </summary> /// <param name="options"> Create ConnectionPolicyTarget parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ConnectionPolicyTarget </returns> public static ConnectionPolicyTargetResource Create(CreateConnectionPolicyTargetOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="options"> Create ConnectionPolicyTarget parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ConnectionPolicyTarget </returns> public static async System.Threading.Tasks.Task<ConnectionPolicyTargetResource> CreateAsync(CreateConnectionPolicyTargetOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// create /// </summary> /// <param name="pathConnectionPolicySid"> The SID of the Connection Policy that owns the Target </param> /// <param name="target"> The SIP address you want Twilio to route your calls to </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="priority"> The relative importance of the target </param> /// <param name="weight"> The value that determines the relative load the Target should receive compared to others with /// the same priority </param> /// <param name="enabled"> Whether the Target is enabled </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ConnectionPolicyTarget </returns> public static ConnectionPolicyTargetResource Create(string pathConnectionPolicySid, Uri target, string friendlyName = null, int? priority = null, int? weight = null, bool? enabled = null, ITwilioRestClient client = null) { var options = new CreateConnectionPolicyTargetOptions(pathConnectionPolicySid, target){FriendlyName = friendlyName, Priority = priority, Weight = weight, Enabled = enabled}; return Create(options, client); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="pathConnectionPolicySid"> The SID of the Connection Policy that owns the Target </param> /// <param name="target"> The SIP address you want Twilio to route your calls to </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="priority"> The relative importance of the target </param> /// <param name="weight"> The value that determines the relative load the Target should receive compared to others with /// the same priority </param> /// <param name="enabled"> Whether the Target is enabled </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ConnectionPolicyTarget </returns> public static async System.Threading.Tasks.Task<ConnectionPolicyTargetResource> CreateAsync(string pathConnectionPolicySid, Uri target, string friendlyName = null, int? priority = null, int? weight = null, bool? enabled = null, ITwilioRestClient client = null) { var options = new CreateConnectionPolicyTargetOptions(pathConnectionPolicySid, target){FriendlyName = friendlyName, Priority = priority, Weight = weight, Enabled = enabled}; return await CreateAsync(options, client); } #endif private static Request BuildFetchRequest(FetchConnectionPolicyTargetOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Voice, "/v1/ConnectionPolicies/" + options.PathConnectionPolicySid + "/Targets/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch ConnectionPolicyTarget parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ConnectionPolicyTarget </returns> public static ConnectionPolicyTargetResource Fetch(FetchConnectionPolicyTargetOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch ConnectionPolicyTarget parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ConnectionPolicyTarget </returns> public static async System.Threading.Tasks.Task<ConnectionPolicyTargetResource> FetchAsync(FetchConnectionPolicyTargetOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathConnectionPolicySid"> The SID of the Connection Policy that owns the Target </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ConnectionPolicyTarget </returns> public static ConnectionPolicyTargetResource Fetch(string pathConnectionPolicySid, string pathSid, ITwilioRestClient client = null) { var options = new FetchConnectionPolicyTargetOptions(pathConnectionPolicySid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathConnectionPolicySid"> The SID of the Connection Policy that owns the Target </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ConnectionPolicyTarget </returns> public static async System.Threading.Tasks.Task<ConnectionPolicyTargetResource> FetchAsync(string pathConnectionPolicySid, string pathSid, ITwilioRestClient client = null) { var options = new FetchConnectionPolicyTargetOptions(pathConnectionPolicySid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildReadRequest(ReadConnectionPolicyTargetOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Voice, "/v1/ConnectionPolicies/" + options.PathConnectionPolicySid + "/Targets", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read ConnectionPolicyTarget parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ConnectionPolicyTarget </returns> public static ResourceSet<ConnectionPolicyTargetResource> Read(ReadConnectionPolicyTargetOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<ConnectionPolicyTargetResource>.FromJson("targets", response.Content); return new ResourceSet<ConnectionPolicyTargetResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read ConnectionPolicyTarget parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ConnectionPolicyTarget </returns> public static async System.Threading.Tasks.Task<ResourceSet<ConnectionPolicyTargetResource>> ReadAsync(ReadConnectionPolicyTargetOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<ConnectionPolicyTargetResource>.FromJson("targets", response.Content); return new ResourceSet<ConnectionPolicyTargetResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pathConnectionPolicySid"> The SID of the Connection Policy from which to read the Targets </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ConnectionPolicyTarget </returns> public static ResourceSet<ConnectionPolicyTargetResource> Read(string pathConnectionPolicySid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadConnectionPolicyTargetOptions(pathConnectionPolicySid){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pathConnectionPolicySid"> The SID of the Connection Policy from which to read the Targets </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ConnectionPolicyTarget </returns> public static async System.Threading.Tasks.Task<ResourceSet<ConnectionPolicyTargetResource>> ReadAsync(string pathConnectionPolicySid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadConnectionPolicyTargetOptions(pathConnectionPolicySid){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<ConnectionPolicyTargetResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<ConnectionPolicyTargetResource>.FromJson("targets", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<ConnectionPolicyTargetResource> NextPage(Page<ConnectionPolicyTargetResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Voice) ); var response = client.Request(request); return Page<ConnectionPolicyTargetResource>.FromJson("targets", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<ConnectionPolicyTargetResource> PreviousPage(Page<ConnectionPolicyTargetResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Voice) ); var response = client.Request(request); return Page<ConnectionPolicyTargetResource>.FromJson("targets", response.Content); } private static Request BuildUpdateRequest(UpdateConnectionPolicyTargetOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Voice, "/v1/ConnectionPolicies/" + options.PathConnectionPolicySid + "/Targets/" + options.PathSid + "", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// update /// </summary> /// <param name="options"> Update ConnectionPolicyTarget parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ConnectionPolicyTarget </returns> public static ConnectionPolicyTargetResource Update(UpdateConnectionPolicyTargetOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="options"> Update ConnectionPolicyTarget parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ConnectionPolicyTarget </returns> public static async System.Threading.Tasks.Task<ConnectionPolicyTargetResource> UpdateAsync(UpdateConnectionPolicyTargetOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// update /// </summary> /// <param name="pathConnectionPolicySid"> The SID of the Connection Policy that owns the Target </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="target"> The SIP address you want Twilio to route your calls to </param> /// <param name="priority"> The relative importance of the target </param> /// <param name="weight"> The value that determines the relative load the Target should receive compared to others with /// the same priority </param> /// <param name="enabled"> Whether the Target is enabled </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ConnectionPolicyTarget </returns> public static ConnectionPolicyTargetResource Update(string pathConnectionPolicySid, string pathSid, string friendlyName = null, Uri target = null, int? priority = null, int? weight = null, bool? enabled = null, ITwilioRestClient client = null) { var options = new UpdateConnectionPolicyTargetOptions(pathConnectionPolicySid, pathSid){FriendlyName = friendlyName, Target = target, Priority = priority, Weight = weight, Enabled = enabled}; return Update(options, client); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="pathConnectionPolicySid"> The SID of the Connection Policy that owns the Target </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="target"> The SIP address you want Twilio to route your calls to </param> /// <param name="priority"> The relative importance of the target </param> /// <param name="weight"> The value that determines the relative load the Target should receive compared to others with /// the same priority </param> /// <param name="enabled"> Whether the Target is enabled </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ConnectionPolicyTarget </returns> public static async System.Threading.Tasks.Task<ConnectionPolicyTargetResource> UpdateAsync(string pathConnectionPolicySid, string pathSid, string friendlyName = null, Uri target = null, int? priority = null, int? weight = null, bool? enabled = null, ITwilioRestClient client = null) { var options = new UpdateConnectionPolicyTargetOptions(pathConnectionPolicySid, pathSid){FriendlyName = friendlyName, Target = target, Priority = priority, Weight = weight, Enabled = enabled}; return await UpdateAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteConnectionPolicyTargetOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Voice, "/v1/ConnectionPolicies/" + options.PathConnectionPolicySid + "/Targets/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// delete /// </summary> /// <param name="options"> Delete ConnectionPolicyTarget parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ConnectionPolicyTarget </returns> public static bool Delete(DeleteConnectionPolicyTargetOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="options"> Delete ConnectionPolicyTarget parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ConnectionPolicyTarget </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteConnectionPolicyTargetOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// delete /// </summary> /// <param name="pathConnectionPolicySid"> The SID of the Connection Policy that owns the Target </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ConnectionPolicyTarget </returns> public static bool Delete(string pathConnectionPolicySid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteConnectionPolicyTargetOptions(pathConnectionPolicySid, pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="pathConnectionPolicySid"> The SID of the Connection Policy that owns the Target </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ConnectionPolicyTarget </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathConnectionPolicySid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteConnectionPolicyTargetOptions(pathConnectionPolicySid, pathSid); return await DeleteAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a ConnectionPolicyTargetResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> ConnectionPolicyTargetResource object represented by the provided JSON </returns> public static ConnectionPolicyTargetResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<ConnectionPolicyTargetResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The SID of the Connection Policy that owns the Target /// </summary> [JsonProperty("connection_policy_sid")] public string ConnectionPolicySid { get; private set; } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The string that you assigned to describe the resource /// </summary> [JsonProperty("friendly_name")] public string FriendlyName { get; private set; } /// <summary> /// The SIP address you want Twilio to route your calls to /// </summary> [JsonProperty("target")] public Uri Target { get; private set; } /// <summary> /// The relative importance of the target /// </summary> [JsonProperty("priority")] public int? Priority { get; private set; } /// <summary> /// The value that determines the relative load the Target should receive compared to others with the same priority /// </summary> [JsonProperty("weight")] public int? Weight { get; private set; } /// <summary> /// Whether the target is enabled /// </summary> [JsonProperty("enabled")] public bool? Enabled { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT when the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The absolute URL of the resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } private ConnectionPolicyTargetResource() { } } }
#region Copyright & License // // Copyright 2001-2005 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections; namespace log4net.Core { /// <summary> /// A strongly-typed collection of <see cref="Level"/> objects. /// </summary> /// <author>Nicko Cadell</author> public class LevelCollection : ICollection, IList, IEnumerable, ICloneable { #region Interfaces /// <summary> /// Supports type-safe iteration over a <see cref="LevelCollection"/>. /// </summary> public interface ILevelCollectionEnumerator { /// <summary> /// Gets the current element in the collection. /// </summary> Level Current { get; } /// <summary> /// Advances the enumerator to the next element in the collection. /// </summary> /// <returns> /// <c>true</c> if the enumerator was successfully advanced to the next element; /// <c>false</c> if the enumerator has passed the end of the collection. /// </returns> /// <exception cref="InvalidOperationException"> /// The collection was modified after the enumerator was created. /// </exception> bool MoveNext(); /// <summary> /// Sets the enumerator to its initial position, before the first element in the collection. /// </summary> void Reset(); } #endregion private const int DEFAULT_CAPACITY = 16; #region Implementation (data) private Level[] m_array; private int m_count = 0; private int m_version = 0; #endregion #region Static Wrappers /// <summary> /// Creates a read-only wrapper for a <c>LevelCollection</c> instance. /// </summary> /// <param name="list">list to create a readonly wrapper arround</param> /// <returns> /// A <c>LevelCollection</c> wrapper that is read-only. /// </returns> public static LevelCollection ReadOnly(LevelCollection list) { if(list==null) throw new ArgumentNullException("list"); return new ReadOnlyLevelCollection(list); } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <c>LevelCollection</c> class /// that is empty and has the default initial capacity. /// </summary> public LevelCollection() { m_array = new Level[DEFAULT_CAPACITY]; } /// <summary> /// Initializes a new instance of the <c>LevelCollection</c> class /// that has the specified initial capacity. /// </summary> /// <param name="capacity"> /// The number of elements that the new <c>LevelCollection</c> is initially capable of storing. /// </param> public LevelCollection(int capacity) { m_array = new Level[capacity]; } /// <summary> /// Initializes a new instance of the <c>LevelCollection</c> class /// that contains elements copied from the specified <c>LevelCollection</c>. /// </summary> /// <param name="c">The <c>LevelCollection</c> whose elements are copied to the new collection.</param> public LevelCollection(LevelCollection c) { m_array = new Level[c.Count]; AddRange(c); } /// <summary> /// Initializes a new instance of the <c>LevelCollection</c> class /// that contains elements copied from the specified <see cref="Level"/> array. /// </summary> /// <param name="a">The <see cref="Level"/> array whose elements are copied to the new list.</param> public LevelCollection(Level[] a) { m_array = new Level[a.Length]; AddRange(a); } /// <summary> /// Initializes a new instance of the <c>LevelCollection</c> class /// that contains elements copied from the specified <see cref="Level"/> collection. /// </summary> /// <param name="col">The <see cref="Level"/> collection whose elements are copied to the new list.</param> public LevelCollection(ICollection col) { m_array = new Level[col.Count]; AddRange(col); } /// <summary> /// Type visible only to our subclasses /// Used to access protected constructor /// </summary> protected internal enum Tag { /// <summary> /// A value /// </summary> Default } /// <summary> /// Allow subclasses to avoid our default constructors /// </summary> /// <param name="tag"></param> protected internal LevelCollection(Tag tag) { m_array = null; } #endregion #region Operations (type-safe ICollection) /// <summary> /// Gets the number of elements actually contained in the <c>LevelCollection</c>. /// </summary> public virtual int Count { get { return m_count; } } /// <summary> /// Copies the entire <c>LevelCollection</c> to a one-dimensional /// <see cref="Level"/> array. /// </summary> /// <param name="array">The one-dimensional <see cref="Level"/> array to copy to.</param> public virtual void CopyTo(Level[] array) { this.CopyTo(array, 0); } /// <summary> /// Copies the entire <c>LevelCollection</c> to a one-dimensional /// <see cref="Level"/> array, starting at the specified index of the target array. /// </summary> /// <param name="array">The one-dimensional <see cref="Level"/> array to copy to.</param> /// <param name="start">The zero-based index in <paramref name="array"/> at which copying begins.</param> public virtual void CopyTo(Level[] array, int start) { if (m_count > array.GetUpperBound(0) + 1 - start) { throw new System.ArgumentException("Destination array was not long enough."); } Array.Copy(m_array, 0, array, start, m_count); } /// <summary> /// Gets a value indicating whether access to the collection is synchronized (thread-safe). /// </summary> /// <value>true if access to the ICollection is synchronized (thread-safe); otherwise, false.</value> public virtual bool IsSynchronized { get { return m_array.IsSynchronized; } } /// <summary> /// Gets an object that can be used to synchronize access to the collection. /// </summary> public virtual object SyncRoot { get { return m_array.SyncRoot; } } #endregion #region Operations (type-safe IList) /// <summary> /// Gets or sets the <see cref="Level"/> at the specified index. /// </summary> /// <param name="index">The zero-based index of the element to get or set.</param> /// <exception cref="ArgumentOutOfRangeException"> /// <para><paramref name="index"/> is less than zero</para> /// <para>-or-</para> /// <para><paramref name="index"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para> /// </exception> public virtual Level this[int index] { get { ValidateIndex(index); // throws return m_array[index]; } set { ValidateIndex(index); // throws ++m_version; m_array[index] = value; } } /// <summary> /// Adds a <see cref="Level"/> to the end of the <c>LevelCollection</c>. /// </summary> /// <param name="item">The <see cref="Level"/> to be added to the end of the <c>LevelCollection</c>.</param> /// <returns>The index at which the value has been added.</returns> public virtual int Add(Level item) { if (m_count == m_array.Length) { EnsureCapacity(m_count + 1); } m_array[m_count] = item; m_version++; return m_count++; } /// <summary> /// Removes all elements from the <c>LevelCollection</c>. /// </summary> public virtual void Clear() { ++m_version; m_array = new Level[DEFAULT_CAPACITY]; m_count = 0; } /// <summary> /// Creates a shallow copy of the <see cref="LevelCollection"/>. /// </summary> /// <returns>A new <see cref="LevelCollection"/> with a shallow copy of the collection data.</returns> public virtual object Clone() { LevelCollection newCol = new LevelCollection(m_count); Array.Copy(m_array, 0, newCol.m_array, 0, m_count); newCol.m_count = m_count; newCol.m_version = m_version; return newCol; } /// <summary> /// Determines whether a given <see cref="Level"/> is in the <c>LevelCollection</c>. /// </summary> /// <param name="item">The <see cref="Level"/> to check for.</param> /// <returns><c>true</c> if <paramref name="item"/> is found in the <c>LevelCollection</c>; otherwise, <c>false</c>.</returns> public virtual bool Contains(Level item) { for (int i=0; i != m_count; ++i) { if (m_array[i].Equals(item)) { return true; } } return false; } /// <summary> /// Returns the zero-based index of the first occurrence of a <see cref="Level"/> /// in the <c>LevelCollection</c>. /// </summary> /// <param name="item">The <see cref="Level"/> to locate in the <c>LevelCollection</c>.</param> /// <returns> /// The zero-based index of the first occurrence of <paramref name="item"/> /// in the entire <c>LevelCollection</c>, if found; otherwise, -1. /// </returns> public virtual int IndexOf(Level item) { for (int i=0; i != m_count; ++i) { if (m_array[i].Equals(item)) { return i; } } return -1; } /// <summary> /// Inserts an element into the <c>LevelCollection</c> at the specified index. /// </summary> /// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param> /// <param name="item">The <see cref="Level"/> to insert.</param> /// <exception cref="ArgumentOutOfRangeException"> /// <para><paramref name="index"/> is less than zero</para> /// <para>-or-</para> /// <para><paramref name="index"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para> /// </exception> public virtual void Insert(int index, Level item) { ValidateIndex(index, true); // throws if (m_count == m_array.Length) { EnsureCapacity(m_count + 1); } if (index < m_count) { Array.Copy(m_array, index, m_array, index + 1, m_count - index); } m_array[index] = item; m_count++; m_version++; } /// <summary> /// Removes the first occurrence of a specific <see cref="Level"/> from the <c>LevelCollection</c>. /// </summary> /// <param name="item">The <see cref="Level"/> to remove from the <c>LevelCollection</c>.</param> /// <exception cref="ArgumentException"> /// The specified <see cref="Level"/> was not found in the <c>LevelCollection</c>. /// </exception> public virtual void Remove(Level item) { int i = IndexOf(item); if (i < 0) { throw new System.ArgumentException("Cannot remove the specified item because it was not found in the specified Collection."); } ++m_version; RemoveAt(i); } /// <summary> /// Removes the element at the specified index of the <c>LevelCollection</c>. /// </summary> /// <param name="index">The zero-based index of the element to remove.</param> /// <exception cref="ArgumentOutOfRangeException"> /// <para><paramref name="index"/> is less than zero</para> /// <para>-or-</para> /// <para><paramref name="index"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para> /// </exception> public virtual void RemoveAt(int index) { ValidateIndex(index); // throws m_count--; if (index < m_count) { Array.Copy(m_array, index + 1, m_array, index, m_count - index); } // We can't set the deleted entry equal to null, because it might be a value type. // Instead, we'll create an empty single-element array of the right type and copy it // over the entry we want to erase. Level[] temp = new Level[1]; Array.Copy(temp, 0, m_array, m_count, 1); m_version++; } /// <summary> /// Gets a value indicating whether the collection has a fixed size. /// </summary> /// <value>true if the collection has a fixed size; otherwise, false. The default is false</value> public virtual bool IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether the IList is read-only. /// </summary> /// <value>true if the collection is read-only; otherwise, false. The default is false</value> public virtual bool IsReadOnly { get { return false; } } #endregion #region Operations (type-safe IEnumerable) /// <summary> /// Returns an enumerator that can iterate through the <c>LevelCollection</c>. /// </summary> /// <returns>An <see cref="Enumerator"/> for the entire <c>LevelCollection</c>.</returns> public virtual ILevelCollectionEnumerator GetEnumerator() { return new Enumerator(this); } #endregion #region Public helpers (just to mimic some nice features of ArrayList) /// <summary> /// Gets or sets the number of elements the <c>LevelCollection</c> can contain. /// </summary> public virtual int Capacity { get { return m_array.Length; } set { if (value < m_count) { value = m_count; } if (value != m_array.Length) { if (value > 0) { Level[] temp = new Level[value]; Array.Copy(m_array, 0, temp, 0, m_count); m_array = temp; } else { m_array = new Level[DEFAULT_CAPACITY]; } } } } /// <summary> /// Adds the elements of another <c>LevelCollection</c> to the current <c>LevelCollection</c>. /// </summary> /// <param name="x">The <c>LevelCollection</c> whose elements should be added to the end of the current <c>LevelCollection</c>.</param> /// <returns>The new <see cref="LevelCollection.Count"/> of the <c>LevelCollection</c>.</returns> public virtual int AddRange(LevelCollection x) { if (m_count + x.Count >= m_array.Length) { EnsureCapacity(m_count + x.Count); } Array.Copy(x.m_array, 0, m_array, m_count, x.Count); m_count += x.Count; m_version++; return m_count; } /// <summary> /// Adds the elements of a <see cref="Level"/> array to the current <c>LevelCollection</c>. /// </summary> /// <param name="x">The <see cref="Level"/> array whose elements should be added to the end of the <c>LevelCollection</c>.</param> /// <returns>The new <see cref="LevelCollection.Count"/> of the <c>LevelCollection</c>.</returns> public virtual int AddRange(Level[] x) { if (m_count + x.Length >= m_array.Length) { EnsureCapacity(m_count + x.Length); } Array.Copy(x, 0, m_array, m_count, x.Length); m_count += x.Length; m_version++; return m_count; } /// <summary> /// Adds the elements of a <see cref="Level"/> collection to the current <c>LevelCollection</c>. /// </summary> /// <param name="col">The <see cref="Level"/> collection whose elements should be added to the end of the <c>LevelCollection</c>.</param> /// <returns>The new <see cref="LevelCollection.Count"/> of the <c>LevelCollection</c>.</returns> public virtual int AddRange(ICollection col) { if (m_count + col.Count >= m_array.Length) { EnsureCapacity(m_count + col.Count); } foreach(object item in col) { Add((Level)item); } return m_count; } /// <summary> /// Sets the capacity to the actual number of elements. /// </summary> public virtual void TrimToSize() { this.Capacity = m_count; } #endregion #region Implementation (helpers) /// <exception cref="ArgumentOutOfRangeException"> /// <para><paramref name="index"/> is less than zero</para> /// <para>-or-</para> /// <para><paramref name="index"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para> /// </exception> private void ValidateIndex(int i) { ValidateIndex(i, false); } /// <exception cref="ArgumentOutOfRangeException"> /// <para><paramref name="index"/> is less than zero</para> /// <para>-or-</para> /// <para><paramref name="index"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para> /// </exception> private void ValidateIndex(int i, bool allowEqualEnd) { int max = (allowEqualEnd) ? (m_count) : (m_count-1); if (i < 0 || i > max) { throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("i", (object)i, "Index was out of range. Must be non-negative and less than the size of the collection. [" + (object)i + "] Specified argument was out of the range of valid values."); } } private void EnsureCapacity(int min) { int newCapacity = ((m_array.Length == 0) ? DEFAULT_CAPACITY : m_array.Length * 2); if (newCapacity < min) { newCapacity = min; } this.Capacity = newCapacity; } #endregion #region Implementation (ICollection) void ICollection.CopyTo(Array array, int start) { Array.Copy(m_array, 0, array, start, m_count); } #endregion #region Implementation (IList) object IList.this[int i] { get { return (object)this[i]; } set { this[i] = (Level)value; } } int IList.Add(object x) { return this.Add((Level)x); } bool IList.Contains(object x) { return this.Contains((Level)x); } int IList.IndexOf(object x) { return this.IndexOf((Level)x); } void IList.Insert(int pos, object x) { this.Insert(pos, (Level)x); } void IList.Remove(object x) { this.Remove((Level)x); } void IList.RemoveAt(int pos) { this.RemoveAt(pos); } #endregion #region Implementation (IEnumerable) IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)(this.GetEnumerator()); } #endregion #region Nested enumerator class /// <summary> /// Supports simple iteration over a <see cref="LevelCollection"/>. /// </summary> private sealed class Enumerator : IEnumerator, ILevelCollectionEnumerator { #region Implementation (data) private readonly LevelCollection m_collection; private int m_index; private int m_version; #endregion #region Construction /// <summary> /// Initializes a new instance of the <c>Enumerator</c> class. /// </summary> /// <param name="tc"></param> internal Enumerator(LevelCollection tc) { m_collection = tc; m_index = -1; m_version = tc.m_version; } #endregion #region Operations (type-safe IEnumerator) /// <summary> /// Gets the current element in the collection. /// </summary> public Level Current { get { return m_collection[m_index]; } } /// <summary> /// Advances the enumerator to the next element in the collection. /// </summary> /// <returns> /// <c>true</c> if the enumerator was successfully advanced to the next element; /// <c>false</c> if the enumerator has passed the end of the collection. /// </returns> /// <exception cref="InvalidOperationException"> /// The collection was modified after the enumerator was created. /// </exception> public bool MoveNext() { if (m_version != m_collection.m_version) { throw new System.InvalidOperationException("Collection was modified; enumeration operation may not execute."); } ++m_index; return (m_index < m_collection.Count); } /// <summary> /// Sets the enumerator to its initial position, before the first element in the collection. /// </summary> public void Reset() { m_index = -1; } #endregion #region Implementation (IEnumerator) object IEnumerator.Current { get { return this.Current; } } #endregion } #endregion #region Nested Read Only Wrapper class private sealed class ReadOnlyLevelCollection : LevelCollection { #region Implementation (data) private readonly LevelCollection m_collection; #endregion #region Construction internal ReadOnlyLevelCollection(LevelCollection list) : base(Tag.Default) { m_collection = list; } #endregion #region Type-safe ICollection public override void CopyTo(Level[] array) { m_collection.CopyTo(array); } public override void CopyTo(Level[] array, int start) { m_collection.CopyTo(array,start); } public override int Count { get { return m_collection.Count; } } public override bool IsSynchronized { get { return m_collection.IsSynchronized; } } public override object SyncRoot { get { return this.m_collection.SyncRoot; } } #endregion #region Type-safe IList public override Level this[int i] { get { return m_collection[i]; } set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } } public override int Add(Level x) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override void Clear() { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override bool Contains(Level x) { return m_collection.Contains(x); } public override int IndexOf(Level x) { return m_collection.IndexOf(x); } public override void Insert(int pos, Level x) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override void Remove(Level x) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override void RemoveAt(int pos) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override bool IsFixedSize { get { return true; } } public override bool IsReadOnly { get { return true; } } #endregion #region Type-safe IEnumerable public override ILevelCollectionEnumerator GetEnumerator() { return m_collection.GetEnumerator(); } #endregion #region Public Helpers // (just to mimic some nice features of ArrayList) public override int Capacity { get { return m_collection.Capacity; } set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } } public override int AddRange(LevelCollection x) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override int AddRange(Level[] x) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } #endregion } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using Trionic5Tools; namespace Trionic5Controls { public partial class frmEasyFirmwareSettings : DevExpress.XtraEditors.XtraForm { public frmEasyFirmwareSettings() { InitializeComponent(); } public string CarModel { get { return txtCarModel.Text; } set { txtCarModel.Text = value; txtCarModel.Properties.MaxLength = txtCarModel.Text.Length; } } public string EngineType { get { return txtEngineType.Text; } set { txtEngineType.Text = value; txtEngineType.Properties.MaxLength = txtEngineType.Text.Length; } } public string PartNumber { get { return txtPartnumber.Text; } set { txtPartnumber.Text = value; txtPartnumber.Properties.MaxLength = txtPartnumber.Text.Length; } } public string SoftwareID { get { return txtSoftwareID.Text; } set { txtSoftwareID.Text = value; txtSoftwareID.Properties.MaxLength = txtSoftwareID.Text.Length; } } public string Dataname { get { return txtDataName.Text; } set { txtDataName.Text = value; txtDataName.Properties.MaxLength = txtDataName.Text.Length; } } public string VSSCode { get { return txtVSSCode.Text; } set { txtVSSCode.Text = value; txtVSSCode.Properties.MaxLength = txtVSSCode.Text.Length; } } public bool VSSEnabled { get { return chkVSSCode.Checked; } set { chkVSSCode.Checked = value; } } public bool TankPressureDiagnosticsEnabled { get { return chkTankPressureDiagnostics.Checked; } set { chkTankPressureDiagnostics.Checked = value; } } public bool SecondO2Enabled { get { return chkEnableSecondLambdaSensor.Checked; } set { chkEnableSecondLambdaSensor.Checked = value; } } public bool RAMLocked { get { return chkRAMLocked.Checked; } set { chkRAMLocked.Checked = value; } } public bool AutoGearBox { get { return chkAutomaticTransmission.Checked; } set { chkAutomaticTransmission.Checked = value; } } public bool HeatplatesPresent { get { return chkHeatPlates.Checked; } set { chkHeatPlates.Checked = value; } } public bool AfterstartEnrichment { get { return chkEnrichmentAfterStart.Checked; } set { chkEnrichmentAfterStart.Checked = value; } } public bool WOTEnrichment { get { return chkWOTEnrichment.Checked; } set { chkWOTEnrichment.Checked = value; } } /*public bool InterpolationOfDelay { get { return checkEdit5.Checked; } set { checkEdit5.Checked = value; } }*/ public bool TemperatureCompensation { get { return chkTemperatureCompensation.Checked; } set { chkTemperatureCompensation.Checked = value; } } public bool LambdaControl { get { return chkLambdaControl.Checked; } set { chkLambdaControl.Checked = value; } } public bool Adaptivity { get { return chkAdaptivity.Checked; } set { chkAdaptivity.Checked = value; } } public bool IdleControl { get { return chkIdleControl.Checked; } set { chkIdleControl.Checked = value; } } public bool EnrichmentDuringStart { get { return chkEnrichmentDuringStart.Checked; } set { chkEnrichmentDuringStart.Checked = value; } } public bool LambdaDuringTransitions { get { return chkLambdaControlOnTransients.Checked; } set { chkLambdaControlOnTransients.Checked = value; } } public bool Fuelcut { get { return chkFuelcutEngineBrake.Checked; } set { chkFuelcutEngineBrake.Checked = value; } } public bool AccelEnrichment { get { return chkAccelerationEnrichment.Checked; } set { chkAccelerationEnrichment.Checked = value; } } public bool AirpumpControl { get { return chkAirpumpControl.Checked; } set { chkAirpumpControl.Checked = value; } } public bool DecelEnleanment { get { return chkDecelerationEnleanment.Checked; } set { chkDecelerationEnleanment.Checked = value; } } public bool AdaptionWithClosedThrottle { get { return chkAdaptivityWithClosedThrottle.Checked; } set { chkAdaptivityWithClosedThrottle.Checked = value; } } public bool FactorToLambdaWhenThrottleOpening { get { return chkLambdaCorrectionOnTPSOpening.Checked; } set { chkLambdaCorrectionOnTPSOpening.Checked = value; } } public bool SeperateInjectionMapForIdle { get { return chkUseIdleInjectionMap.Checked; } set { chkUseIdleInjectionMap.Checked = value; } } public bool FactorToLambdaWhenACEngaged { get { return chkLambdaCorrectionOnACEngage.Checked; } set { chkLambdaCorrectionOnACEngage.Checked = value; } } /*public bool ThrottleAccRetAdjustSimult { get { return checkEdit17.Checked; } set { checkEdit17.Checked = value; } }*/ public bool FuelAdjustDuringIdle { get { return chkFuelAdjustDuringIdle.Checked; } set { chkFuelAdjustDuringIdle.Checked = value; } } public bool PurgeControl { get { return chkPurgeControl.Checked; } set { chkPurgeControl.Checked = value; } } public bool AdaptionOfIdleControl { get { return chkAdaptionOfIdleControl.Checked; } set { chkAdaptionOfIdleControl.Checked = value; } } public bool LambdaControlDuringIdle { get { return chkLambdaControlDuringIdle.Checked; } set { chkLambdaControlDuringIdle.Checked = value; } } public bool Tempcompwithactivelambdacontrol { get { return chkTemperatureCorrectionInClosedLoop.Checked; } set { chkTemperatureCorrectionInClosedLoop.Checked = value; } } public bool NoFuelCutR12 { get { return chkNoFuelcutR12.Checked; } set { chkNoFuelcutR12.Checked = value; } } public bool GlobalAdaption { get { return chkGlobalAdaption.Checked; } set { chkGlobalAdaption.Checked = value; } } public bool HigherIdleDuringStart { get { return chkHigherIdleOnStart.Checked; } set { chkHigherIdleOnStart.Checked = value; } } public bool APCControl { get { return chkBoostControl.Checked; } set { chkBoostControl.Checked = value; } } public bool ETS { get { return chkETS.Checked; } set { chkETS.Checked = value; } } public bool LoadControl { get { return chkLoadControl.Checked; } set { chkLoadControl.Checked = value; } } public bool LoadBufferDuringIdle { get { return chkLoadBufferOnIdle.Checked; } set { chkLoadBufferOnIdle.Checked = value; } } public bool ConstantInjectionTime { get { return chkConstantInjectionE51.Checked; } set { chkConstantInjectionE51.Checked = value; } } public bool ConstantInjectionTimeDuringIdle { get { return chkConstantInjectionOnIdle.Checked; } set { chkConstantInjectionOnIdle.Checked = value; } } public bool PurgeValveMY94 { get { return chkPurgeValveMY94.Checked; } set { chkPurgeValveMY94.Checked = value; } } /*public bool ConstantAngle { get { return chkIdleIgnitionGear12.Checked; } set { chkIdleIgnitionGear12.Checked = value; } }*/ public bool KnockRegulatingDisabled { get { return chkKnockDetectionOff.Checked; } set { chkKnockDetectionOff.Checked = value; } } public bool NormalAsperatedEngine { get { return chkNormallyAspirated.Checked; } set { chkNormallyAspirated.Checked = value; } } public bool ConstIdleIgnAngleDuringFirstAndSecondGear { get { return chkIdleIgnitionGear12.Checked; } set { chkIdleIgnitionGear12.Checked = value; } } public void DisableVSSOptions() { chkVSSCode.Enabled = false; txtVSSCode.Enabled = false; } public void DisableAdvancedControls() { chkLoadBufferOnIdle.Enabled = false; chkIdleIgnitionGear12.Enabled = false; chkNoFuelcutR12.Enabled = false; chkAirpumpControl.Enabled = false; chkNormallyAspirated.Enabled = false; chkKnockDetectionOff.Enabled = false; chkPurgeValveMY94.Enabled = false; /* Loadbufferduringidle, // byte 4, bit 1 Constidleignangleduringgearoneandtwo,// byte 4, bit 2 NofuelcutR12, // byte 4, bit 3 Airpumpcontrol, // byte 4, bit 4 Normalasperatedengine, // byte 4, bit 5 Knockregulatingdisabled, // byte 4, bit 6 Constantangle, // byte 4, bit 7 PurgevalveMY94 // byte 4, bit 8 * */ } public bool IsTrionic55 { get { return chkTrionic55.Checked; } set { chkTrionic55.Checked = value; if (!chkTrionic55.Checked) { chkEnableSecondLambdaSensor.Enabled = false; chkEnableSecondLambdaSensor.Checked = false; } } } public InjectorType Injectors { get { return (InjectorType)cbxInjectors.SelectedIndex; } set { cbxInjectors.SelectedIndex = (int)value; } } public TurboType Turbo { get { return (TurboType)cbxTurbo.SelectedIndex; } set { cbxTurbo.SelectedIndex = (int)value; } } public MapSensorType MapSensor { get { return (MapSensorType)cbxMapsensor.SelectedIndex; } set { cbxMapsensor.SelectedIndex = (int)value; } } public TuningStage TuningStage { get { return (TuningStage)cbxTuningStage.SelectedIndex; } set { cbxTuningStage.SelectedIndex = (int)value; } } public DateTime SynchDateTime { set { txtSyncTimestamp.Text = value.ToString("dd/MM/yyyy HH:mm:ss"); } } public string CPUFrequency { get { return txtCPUSpeed.Text; } set { txtCPUSpeed.Text = value; } } private bool m_compare_file = false; public bool Compare_file { get { return m_compare_file; } set { m_compare_file = value; } } private bool m_open_file = false; private string m_filetoOpen = string.Empty; public string FiletoOpen { get { return m_filetoOpen; } set { m_filetoOpen = value; } } public bool Open_file { get { return m_open_file; } set { m_open_file = value; } } private void txtPartnumber_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e) { frmPartnumberLookup partnumberlookup = new frmPartnumberLookup(); partnumberlookup.LookUpPartnumber(txtPartnumber.Text); partnumberlookup.ShowDialog(); if (partnumberlookup.Open_File) { m_filetoOpen = partnumberlookup.GetFileToOpen(); m_open_file = true; this.DialogResult = DialogResult.Abort; this.Close(); } else if (partnumberlookup.Compare_File) { m_filetoOpen = partnumberlookup.GetFileToOpen(); m_compare_file = true; this.DialogResult = DialogResult.Abort; this.Close(); } } private void simpleButton1_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; this.Close(); } private void simpleButton2_Click(object sender, EventArgs e) { } private void chkRAMLocked_CheckedChanged(object sender, EventArgs e) { UpdateRamLockedColor(); } private void UpdateRamLockedColor() { if (chkRAMLocked.Checked) chkRAMLocked.ForeColor = Color.Red; else chkRAMLocked.ForeColor = Color.Black; } private void frmEasyFirmwareSettings_Shown(object sender, EventArgs e) { UpdateRamLockedColor(); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Net; using System.Web; using ServiceStack.Common; using ServiceStack.MiniProfiler.UI; using ServiceStack.ServiceHost; using ServiceStack.Text; using ServiceStack.WebHost.Endpoints.Extensions; using ServiceStack.WebHost.Endpoints.Support; using HttpRequestWrapper = ServiceStack.WebHost.Endpoints.Extensions.HttpRequestWrapper; namespace ServiceStack.WebHost.Endpoints { public class ServiceStackHttpHandlerFactory : IHttpHandlerFactory { static readonly List<string> WebHostRootFileNames = new List<string>(); static private readonly string WebHostPhysicalPath = null; static private readonly string DefaultRootFileName = null; static private string ApplicationBaseUrl = null; static private readonly IHttpHandler DefaultHttpHandler = null; static private readonly RedirectHttpHandler NonRootModeDefaultHttpHandler = null; static private readonly IHttpHandler ForbiddenHttpHandler = null; static private readonly IHttpHandler NotFoundHttpHandler = null; static private readonly IHttpHandler StaticFileHandler = new StaticFileHandler(); private static readonly bool IsIntegratedPipeline = false; private static readonly bool ServeDefaultHandler = false; private static readonly bool AutoRedirectsDirs = false; private static Func<IHttpRequest, IHttpHandler>[] RawHttpHandlers; [ThreadStatic] public static string DebugLastHandlerArgs; static ServiceStackHttpHandlerFactory() { //MONO doesn't implement this property var pi = typeof(HttpRuntime).GetProperty("UsingIntegratedPipeline"); if (pi != null) { IsIntegratedPipeline = (bool)pi.GetGetMethod().Invoke(null, new object[0]); } var config = EndpointHost.Config; if (config == null) { throw new ConfigurationErrorsException( "ServiceStack: AppHost does not exist or has not been initialized. " + "Make sure you have created an AppHost and started it with 'new AppHost().Init();' in your Global.asax Application_Start()", new ArgumentNullException("EndpointHost.Config")); } var isAspNetHost = HttpListenerBase.Instance == null || HttpContext.Current != null; WebHostPhysicalPath = config.WebHostPhysicalPath; AutoRedirectsDirs = isAspNetHost && !Env.IsMono; //Apache+mod_mono treats path="servicestack*" as path="*" so takes over root path, so we need to serve matching resources var hostedAtRootPath = config.ServiceStackHandlerFactoryPath == null; //DefaultHttpHandler not supported in IntegratedPipeline mode if (!IsIntegratedPipeline && isAspNetHost && !hostedAtRootPath && !Env.IsMono) DefaultHttpHandler = new DefaultHttpHandler(); ServeDefaultHandler = hostedAtRootPath || Env.IsMono; if (ServeDefaultHandler) { foreach (var filePath in Directory.GetFiles(WebHostPhysicalPath)) { var fileNameLower = Path.GetFileName(filePath).ToLower(); if (DefaultRootFileName == null && config.DefaultDocuments.Contains(fileNameLower)) { //Can't serve Default.aspx pages when hostedAtRootPath so ignore and allow for next default document if (!(hostedAtRootPath && fileNameLower.EndsWith(".aspx"))) { DefaultRootFileName = fileNameLower; ((StaticFileHandler)StaticFileHandler).SetDefaultFile(filePath); if (DefaultHttpHandler == null) DefaultHttpHandler = new RedirectHttpHandler { RelativeUrl = DefaultRootFileName }; } } WebHostRootFileNames.Add(Path.GetFileName(fileNameLower)); } foreach (var dirName in Directory.GetDirectories(WebHostPhysicalPath)) { var dirNameLower = Path.GetFileName(dirName).ToLower(); WebHostRootFileNames.Add(Path.GetFileName(dirNameLower)); } } if (!string.IsNullOrEmpty(config.DefaultRedirectPath)) DefaultHttpHandler = new RedirectHttpHandler { RelativeUrl = config.DefaultRedirectPath }; if (DefaultHttpHandler == null && !string.IsNullOrEmpty(config.MetadataRedirectPath)) DefaultHttpHandler = new RedirectHttpHandler { RelativeUrl = config.MetadataRedirectPath }; if (!string.IsNullOrEmpty(config.MetadataRedirectPath)) NonRootModeDefaultHttpHandler = new RedirectHttpHandler { RelativeUrl = config.MetadataRedirectPath }; if (DefaultHttpHandler == null) DefaultHttpHandler = NotFoundHttpHandler; var defaultRedirectHanlder = DefaultHttpHandler as RedirectHttpHandler; var debugDefaultHandler = defaultRedirectHanlder != null ? defaultRedirectHanlder.RelativeUrl : typeof(DefaultHttpHandler).Name; SetApplicationBaseUrl(config.WebHostUrl); ForbiddenHttpHandler = config.GetCustomErrorHttpHandler(HttpStatusCode.Forbidden); if (ForbiddenHttpHandler == null) { ForbiddenHttpHandler = new ForbiddenHttpHandler { IsIntegratedPipeline = IsIntegratedPipeline, WebHostPhysicalPath = WebHostPhysicalPath, WebHostRootFileNames = WebHostRootFileNames, ApplicationBaseUrl = ApplicationBaseUrl, DefaultRootFileName = DefaultRootFileName, DefaultHandler = debugDefaultHandler, }; } NotFoundHttpHandler = config.GetCustomErrorHttpHandler(HttpStatusCode.NotFound); if (NotFoundHttpHandler == null) { NotFoundHttpHandler = new NotFoundHttpHandler { IsIntegratedPipeline = IsIntegratedPipeline, WebHostPhysicalPath = WebHostPhysicalPath, WebHostRootFileNames = WebHostRootFileNames, ApplicationBaseUrl = ApplicationBaseUrl, DefaultRootFileName = DefaultRootFileName, DefaultHandler = debugDefaultHandler, }; } var rawHandlers = config.RawHttpHandlers; rawHandlers.Add(ReturnRequestInfo); rawHandlers.Add(MiniProfilerHandler.MatchesRequest); RawHttpHandlers = rawHandlers.ToArray(); } // Entry point for ASP.NET public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated) { DebugLastHandlerArgs = requestType + "|" + url + "|" + pathTranslated; var httpReq = new HttpRequestWrapper(pathTranslated, context.Request); foreach (var rawHttpHandler in RawHttpHandlers) { var reqInfo = rawHttpHandler(httpReq); if (reqInfo != null) return reqInfo; } var mode = EndpointHost.Config.ServiceStackHandlerFactoryPath; var pathInfo = context.Request.GetPathInfo(); //WebDev Server auto requests '/default.aspx' so recorrect path to different default document if (mode == null && (url == "/default.aspx" || url == "/Default.aspx")) pathInfo = "/"; //Default Request / if (string.IsNullOrEmpty(pathInfo) || pathInfo == "/") { //Exception calling context.Request.Url on Apache+mod_mono if (ApplicationBaseUrl == null) { var absoluteUrl = Env.IsMono ? url.ToParentPath() : context.Request.GetApplicationUrl(); SetApplicationBaseUrl(absoluteUrl); } //e.g. CatchAllHandler to Process Markdown files var catchAllHandler = GetCatchAllHandlerIfAny(httpReq.HttpMethod, pathInfo, httpReq.GetPhysicalPath()); if (catchAllHandler != null) return catchAllHandler; return ServeDefaultHandler ? DefaultHttpHandler : NonRootModeDefaultHttpHandler; } if (mode != null && pathInfo.EndsWith(mode)) { var requestPath = context.Request.Path.ToLower(); if (requestPath == "/" + mode || requestPath == mode || requestPath == mode + "/") { if (context.Request.PhysicalPath != WebHostPhysicalPath || !File.Exists(Path.Combine(context.Request.PhysicalPath, DefaultRootFileName ?? ""))) { return new IndexPageHttpHandler(); } } var okToServe = ShouldAllow(context.Request.FilePath); return okToServe ? DefaultHttpHandler : ForbiddenHttpHandler; } return GetHandlerForPathInfo( context.Request.HttpMethod, pathInfo, context.Request.FilePath, pathTranslated) ?? NotFoundHttpHandler; } private static void SetApplicationBaseUrl(string absoluteUrl) { if (absoluteUrl == null) return; ApplicationBaseUrl = absoluteUrl; // var defaultRedirectUrl = DefaultHttpHandler as RedirectHttpHandler; // if (defaultRedirectUrl != null && defaultRedirectUrl.AbsoluteUrl == null) // defaultRedirectUrl.AbsoluteUrl = ApplicationBaseUrl.CombineWith( // defaultRedirectUrl.RelativeUrl); // // if (NonRootModeDefaultHttpHandler != null && NonRootModeDefaultHttpHandler.AbsoluteUrl == null) // NonRootModeDefaultHttpHandler.AbsoluteUrl = ApplicationBaseUrl.CombineWith( // NonRootModeDefaultHttpHandler.RelativeUrl); } public static string GetBaseUrl() { return EndpointHost.Config.WebHostUrl ?? ApplicationBaseUrl; } // Entry point for HttpListener public static IHttpHandler GetHandler(IHttpRequest httpReq) { foreach (var rawHttpHandler in RawHttpHandlers) { var reqInfo = rawHttpHandler(httpReq); if (reqInfo != null) return reqInfo; } var mode = EndpointHost.Config.ServiceStackHandlerFactoryPath; var pathInfo = httpReq.PathInfo; //Default Request / if (string.IsNullOrEmpty(pathInfo) || pathInfo == "/") { if (ApplicationBaseUrl == null) SetApplicationBaseUrl(httpReq.GetPathUrl()); //e.g. CatchAllHandler to Process Markdown files var catchAllHandler = GetCatchAllHandlerIfAny(httpReq.HttpMethod, pathInfo, httpReq.GetPhysicalPath()); if (catchAllHandler != null) return catchAllHandler; return ServeDefaultHandler ? DefaultHttpHandler : NonRootModeDefaultHttpHandler; } if (mode != null && pathInfo.EndsWith(mode)) { var requestPath = pathInfo; if (requestPath == "/" + mode || requestPath == mode || requestPath == mode + "/") { //TODO: write test for this if (httpReq.GetPhysicalPath() != WebHostPhysicalPath || !File.Exists(Path.Combine(httpReq.ApplicationFilePath, DefaultRootFileName ?? ""))) { return new IndexPageHttpHandler(); } } var okToServe = ShouldAllow(httpReq.GetPhysicalPath()); return okToServe ? DefaultHttpHandler : ForbiddenHttpHandler; } return GetHandlerForPathInfo(httpReq.HttpMethod, pathInfo, pathInfo, httpReq.GetPhysicalPath()) ?? NotFoundHttpHandler; } /// <summary> /// If enabled, just returns the Request Info as it understands /// </summary> /// <param name="context"></param> /// <returns></returns> private static IHttpHandler ReturnRequestInfo(HttpRequest httpReq) { if (EndpointHost.Config.DebugOnlyReturnRequestInfo || (EndpointHost.DebugMode && httpReq.PathInfo.EndsWith("__requestinfo"))) { var reqInfo = RequestInfoHandler.GetRequestInfo( new HttpRequestWrapper(typeof(RequestInfo).Name, httpReq)); reqInfo.Host = EndpointHost.Config.DebugAspNetHostEnvironment + "_v" + Env.ServiceStackVersion + "_" + EndpointHost.Config.ServiceName; //reqInfo.FactoryUrl = url; //Just RawUrl without QueryString //reqInfo.FactoryPathTranslated = pathTranslated; //Local path on filesystem reqInfo.PathInfo = httpReq.PathInfo; reqInfo.Path = httpReq.Path; reqInfo.ApplicationPath = httpReq.ApplicationPath; return new RequestInfoHandler { RequestInfo = reqInfo }; } return null; } private static IHttpHandler ReturnRequestInfo(IHttpRequest httpReq) { if (EndpointHost.Config.DebugOnlyReturnRequestInfo || (EndpointHost.DebugMode && httpReq.PathInfo.EndsWith("__requestinfo"))) { var reqInfo = RequestInfoHandler.GetRequestInfo(httpReq); reqInfo.Host = EndpointHost.Config.DebugHttpListenerHostEnvironment + "_v" + Env.ServiceStackVersion + "_" + EndpointHost.Config.ServiceName; reqInfo.PathInfo = httpReq.PathInfo; reqInfo.Path = httpReq.GetPathUrl(); return new RequestInfoHandler { RequestInfo = reqInfo }; } return null; } // no handler registered // serve the file from the filesystem, restricting to a safelist of extensions private static bool ShouldAllow(string filePath) { var fileExt = Path.GetExtension(filePath); if (string.IsNullOrEmpty(fileExt)) return false; return EndpointHost.Config.AllowFileExtensions.Contains(fileExt.Substring(1)); } public static IHttpHandler GetHandlerForPathInfo(string httpMethod, string pathInfo, string requestPath, string filePath) { var pathParts = pathInfo.TrimStart('/').Split('/'); if (pathParts.Length == 0) return NotFoundHttpHandler; string contentType; var restPath = RestHandler.FindMatchingRestPath(httpMethod, pathInfo, out contentType); if (restPath != null) return new RestHandler { RestPath = restPath, RequestName = restPath.RequestType.Name, ResponseContentType = contentType }; var existingFile = pathParts[0].ToLower(); if (WebHostRootFileNames.Contains(existingFile)) { var fileExt = Path.GetExtension(filePath); var isFileRequest = !string.IsNullOrEmpty(fileExt); if (!isFileRequest && !AutoRedirectsDirs) { //If pathInfo is for Directory try again with redirect including '/' suffix if (!pathInfo.EndsWith("/")) { var appFilePath = filePath.Substring(0, filePath.Length - requestPath.Length); var redirect = Support.StaticFileHandler.DirectoryExists(filePath, appFilePath); if (redirect) { return new RedirectHttpHandler { RelativeUrl = pathInfo + "/", }; } } } //e.g. CatchAllHandler to Process Markdown files var catchAllHandler = GetCatchAllHandlerIfAny(httpMethod, pathInfo, filePath); if (catchAllHandler != null) return catchAllHandler; if (!isFileRequest) return NotFoundHttpHandler; return ShouldAllow(requestPath) ? StaticFileHandler : ForbiddenHttpHandler; } var handler = GetCatchAllHandlerIfAny(httpMethod, pathInfo, filePath); if (handler != null) return handler; if (EndpointHost.Config.FallbackRestPath != null) { restPath = EndpointHost.Config.FallbackRestPath(httpMethod, pathInfo, filePath); if (restPath != null) { return new RestHandler { RestPath = restPath, RequestName = restPath.RequestType.Name, ResponseContentType = contentType }; } } return null; } private static IHttpHandler GetCatchAllHandlerIfAny(string httpMethod, string pathInfo, string filePath) { if (EndpointHost.CatchAllHandlers != null) { foreach (var httpHandlerResolver in EndpointHost.CatchAllHandlers) { var httpHandler = httpHandlerResolver(httpMethod, pathInfo, filePath); if (httpHandler != null) return httpHandler; } } return null; } public void ReleaseHandler(IHttpHandler handler) { } } }
namespace Castle.Goodies.Viewer { using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.IO; using System.Reflection; using System.Windows.Forms; using System.Data; using System.Security.Policy; using Netron.GraphLib; using Castle.Core; using Castle.MicroKernel; using Castle.Windsor; using Castle.Goodies.Viewer.Shapes; public class MainForm : Form { private Random rnd = new Random(); private System.ComponentModel.Container components = null; private Netron.GraphLib.UI.GraphControl graphControl1; private System.Windows.Forms.StatusBar statusBar1; private System.Windows.Forms.MainMenu mainMenu1; private System.Windows.Forms.MenuItem menuItem1; private System.Windows.Forms.MenuItem menuItem2; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.Panel panel1; private Netron.GraphLib.UI.Stamper stamper1; private System.Windows.Forms.Splitter splitter2; private System.Windows.Forms.PropertyGrid propertyGrid1; private System.Windows.Forms.Splitter splitter1; private String appPath = @"E:\dev\projects\digitalgravity\castle\trunk\Samples\MindDump\bin"; public MainForm() { // // Required for Windows Form Designer support // InitializeComponent(); AppDomain currentDomain = AppDomain.CurrentDomain; AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); AppDomain app = AppDomain.CreateDomain("minddump", new Evidence(currentDomain.Evidence), appPath, null, false); // app.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); object remoteInstance = null; try { remoteInstance = app.CreateInstanceAndUnwrap( "Castle.Applications.MindDump", "Castle.Applications.MindDump.MindDumpContainer"); } catch(Exception ex) { MessageBox.Show(ex.StackTrace); } IKernel kernel = null; if (remoteInstance is IWindsorContainer) { kernel = (remoteInstance as IWindsorContainer).Kernel; } else { kernel = (remoteInstance as IKernel); } graphControl1.AddLibrary("BasicShapes.dll"); graphControl1.AddLibrary("Castle.Goodies.Viewer.exe"); stamper1.GraphControl = graphControl1; graphControl1.AllowAddShape = false; if (kernel == null) return; GraphNode[] nodes = kernel.GraphNodes; Hashtable node2Shape = new Hashtable(); foreach(ComponentModel node in nodes) { ComponentNode shape = (ComponentNode) graphControl1.AddShape("castle.comp.node", new PointF(80,20)); shape.Key = node.Name; shape.Text = GetPossibleNullName(node.Service); shape.Implementation = GetPossibleNullName(node.Implementation); shape.Tag = node; node2Shape[node] = shape; SetShape(shape); } foreach(ComponentModel node in nodes) { Shape parentShape = node2Shape[node] as Shape; foreach(ComponentModel dep in node.Adjacencies) { Shape childShape = node2Shape[dep] as Shape; Connect(parentShape, childShape); } } } private string GetPossibleNullName(Type type) { if (type == null) { return "<Custom Activator>"; } return type.Name; } private void SetShape(Shape shape) { shape.FitSize(false); shape.X = rnd.Next(50,this.graphControl1.Width-100); shape.Y = rnd.Next(50,this.graphControl1.Height-20); } private Connection Connect(Shape childShape, Shape parentShape) { Connection conn = graphControl1.AddEdge(childShape.Connectors[1], parentShape.Connectors[0]); // conn.From.ConnectorLocation = ConnectorLocations.South; // conn.To.ConnectorLocation = ConnectorLocations.North; conn.LineEnd = ConnectionEnds.RightOpenArrow; return conn; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.graphControl1 = new Netron.GraphLib.UI.GraphControl(); this.statusBar1 = new System.Windows.Forms.StatusBar(); this.mainMenu1 = new System.Windows.Forms.MainMenu(); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.menuItem2 = new System.Windows.Forms.MenuItem(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.panel1 = new System.Windows.Forms.Panel(); this.stamper1 = new Netron.GraphLib.UI.Stamper(); this.splitter2 = new System.Windows.Forms.Splitter(); this.propertyGrid1 = new System.Windows.Forms.PropertyGrid(); this.splitter1 = new System.Windows.Forms.Splitter(); this.tabControl1.SuspendLayout(); this.tabPage1.SuspendLayout(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // graphControl1 // this.graphControl1.AllowAddConnection = true; this.graphControl1.AllowAddShape = true; this.graphControl1.AllowDeleteShape = true; this.graphControl1.AllowDrop = true; this.graphControl1.AllowMoveShape = true; this.graphControl1.AutomataPulse = 10; this.graphControl1.AutoScroll = true; this.graphControl1.BackgroundColor = System.Drawing.Color.Gray; this.graphControl1.BackgroundImagePath = null; this.graphControl1.BackgroundType = Netron.GraphLib.CanvasBackgroundTypes.FlatColor; this.graphControl1.DefaultConnectionPath = "Default"; this.graphControl1.DefaultLineEnd = Netron.GraphLib.ConnectionEnds.NoEnds; this.graphControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.graphControl1.DoTrack = false; this.graphControl1.EnableContextMenu = false; this.graphControl1.EnableLayout = false; this.graphControl1.FileName = null; this.graphControl1.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.graphControl1.GradientBottom = System.Drawing.Color.White; this.graphControl1.GradientTop = System.Drawing.Color.LightSteelBlue; this.graphControl1.GraphLayoutAlgorithm = Netron.GraphLib.GraphLayoutAlgorithms.SpringEmbedder; this.graphControl1.GridSize = 20; this.graphControl1.Location = new System.Drawing.Point(0, 0); this.graphControl1.Name = "graphControl1"; this.graphControl1.RestrictToCanvas = false; this.graphControl1.ShowGrid = true; this.graphControl1.Size = new System.Drawing.Size(424, 445); this.graphControl1.Snap = false; this.graphControl1.TabIndex = 4; this.graphControl1.Text = "graphControl1"; this.graphControl1.Zoom = 1F; this.graphControl1.ShowNodeProperties += new Netron.GraphLib.ShowPropsDelegate(this.graphControl1_ShowNodeProperties); // // statusBar1 // this.statusBar1.Location = new System.Drawing.Point(0, 471); this.statusBar1.Name = "statusBar1"; this.statusBar1.Size = new System.Drawing.Size(728, 22); this.statusBar1.TabIndex = 2; this.statusBar1.Text = "statusBar1"; // // mainMenu1 // this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem1}); // // menuItem1 // this.menuItem1.Index = 0; this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem2}); this.menuItem1.Text = "File"; // // menuItem2 // this.menuItem2.Index = 0; this.menuItem2.Text = "Exit"; // // tabControl1 // this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Dock = System.Windows.Forms.DockStyle.Left; this.tabControl1.Location = new System.Drawing.Point(0, 0); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(432, 471); this.tabControl1.TabIndex = 5; // // tabPage1 // this.tabPage1.Controls.Add(this.graphControl1); this.tabPage1.Location = new System.Drawing.Point(4, 22); this.tabPage1.Name = "tabPage1"; this.tabPage1.Size = new System.Drawing.Size(424, 445); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "Configuration"; // // tabPage2 // this.tabPage2.Location = new System.Drawing.Point(4, 22); this.tabPage2.Name = "tabPage2"; this.tabPage2.Size = new System.Drawing.Size(424, 445); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Facilities"; // // panel1 // this.panel1.BackColor = System.Drawing.SystemColors.Control; this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.panel1.Controls.Add(this.propertyGrid1); this.panel1.Controls.Add(this.splitter2); this.panel1.Controls.Add(this.stamper1); this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; this.panel1.Location = new System.Drawing.Point(432, 0); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(296, 471); this.panel1.TabIndex = 7; // // stamper1 // this.stamper1.AutoScroll = true; this.stamper1.Dock = System.Windows.Forms.DockStyle.Bottom; this.stamper1.Location = new System.Drawing.Point(0, 259); this.stamper1.Name = "stamper1"; this.stamper1.Size = new System.Drawing.Size(292, 208); this.stamper1.TabIndex = 2; this.stamper1.Zoom = 0.2F; // // splitter2 // this.splitter2.Dock = System.Windows.Forms.DockStyle.Bottom; this.splitter2.Location = new System.Drawing.Point(0, 256); this.splitter2.Name = "splitter2"; this.splitter2.Size = new System.Drawing.Size(292, 3); this.splitter2.TabIndex = 3; this.splitter2.TabStop = false; // // propertyGrid1 // this.propertyGrid1.CommandsVisibleIfAvailable = true; this.propertyGrid1.Dock = System.Windows.Forms.DockStyle.Fill; this.propertyGrid1.LargeButtons = false; this.propertyGrid1.LineColor = System.Drawing.SystemColors.ScrollBar; this.propertyGrid1.Location = new System.Drawing.Point(0, 0); this.propertyGrid1.Name = "propertyGrid1"; this.propertyGrid1.Size = new System.Drawing.Size(292, 256); this.propertyGrid1.TabIndex = 4; this.propertyGrid1.Text = "propertyGrid1"; this.propertyGrid1.ViewBackColor = System.Drawing.SystemColors.Window; this.propertyGrid1.ViewForeColor = System.Drawing.SystemColors.WindowText; // // splitter1 // this.splitter1.Location = new System.Drawing.Point(432, 0); this.splitter1.Name = "splitter1"; this.splitter1.Size = new System.Drawing.Size(3, 471); this.splitter1.TabIndex = 8; this.splitter1.TabStop = false; // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 14); this.ClientSize = new System.Drawing.Size(728, 493); this.Controls.Add(this.splitter1); this.Controls.Add(this.panel1); this.Controls.Add(this.tabControl1); this.Controls.Add(this.statusBar1); this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Menu = this.mainMenu1; this.Name = "Form1"; this.Text = "Form1"; this.tabControl1.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.panel1.ResumeLayout(false); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new MainForm()); } private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { // Is full assemblyName? String name = args.Name; int index = name.IndexOf(','); if (index != -1) { name = name.Substring(0, index); } name = Path.Combine( appPath, name ); String nameVar1 = String.Format( "{0}.dll", name ); String nameVar2 = String.Format( "{0}.exe", name ); FileInfo info1 = new FileInfo( nameVar1 ); FileInfo info2 = new FileInfo( nameVar2 ); if (info1.Exists) { return Assembly.LoadFile( info1.FullName ); } else if (info2.Exists) { return Assembly.LoadFile( info2.FullName ); } // Could not find ... return null; } private void graphControl1_ShowNodeProperties(object sender, Netron.GraphLib.PropertyBag props) { propertyGrid1.SelectedObject = props; } } }
// 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.Linq; using System.Threading.Tasks; using Xunit; namespace System.IO.Compression.Tests { public partial class ZipFileTestBase : FileCleanupTestBase { public static string bad(string filename) => Path.Combine("ZipTestData", "badzipfiles", filename); public static string compat(string filename) => Path.Combine("ZipTestData", "compat", filename); public static string strange(string filename) => Path.Combine("ZipTestData", "StrangeZipFiles", filename); public static string zfile(string filename) => Path.Combine("ZipTestData", "refzipfiles", filename); public static string zfolder(string filename) => Path.Combine("ZipTestData", "refzipfolders", filename); public static string zmodified(string filename) => Path.Combine("ZipTestData", "modified", filename); protected TempFile CreateTempCopyFile(string path, string newPath) { TempFile newfile = new TempFile(newPath); File.Copy(path, newPath, overwrite: true); return newfile; } public static long LengthOfUnseekableStream(Stream s) { long totalBytes = 0; const int bufSize = 4096; byte[] buf = new byte[bufSize]; long bytesRead = 0; do { bytesRead = s.Read(buf, 0, bufSize); totalBytes += bytesRead; } while (bytesRead > 0); return totalBytes; } // reads exactly bytesToRead out of stream, unless it is out of bytes public static void ReadBytes(Stream stream, byte[] buffer, long bytesToRead) { int bytesLeftToRead; if (bytesToRead > int.MaxValue) { throw new NotImplementedException("64 bit addresses"); } else { bytesLeftToRead = (int)bytesToRead; } int totalBytesRead = 0; while (bytesLeftToRead > 0) { int bytesRead = stream.Read(buffer, totalBytesRead, bytesLeftToRead); if (bytesRead == 0) throw new IOException("Unexpected end of stream"); totalBytesRead += bytesRead; bytesLeftToRead -= bytesRead; } } public static bool ArraysEqual<T>(T[] a, T[] b) where T : IComparable<T> { if (a.Length != b.Length) return false; for (int i = 0; i < a.Length; i++) { if (a[i].CompareTo(b[i]) != 0) return false; } return true; } public static bool ArraysEqual<T>(T[] a, T[] b, int length) where T : IComparable<T> { for (int i = 0; i < length; i++) { if (a[i].CompareTo(b[i]) != 0) return false; } return true; } public static void StreamsEqual(Stream ast, Stream bst) { StreamsEqual(ast, bst, -1); } public static void StreamsEqual(Stream ast, Stream bst, int blocksToRead) { if (ast.CanSeek) ast.Seek(0, SeekOrigin.Begin); if (bst.CanSeek) bst.Seek(0, SeekOrigin.Begin); const int bufSize = 4096; byte[] ad = new byte[bufSize]; byte[] bd = new byte[bufSize]; int ac = 0; int bc = 0; int blocksRead = 0; //assume read doesn't do weird things do { if (blocksToRead != -1 && blocksRead >= blocksToRead) break; ac = ast.Read(ad, 0, 4096); bc = bst.Read(bd, 0, 4096); Assert.Equal(ac, bc); Assert.True(ArraysEqual<byte>(ad, bd, ac), "Stream contents not equal: " + ast.ToString() + ", " + bst.ToString()); blocksRead++; } while (ac == 4096); } public static async Task IsZipSameAsDirAsync(string archiveFile, string directory, ZipArchiveMode mode) { await IsZipSameAsDirAsync(archiveFile, directory, mode, requireExplicit: false, checkTimes: false); } public static async Task IsZipSameAsDirAsync(string archiveFile, string directory, ZipArchiveMode mode, bool requireExplicit, bool checkTimes) { var s = await StreamHelpers.CreateTempCopyStream(archiveFile); IsZipSameAsDir(s, directory, mode, requireExplicit, checkTimes); } public static void IsZipSameAsDir(Stream archiveFile, string directory, ZipArchiveMode mode, bool requireExplicit, bool checkTimes) { int count = 0; using (ZipArchive archive = new ZipArchive(archiveFile, mode)) { List<FileData> files = FileData.InPath(directory); Assert.All<FileData>(files, (file) => { count++; string entryName = file.FullName; if (file.IsFolder) entryName += Path.DirectorySeparatorChar; ZipArchiveEntry entry = archive.GetEntry(entryName); if (entry == null) { entryName = FlipSlashes(entryName); entry = archive.GetEntry(entryName); } if (file.IsFile) { Assert.NotNull(entry); long givenLength = entry.Length; var buffer = new byte[entry.Length]; using (Stream entrystream = entry.Open()) { entrystream.Read(buffer, 0, buffer.Length); string crc = CRC.CalculateCRC(buffer); Assert.Equal(file.Length, givenLength); Assert.Equal(file.CRC, crc); } if (checkTimes) { const int zipTimestampResolution = 2; // Zip follows the FAT timestamp resolution of two seconds for file records DateTime lower = file.LastModifiedDate.AddSeconds(-zipTimestampResolution); DateTime upper = file.LastModifiedDate.AddSeconds(zipTimestampResolution); Assert.InRange(entry.LastWriteTime.Ticks, lower.Ticks, upper.Ticks); } Assert.Equal(file.Name, entry.Name); Assert.Equal(entryName, entry.FullName); Assert.Equal(entryName, entry.ToString()); Assert.Equal(archive, entry.Archive); } else if (file.IsFolder) { if (entry == null) //entry not found { string entryNameOtherSlash = FlipSlashes(entryName); bool isEmtpy = !files.Any( f => f.IsFile && (f.FullName.StartsWith(entryName, StringComparison.OrdinalIgnoreCase) || f.FullName.StartsWith(entryNameOtherSlash, StringComparison.OrdinalIgnoreCase))); if (requireExplicit || isEmtpy) { Assert.Contains("emptydir", entryName); } if ((!requireExplicit && !isEmtpy) || entryName.Contains("emptydir")) count--; //discount this entry } else { using (Stream es = entry.Open()) { try { Assert.Equal(0, es.Length); } catch (NotSupportedException) { try { Assert.Equal(-1, es.ReadByte()); } catch (Exception) { Console.WriteLine("Didn't return EOF"); throw; } } } } } }); Assert.Equal(count, archive.Entries.Count); } } private static string FlipSlashes(string name) { Debug.Assert(!(name.Contains("\\") && name.Contains("/"))); return name.Contains("\\") ? name.Replace("\\", "/") : name.Contains("/") ? name.Replace("/", "\\") : name; } public static void DirsEqual(string actual, string expected) { var expectedList = FileData.InPath(expected); var actualList = Directory.GetFiles(actual, "*.*", SearchOption.AllDirectories); var actualFolders = Directory.GetDirectories(actual, "*.*", SearchOption.AllDirectories); var actualCount = actualList.Length + actualFolders.Length; Assert.Equal(expectedList.Count, actualCount); ItemEqual(actualList, expectedList, isFile: true); ItemEqual(actualFolders, expectedList, isFile: false); } public static void DirFileNamesEqual(string actual, string expected) { IEnumerable<string> actualEntries = Directory.EnumerateFileSystemEntries(actual, "*", SearchOption.AllDirectories); IEnumerable<string> expectedEntries = Directory.EnumerateFileSystemEntries(expected, "*", SearchOption.AllDirectories); Assert.True(Enumerable.SequenceEqual(expectedEntries.Select(i => Path.GetFileName(i)), actualEntries.Select(i => Path.GetFileName(i)))); } private static void ItemEqual(string[] actualList, List<FileData> expectedList, bool isFile) { for (int i = 0; i < actualList.Length; i++) { var actualFile = actualList[i]; string aEntry = Path.GetFullPath(actualFile); string aName = Path.GetFileName(aEntry); var bData = expectedList.Where(f => string.Equals(f.Name, aName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); string bEntry = Path.GetFullPath(Path.Combine(bData.OrigFolder, bData.FullName)); string bName = Path.GetFileName(bEntry); // expected 'emptydir' folder doesn't exist because MSBuild doesn't copy empty dir if (!isFile && aName.Contains("emptydir") && bName.Contains("emptydir")) continue; //we want it to be false that one of them is a directory and the other isn't Assert.False(Directory.Exists(aEntry) ^ Directory.Exists(bEntry), "Directory in one is file in other"); //contents same if (isFile) { Stream sa = StreamHelpers.CreateTempCopyStream(aEntry).Result; Stream sb = StreamHelpers.CreateTempCopyStream(bEntry).Result; StreamsEqual(sa, sb); } } } public static async Task CreateFromDir(string directory, Stream archiveStream, ZipArchiveMode mode) { var files = FileData.InPath(directory); using (ZipArchive archive = new ZipArchive(archiveStream, mode, true)) { foreach (var i in files) { if (i.IsFolder) { string entryName = i.FullName; ZipArchiveEntry e = archive.CreateEntry(entryName.Replace('\\', '/') + "/"); e.LastWriteTime = i.LastModifiedDate; } } foreach (var i in files) { if (i.IsFile) { string entryName = i.FullName; var installStream = await StreamHelpers.CreateTempCopyStream(Path.Combine(i.OrigFolder, i.FullName)); if (installStream != null) { ZipArchiveEntry e = archive.CreateEntry(entryName.Replace('\\', '/')); e.LastWriteTime = i.LastModifiedDate; using (Stream entryStream = e.Open()) { installStream.CopyTo(entryStream); } } } } } } internal static void AddEntry(ZipArchive archive, string name, string contents, DateTimeOffset lastWrite) { ZipArchiveEntry e = archive.CreateEntry(name); e.LastWriteTime = lastWrite; using (StreamWriter w = new StreamWriter(e.Open())) { w.WriteLine(contents); } } } }
using System; #pragma warning disable 1591 // ReSharper disable UnusedMember.Global // ReSharper disable MemberCanBePrivate.Global // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable IntroduceOptionalParameters.Global // ReSharper disable MemberCanBeProtected.Global // ReSharper disable InconsistentNaming namespace JetBrains.Annotations { /// <summary> /// Indicates that the value of the marked element could be <c>null</c> sometimes, /// so the check for <c>null</c> is necessary before its usage /// </summary> /// <example><code> /// [CanBeNull] public object Test() { return null; } /// public void UseTest() { /// var p = Test(); /// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException' /// } /// </code></example> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] public sealed class CanBeNullAttribute : Attribute { } /// <summary> /// Indicates that the value of the marked element could never be <c>null</c> /// </summary> /// <example><code> /// [NotNull] public object Foo() { /// return null; // Warning: Possible 'null' assignment /// } /// </code></example> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] public sealed class NotNullAttribute : Attribute { } /// <summary> /// Indicates that the marked method builds string by format pattern and (optional) arguments. /// Parameter, which contains format string, should be given in constructor. The format string /// should be in <see cref="string.Format(IFormatProvider,string,object[])"/>-like form /// </summary> /// <example><code> /// [StringFormatMethod("message")] /// public void ShowError(string message, params object[] args) { /* do something */ } /// public void Foo() { /// ShowError("Failed: {0}"); // Warning: Non-existing argument in format string /// } /// </code></example> [AttributeUsage( AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public sealed class StringFormatMethodAttribute : Attribute { /// <param name="formatParameterName"> /// Specifies which parameter of an annotated method should be treated as format-string /// </param> public StringFormatMethodAttribute(string formatParameterName) { FormatParameterName = formatParameterName; } public string FormatParameterName { get; private set; } } /// <summary> /// Indicates that the function argument should be string literal and match one /// of the parameters of the caller function. For example, ReSharper annotates /// the parameter of <see cref="System.ArgumentNullException"/> /// </summary> /// <example><code> /// public void Foo(string param) { /// if (param == null) /// throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol /// } /// </code></example> [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] public sealed class InvokerParameterNameAttribute : Attribute { } /// <summary> /// Indicates that the method is contained in a type that implements /// <see cref="System.ComponentModel.INotifyPropertyChanged"/> interface /// and this method is used to notify that some property value changed /// </summary> /// <remarks> /// The method should be non-static and conform to one of the supported signatures: /// <list> /// <item><c>NotifyChanged(string)</c></item> /// <item><c>NotifyChanged(params string[])</c></item> /// <item><c>NotifyChanged{T}(Expression{Func{T}})</c></item> /// <item><c>NotifyChanged{T,U}(Expression{Func{T,U}})</c></item> /// <item><c>SetProperty{T}(ref T, T, string)</c></item> /// </list> /// </remarks> /// <example><code> /// public class Foo : INotifyPropertyChanged { /// public event PropertyChangedEventHandler PropertyChanged; /// [NotifyPropertyChangedInvocator] /// protected virtual void NotifyChanged(string propertyName) { ... } /// /// private string _name; /// public string Name { /// get { return _name; } /// set { _name = value; NotifyChanged("LastName"); /* Warning */ } /// } /// } /// </code> /// Examples of generated notifications: /// <list> /// <item><c>NotifyChanged("Property")</c></item> /// <item><c>NotifyChanged(() =&gt; Property)</c></item> /// <item><c>NotifyChanged((VM x) =&gt; x.Property)</c></item> /// <item><c>SetProperty(ref myField, value, "Property")</c></item> /// </list> /// </example> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public sealed class NotifyPropertyChangedInvocatorAttribute : Attribute { public NotifyPropertyChangedInvocatorAttribute() { } public NotifyPropertyChangedInvocatorAttribute(string parameterName) { ParameterName = parameterName; } public string ParameterName { get; private set; } } /// <summary> /// Describes dependency between method input and output /// </summary> /// <syntax> /// <p>Function Definition Table syntax:</p> /// <list> /// <item>FDT ::= FDTRow [;FDTRow]*</item> /// <item>FDTRow ::= Input =&gt; Output | Output &lt;= Input</item> /// <item>Input ::= ParameterName: Value [, Input]*</item> /// <item>Output ::= [ParameterName: Value]* {halt|stop|void|nothing|Value}</item> /// <item>Value ::= true | false | null | notnull | canbenull</item> /// </list> /// If method has single input parameter, it's name could be omitted.<br/> /// Using <c>halt</c> (or <c>void</c>/<c>nothing</c>, which is the same) /// for method output means that the methos doesn't return normally.<br/> /// <c>canbenull</c> annotation is only applicable for output parameters.<br/> /// You can use multiple <c>[ContractAnnotation]</c> for each FDT row, /// or use single attribute with rows separated by semicolon.<br/> /// </syntax> /// <examples><list> /// <item><code> /// [ContractAnnotation("=> halt")] /// public void TerminationMethod() /// </code></item> /// <item><code> /// [ContractAnnotation("halt &lt;= condition: false")] /// public void Assert(bool condition, string text) // regular assertion method /// </code></item> /// <item><code> /// [ContractAnnotation("s:null => true")] /// public bool IsNullOrEmpty(string s) // string.IsNullOrEmpty() /// </code></item> /// <item><code> /// // A method that returns null if the parameter is null, and not null if the parameter is not null /// [ContractAnnotation("null => null; notnull => notnull")] /// public object Transform(object data) /// </code></item> /// <item><code> /// [ContractAnnotation("s:null=>false; =>true,result:notnull; =>false, result:null")] /// public bool TryParse(string s, out Person result) /// </code></item> /// </list></examples> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)] public sealed class ContractAnnotationAttribute : Attribute { public ContractAnnotationAttribute([NotNull] string contract) : this(contract, false) { } public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates) { Contract = contract; ForceFullStates = forceFullStates; } public string Contract { get; private set; } public bool ForceFullStates { get; private set; } } /// <summary> /// Indicates that marked element should be localized or not /// </summary> /// <example><code> /// [LocalizationRequiredAttribute(true)] /// public class Foo { /// private string str = "my string"; // Warning: Localizable string /// } /// </code></example> [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] public sealed class LocalizationRequiredAttribute : Attribute { public LocalizationRequiredAttribute() : this(true) { } public LocalizationRequiredAttribute(bool required) { Required = required; } public bool Required { get; private set; } } /// <summary> /// Indicates that the value of the marked type (or its derivatives) /// cannot be compared using '==' or '!=' operators and <c>Equals()</c> /// should be used instead. However, using '==' or '!=' for comparison /// with <c>null</c> is always permitted. /// </summary> /// <example><code> /// [CannotApplyEqualityOperator] /// class NoEquality { } /// class UsesNoEquality { /// public void Test() { /// var ca1 = new NoEquality(); /// var ca2 = new NoEquality(); /// if (ca1 != null) { // OK /// bool condition = ca1 == ca2; // Warning /// } /// } /// } /// </code></example> [AttributeUsage( AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = true)] public sealed class CannotApplyEqualityOperatorAttribute : Attribute { } /// <summary> /// When applied to a target attribute, specifies a requirement for any type marked /// with the target attribute to implement or inherit specific type or types. /// </summary> /// <example><code> /// [BaseTypeRequired(typeof(IComponent)] // Specify requirement /// public class ComponentAttribute : Attribute { } /// [Component] // ComponentAttribute requires implementing IComponent interface /// public class MyComponent : IComponent { } /// </code></example> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] [BaseTypeRequired(typeof(Attribute))] public sealed class BaseTypeRequiredAttribute : Attribute { public BaseTypeRequiredAttribute([NotNull] Type baseType) { BaseType = baseType; } [NotNull] public Type BaseType { get; private set; } } /// <summary> /// Indicates that the marked symbol is used implicitly /// (e.g. via reflection, in external library), so this symbol /// will not be marked as unused (as well as by other usage inspections) /// </summary> [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] public sealed class UsedImplicitlyAttribute : Attribute { public UsedImplicitlyAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } public UsedImplicitlyAttribute( ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } public ImplicitUseKindFlags UseKindFlags { get; private set; } public ImplicitUseTargetFlags TargetFlags { get; private set; } } /// <summary> /// Should be used on attributes and causes ReSharper /// to not mark symbols marked with such attributes as unused /// (as well as by other usage inspections) /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public sealed class MeansImplicitUseAttribute : Attribute { public MeansImplicitUseAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } public MeansImplicitUseAttribute( ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } [UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; private set; } [UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; private set; } } [Flags] public enum ImplicitUseKindFlags { Default = Access | Assign | InstantiatedWithFixedConstructorSignature, /// <summary>Only entity marked with attribute considered used</summary> Access = 1, /// <summary>Indicates implicit assignment to a member</summary> Assign = 2, /// <summary> /// Indicates implicit instantiation of a type with fixed constructor signature. /// That means any unused constructor parameters won't be reported as such. /// </summary> InstantiatedWithFixedConstructorSignature = 4, /// <summary>Indicates implicit instantiation of a type</summary> InstantiatedNoFixedConstructorSignature = 8, } /// <summary> /// Specify what is considered used implicitly /// when marked with <see cref="MeansImplicitUseAttribute"/> /// or <see cref="UsedImplicitlyAttribute"/> /// </summary> [Flags] public enum ImplicitUseTargetFlags { Default = Itself, Itself = 1, /// <summary>Members of entity marked with attribute are considered used</summary> Members = 2, /// <summary>Entity marked with attribute and all its members considered used</summary> WithMembers = Itself | Members } /// <summary> /// This attribute is intended to mark publicly available API /// which should not be removed and so is treated as used /// </summary> [MeansImplicitUse] public sealed class PublicAPIAttribute : Attribute { public PublicAPIAttribute() { } public PublicAPIAttribute([NotNull] string comment) { Comment = comment; } [NotNull] public string Comment { get; private set; } } /// <summary> /// Tells code analysis engine if the parameter is completely handled /// when the invoked method is on stack. If the parameter is a delegate, /// indicates that delegate is executed while the method is executed. /// If the parameter is an enumerable, indicates that it is enumerated /// while the method is executed /// </summary> [AttributeUsage(AttributeTargets.Parameter, Inherited = true)] public sealed class InstantHandleAttribute : Attribute { } /// <summary> /// Indicates that a method does not make any observable state changes. /// The same as <c>System.Diagnostics.Contracts.PureAttribute</c> /// </summary> /// <example><code> /// [Pure] private int Multiply(int x, int y) { return x * y; } /// public void Foo() { /// const int a = 2, b = 2; /// Multiply(a, b); // Waring: Return value of pure method is not used /// } /// </code></example> [AttributeUsage(AttributeTargets.Method, Inherited = true)] public sealed class PureAttribute : Attribute { } /// <summary> /// Indicates that a parameter is a path to a file or a folder /// within a web project. Path can be relative or absolute, /// starting from web root (~) /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public class PathReferenceAttribute : Attribute { public PathReferenceAttribute() { } public PathReferenceAttribute([PathReference] string basePath) { BasePath = basePath; } [NotNull] public string BasePath { get; private set; } } // ASP.NET MVC attributes /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC action. If applied to a method, the MVC action name is calculated /// implicitly from the context. Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c> /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] public sealed class AspMvcActionAttribute : Attribute { public AspMvcActionAttribute() { } public AspMvcActionAttribute([NotNull] string anonymousProperty) { AnonymousProperty = anonymousProperty; } [NotNull] public string AnonymousProperty { get; private set; } } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC area. /// Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c> /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class AspMvcAreaAttribute : PathReferenceAttribute { public AspMvcAreaAttribute() { } public AspMvcAreaAttribute([NotNull] string anonymousProperty) { AnonymousProperty = anonymousProperty; } [NotNull] public string AnonymousProperty { get; private set; } } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that /// the parameter is an MVC controller. If applied to a method, /// the MVC controller name is calculated implicitly from the context. /// Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String, String)</c> /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] public sealed class AspMvcControllerAttribute : Attribute { public AspMvcControllerAttribute() { } public AspMvcControllerAttribute([NotNull] string anonymousProperty) { AnonymousProperty = anonymousProperty; } [NotNull] public string AnonymousProperty { get; private set; } } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC Master. /// Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Controller.View(String, String)</c> /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class AspMvcMasterAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC model type. /// Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Controller.View(String, Object)</c> /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class AspMvcModelTypeAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that /// the parameter is an MVC partial view. If applied to a method, /// the MVC partial view name is calculated implicitly from the context. /// Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper, String)</c> /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] public sealed class AspMvcPartialViewAttribute : PathReferenceAttribute { } /// <summary> /// ASP.NET MVC attribute. Allows disabling all inspections /// for MVC views within a class or a method. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public sealed class AspMvcSupressViewErrorAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC display template. /// Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.DisplayExtensions.DisplayForModel(HtmlHelper, String)</c> /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class AspMvcDisplayTemplateAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC editor template. /// Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.EditorExtensions.EditorForModel(HtmlHelper, String)</c> /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class AspMvcEditorTemplateAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC template. /// Use this attribute for custom wrappers similar to /// <c>System.ComponentModel.DataAnnotations.UIHintAttribute(System.String)</c> /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class AspMvcTemplateAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC view. If applied to a method, the MVC view name is calculated implicitly /// from the context. Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Controller.View(Object)</c> /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] public sealed class AspMvcViewAttribute : PathReferenceAttribute { } /// <summary> /// ASP.NET MVC attribute. When applied to a parameter of an attribute, /// indicates that this parameter is an MVC action name /// </summary> /// <example><code> /// [ActionName("Foo")] /// public ActionResult Login(string returnUrl) { /// ViewBag.ReturnUrl = Url.Action("Foo"); // OK /// return RedirectToAction("Bar"); // Error: Cannot resolve action /// } /// </code></example> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)] public sealed class AspMvcActionSelectorAttribute : Attribute { } [AttributeUsage( AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field, Inherited = true)] public sealed class HtmlElementAttributesAttribute : Attribute { public HtmlElementAttributesAttribute() { } public HtmlElementAttributesAttribute([NotNull] string name) { Name = name; } [NotNull] public string Name { get; private set; } } [AttributeUsage( AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property, Inherited = true)] public sealed class HtmlAttributeValueAttribute : Attribute { public HtmlAttributeValueAttribute([NotNull] string name) { Name = name; } [NotNull] public string Name { get; private set; } } // Razor attributes /// <summary> /// Razor attribute. Indicates that a parameter or a method is a Razor section. /// Use this attribute for custom wrappers similar to /// <c>System.Web.WebPages.WebPageBase.RenderSection(String)</c> /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method, Inherited = true)] public sealed class RazorSectionAttribute : Attribute { } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Versions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.TodoComments { internal partial class TodoCommentIncrementalAnalyzer : IIncrementalAnalyzer { public const string Name = "Todo Comment Document Worker"; private readonly TodoCommentIncrementalAnalyzerProvider _owner; private readonly Workspace _workspace; private readonly IOptionService _optionService; private readonly TodoCommentTokens _todoCommentTokens; private readonly TodoCommentState _state; public TodoCommentIncrementalAnalyzer(Workspace workspace, IOptionService optionService, TodoCommentIncrementalAnalyzerProvider owner, TodoCommentTokens todoCommentTokens) { _workspace = workspace; _optionService = optionService; _owner = owner; _todoCommentTokens = todoCommentTokens; _state = new TodoCommentState(); } public Task DocumentResetAsync(Document document, CancellationToken cancellationToken) { // remove cache _state.Remove(document.Id); return _state.PersistAsync(document, new Data(VersionStamp.Default, VersionStamp.Default, ImmutableArray<ITaskItem>.Empty), cancellationToken); } public async Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) { Contract.ThrowIfFalse(document.IsFromPrimaryBranch()); // it has an assumption that this will not be called concurrently for same document. // in fact, in current design, it won't be even called concurrently for different documents. // but, can be called concurrently for different documents in future if we choose to. if (!_optionService.GetOption(InternalFeatureOnOffOptions.TodoComments)) { return; } // use tree version so that things like compiler option changes are considered var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); var syntaxVersion = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false); var existingData = await _state.TryGetExistingDataAsync(document, cancellationToken).ConfigureAwait(false); if (existingData != null) { // check whether we can use the data as it is (can happen when re-using persisted data from previous VS session) if (CheckVersions(document, textVersion, syntaxVersion, existingData)) { Contract.Requires(_workspace == document.Project.Solution.Workspace); RaiseTaskListUpdated(_workspace, document.Id, existingData.Items); return; } } var service = document.GetLanguageService<ITodoCommentService>(); if (service == null) { return; } var comments = await service.GetTodoCommentsAsync(document, _todoCommentTokens.GetTokens(_workspace), cancellationToken).ConfigureAwait(false); var items = await CreateItemsAsync(document, comments, cancellationToken).ConfigureAwait(false); var data = new Data(textVersion, syntaxVersion, items); await _state.PersistAsync(document, data, cancellationToken).ConfigureAwait(false); // * NOTE * cancellation can't throw after this point. if (existingData == null || existingData.Items.Length > 0 || data.Items.Length > 0) { Contract.Requires(_workspace == document.Project.Solution.Workspace); RaiseTaskListUpdated(_workspace, document.Id, data.Items); } } private async Task<ImmutableArray<ITaskItem>> CreateItemsAsync(Document document, IList<TodoComment> comments, CancellationToken cancellationToken) { var items = ImmutableArray.CreateBuilder<ITaskItem>(); if (comments != null) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var syntaxTree = document.SupportsSyntaxTree ? await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false) : null; foreach (var comment in comments) { items.Add(CreateItem(document, text, syntaxTree, comment)); } } return items.ToImmutable(); } private ITaskItem CreateItem(Document document, SourceText text, SyntaxTree tree, TodoComment comment) { var textSpan = new TextSpan(comment.Position, 0); var location = tree == null ? Location.Create(document.FilePath, textSpan, text.Lines.GetLinePositionSpan(textSpan)) : tree.GetLocation(textSpan); var originalLineInfo = location.GetLineSpan(); var mappedLineInfo = location.GetMappedLineSpan(); return new TodoTaskItem( comment.Descriptor.Priority, comment.Message, document.Project.Solution.Workspace, document.Id, mappedLine: mappedLineInfo.StartLinePosition.Line, originalLine: originalLineInfo.StartLinePosition.Line, mappedColumn: mappedLineInfo.StartLinePosition.Character, originalColumn: originalLineInfo.StartLinePosition.Character, mappedFilePath: mappedLineInfo.GetMappedFilePathIfExist(), originalFilePath: document.FilePath); } public ImmutableArray<ITaskItem> GetTodoItems(Workspace workspace, DocumentId id, CancellationToken cancellationToken) { var document = workspace.CurrentSolution.GetDocument(id); if (document == null) { return ImmutableArray<ITaskItem>.Empty; } // TODO let's think about what to do here. for now, let call it synchronously. also, there is no actual asynch-ness for the // TryGetExistingDataAsync, API just happen to be async since our persistent API is async API. but both caller and implementor are // actually not async. var existingData = _state.TryGetExistingDataAsync(document, cancellationToken).WaitAndGetResult(cancellationToken); if (existingData == null) { return ImmutableArray<ITaskItem>.Empty; } return existingData.Items; } private static bool CheckVersions(Document document, VersionStamp textVersion, VersionStamp syntaxVersion, Data existingData) { // first check full version to see whether we can reuse data in same session, if we can't, check timestamp only version to see whether // we can use it cross-session. return document.CanReusePersistedTextVersion(textVersion, existingData.TextVersion) && document.CanReusePersistedSyntaxTreeVersion(syntaxVersion, existingData.SyntaxVersion); } internal ImmutableArray<ITaskItem> GetItems_TestingOnly(DocumentId documentId) { return _state.GetItems_TestingOnly(documentId); } private void RaiseTaskListUpdated(Workspace workspace, DocumentId documentId, ImmutableArray<ITaskItem> items) { if (_owner != null) { _owner.RaiseTaskListUpdated(documentId, workspace, documentId.ProjectId, documentId, items); } } public void RemoveDocument(DocumentId documentId) { _state.Remove(documentId); RaiseTaskListUpdated(_workspace, documentId, ImmutableArray<ITaskItem>.Empty); } public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) { return e.Option == TodoCommentOptions.TokenList; } private class Data { public readonly VersionStamp TextVersion; public readonly VersionStamp SyntaxVersion; public readonly ImmutableArray<ITaskItem> Items; public Data(VersionStamp textVersion, VersionStamp syntaxVersion, ImmutableArray<ITaskItem> items) { this.TextVersion = textVersion; this.SyntaxVersion = syntaxVersion; this.Items = items; } } #region not used public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public void RemoveProject(ProjectId projectId) { } #endregion } }
// ******************************************************************************************************** // Product Name: DotSpatial.Positioning.dll // Description: A library for managing GPS connections. // ******************************************************************************************************** // // The Original Code is from http://gps3.codeplex.com/ version 3.0 // // The Initial Developer of this original code is Jon Pearson. Submitted Oct. 21, 2010 by Ben Tombs (tidyup) // // Contributor(s): (Open source contributors should list themselves and their modifications here). // ------------------------------------------------------------------------------------------------------- // | Developer | Date | Comments // |--------------------------|------------|-------------------------------------------------------------- // | Tidyup (Ben Tombs) | 10/21/2010 | Original copy submitted from modified GPS.Net 3.0 // | Shade1974 (Ted Dunsford) | 10/22/2010 | Added file headers reviewed formatting with resharper. // ******************************************************************************************************** using System; using System.Collections.Generic; using System.Text; namespace DotSpatial.Positioning { /// <summary> /// Represents a $GPGSV sentence describing the location and signal strength of GPS /// satellites. /// </summary> /// <remarks>This sentence is used to determine the location of GPS satellites relative /// to the current location, as well as to indicate the strength of a satellite's radio /// signal.</remarks> public sealed class GpgsvSentence : NmeaSentence, ISatelliteCollectionSentence { #region Constructors /// <summary> /// Creates a GPGSV sentence instance from the specified string. /// </summary> /// <param name="sentence">The sentence.</param> public GpgsvSentence(string sentence) : base(sentence) { SetPropertiesFromSentence(); } /// <summary> /// Initializes a new instance of the <see cref="GpgsvSentence"/> class. /// </summary> /// <param name="sentence">The sentence.</param> /// <param name="commandWord">The command word.</param> /// <param name="words">The words.</param> /// <param name="validChecksum">The valid checksum.</param> internal GpgsvSentence(string sentence, string commandWord, string[] words, string validChecksum) : base(sentence, commandWord, words, validChecksum) { SetPropertiesFromSentence(); } /// <summary> /// Creates a GPSV sentence instance from the specified parameters describing the location and signal strength of GPS satellites /// </summary> /// <param name="totalMessageCount">The total message count.</param> /// <param name="currentMessageNumber">The current message number.</param> /// <param name="satellitesInView">The satellites in view.</param> /// <param name="satellites">The satellites.</param> public GpgsvSentence(int totalMessageCount, int currentMessageNumber, int satellitesInView, IList<Satellite> satellites) { TotalMessageCount = totalMessageCount; CurrentMessageNumber = currentMessageNumber; SatellitesInView = satellitesInView; Satellites = satellites; // Build a sentence StringBuilder builder = new StringBuilder(128); // Append the command word builder.Append("$GPGSV"); builder.Append(','); // Total message count builder.Append(TotalMessageCount); builder.Append(','); // Current message number builder.Append(CurrentMessageNumber); builder.Append(','); // Satellites in view builder.Append(SatellitesInView); int count = Satellites.Count; for (int index = 0; index < count; index++) { Satellite satellite = Satellites[index]; // Serialize this satellite builder.Append(","); builder.Append(satellite.PseudorandomNumber.ToString("0#", NmeaCultureInfo)); builder.Append(","); builder.Append(satellite.Elevation.ToString("dd", NmeaCultureInfo)); builder.Append(","); builder.Append(satellite.Azimuth.ToString("ddd", NmeaCultureInfo)); builder.Append(","); builder.Append(satellite.SignalToNoiseRatio.Value.ToString("0#", NmeaCultureInfo)); } // Set this object's sentence Sentence = builder.ToString(); SetPropertiesFromSentence(); // Finally, append the checksum AppendChecksum(); } #endregion Constructors #region Overrides /// <summary> /// Corrects this classes properties after the base sentence was changed. /// </summary> private new void SetPropertiesFromSentence() { // Cache the words string[] words = Words; int wordCount = words.Length; /* $GPGSV * * GPS Satellites in view * * eg. $GPGSV, 3, 1, 11, 03, 03, 111, 00, 04, 15, 270, 00, 06, 01, 010, 00, 13, 06, 292, 00*74 * $GPGSV, 3, 2, 11, 14, 25, 170, 00, 16, 57, 208, 39, 18, 67, 296, 40, 19, 40, 246, 00*74 * $GPGSV, 3, 3, 11, 22, 42, 067, 42, 24, 14, 311, 43, 27, 05, 244, 00, ,, ,*4D * * * $GPGSV, 1, 1, 13, 02, 02, 213, ,03, -3, 000, ,11, 00, 121, ,14, 13, 172, 05*62 * * * 1 = Total number of messages of this type in this cycle * 2 = Message number * 3 = Total number of SVs in view * 4 = SV PRN number * 5 = Elevation in degrees, 90 maximum * 6 = Azimuth, degrees from true north, 000 to 359 * 7 = SNR, 00-99 dB (null when not tracking) * 8-11 = Information about second SV, same as field 4-7 * 12-15= Information about third SV, same as field 4-7 * 16-19= Information about fourth SV, same as field 4-7 */ // Example (signal not acquired): $GPGSV, 1, 1, 01, 21, 00, 000, *4B // Example (signal acquired): $GPGSV, 3, 1, 10, 20, 78, 331, 45, 01, 59, 235, 47, 22, 41, 069, ,13, 32, 252, 45*70 // Get the total message count if (wordCount > 0 && words[0].Length != 0) TotalMessageCount = int.Parse(words[0], NmeaCultureInfo); // Get the current message number if (wordCount > 1 && words[1].Length != 0) CurrentMessageNumber = int.Parse(words[1], NmeaCultureInfo); // Get the total message count if (wordCount > 2 && words[2].Length != 0) SatellitesInView = int.Parse(words[2], NmeaCultureInfo); // Make a new list of satellites Satellites = new List<Satellite>(); // Now process each satellite for (int index = 0; index < 6; index++) { int currentWordIndex = index * 4 + 3; // Are we past the length of words? if (currentWordIndex > wordCount - 1) break; // No. Get the unique code for the satellite if (words[currentWordIndex].Length == 0) continue; int pseudorandomNumber = int.Parse(words[currentWordIndex], NmeaCultureInfo); Elevation newElevation; Azimuth newAzimuth; SignalToNoiseRatio newSignalToNoiseRatio; // Update the elevation if (wordCount > currentWordIndex + 1 && words[currentWordIndex + 1].Length != 0) newElevation = Elevation.Parse(words[currentWordIndex + 1], NmeaCultureInfo); else newElevation = Elevation.Empty; // Update the azimuth if (wordCount > currentWordIndex + 2 && words[currentWordIndex + 2].Length != 0) newAzimuth = Azimuth.Parse(words[currentWordIndex + 2], NmeaCultureInfo); else newAzimuth = Azimuth.Empty; // Update the signal strength if (wordCount > currentWordIndex + 3 && words[currentWordIndex + 3].Length != 0) newSignalToNoiseRatio = SignalToNoiseRatio.Parse(words[currentWordIndex + 3], NmeaCultureInfo); else newSignalToNoiseRatio = SignalToNoiseRatio.Empty; // Add the satellite to the collection Satellites.Add(new Satellite(pseudorandomNumber, newAzimuth, newElevation, newSignalToNoiseRatio, false)); } } #endregion Overrides #region Static Members /// <summary> /// Returns a collection of $GPGSV sentences fully describing the specified collection of satellites. /// </summary> /// <param name="satellites">The satellites.</param> /// <returns></returns> public static IList<GpgsvSentence> FromSatellites(IList<Satellite> satellites) { // Divide the collecting into 4-satellite chunks int totalMessages = (int)Math.Ceiling(satellites.Count / 4d); IList<GpgsvSentence> result = new List<GpgsvSentence>(totalMessages); // And populate each member of the array for (int index = 1; index <= totalMessages; index++) { // Make a collection with just the satellites we want List<Satellite> messageSatellites = new List<Satellite>(); for (int count = 0; count < 4; count++) { // Calculate the satellite to add int satelliteIndex = (index - 1) * 4 + count; // Stop if were at the end of the collection if (satelliteIndex >= satellites.Count) break; // Copy the satellite in messageSatellites.Add(satellites[satelliteIndex]); } // Now make the sentence result.Add(new GpgsvSentence(totalMessages, index, satellites.Count, messageSatellites)); } // return all sentences return result; } #endregion Static Members #region Public Members /// <summary> /// Returns a collection of <strong>Satellite</strong> objects describing current /// satellite information. /// </summary> public IList<Satellite> Satellites { get; private set; } /// <summary> /// Returns the total number of $GPGSV sentence in a sequence. /// </summary> public int TotalMessageCount { get; private set; } /// <summary> /// Returns the current message index when the sentence is one of several /// messages. /// </summary> public int CurrentMessageNumber { get; private set; } /// <summary> /// Returns the number of satellites whose signals are detected by the GPS /// device. /// </summary> public int SatellitesInView { get; private set; } #endregion Public Members } }
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2009 Oracle. All rights reserved. * */ using System; using System.Collections.Generic; using System.Text; using BerkeleyDB.Internal; namespace BerkeleyDB { /// <summary> /// A class representing a secondary Berkeley DB database, a base class for /// access method specific classes. /// </summary> public class SecondaryDatabase : BaseDatabase { private SecondaryKeyGenDelegate keyGenHandler; internal BDB_AssociateDelegate doAssocRef; private ForeignKeyNullifyDelegate nullifierHandler; internal BDB_AssociateForeignDelegate doNullifyRef; #region Constructors /// <summary> /// Protected construtor /// </summary> /// <param name="env">The environment in which to open the DB</param> /// <param name="flags">Flags to pass to DB->create</param> protected SecondaryDatabase(DatabaseEnvironment env, uint flags) : base(env, flags) { } internal static SecondaryDatabase fromDB(DB dbp) { try { return (SecondaryDatabase)dbp.api_internal; } catch { } return null; } /// <summary> /// Protected method to configure the DB. Only valid before DB->open. /// </summary> /// <param name="cfg">Configuration parameters.</param> protected void Config(SecondaryDatabaseConfig cfg) { base.Config(cfg); KeyGen = cfg.KeyGen; Nullifier = cfg.ForeignKeyNullfier; db.set_flags(cfg.flags); } /// <summary> /// Instantiate a new SecondaryDatabase object, open the database /// represented by <paramref name="Filename"/> and associate the /// database with the <see cref="SecondaryDatabaseConfig.Primary"> /// primary index</see>. The file specified by /// <paramref name="Filename"/> must exist. /// </summary> /// <remarks> /// <para> /// If <see cref="DatabaseConfig.AutoCommit"/> is set, the operation /// will be implicitly transaction protected. Note that transactionally /// protected operations on a datbase object requires the object itself /// be transactionally protected during its open. /// </para> /// </remarks> /// <param name="Filename"> /// The name of an underlying file that will be used to back the /// database. /// </param> /// <param name="cfg">The database's configuration</param> /// <returns>A new, open database object</returns> public static SecondaryDatabase Open( string Filename, SecondaryDatabaseConfig cfg) { return Open(Filename, null, cfg, null); } /// <summary> /// Instantiate a new SecondaryDatabase object, open the database /// represented by <paramref name="Filename"/> and associate the /// database with the <see cref="SecondaryDatabaseConfig.Primary"> /// primary index</see>. The file specified by /// <paramref name="Filename"/> must exist. /// </summary> /// <remarks> /// <para> /// If <paramref name="Filename"/> is null and /// <paramref name="DatabaseName"/> is non-null, the database can be /// opened by other threads of control and will be replicated to client /// sites in any replication group. /// </para> /// <para> /// If <see cref="DatabaseConfig.AutoCommit"/> is set, the operation /// will be implicitly transaction protected. Note that transactionally /// protected operations on a datbase object requires the object itself /// be transactionally protected during its open. /// </para> /// </remarks> /// <param name="Filename"> /// The name of an underlying file that will be used to back the /// database. /// </param> /// <param name="DatabaseName"> /// This parameter allows applications to have multiple databases in a /// single file. Although no DatabaseName needs to be specified, it is /// an error to attempt to open a second database in a file that was not /// initially created using a database name. /// </param> /// <param name="cfg">The database's configuration</param> /// <returns>A new, open database object</returns> public static SecondaryDatabase Open(string Filename, string DatabaseName, SecondaryDatabaseConfig cfg) { return Open(Filename, DatabaseName, cfg, null); } /// <summary> /// Instantiate a new SecondaryDatabase object, open the database /// represented by <paramref name="Filename"/> and associate the /// database with the <see cref="SecondaryDatabaseConfig.Primary"> /// primary index</see>. The file specified by /// <paramref name="Filename"/> must exist. /// </summary> /// <remarks> /// <para> /// If <see cref="DatabaseConfig.AutoCommit"/> is set, the operation /// will be implicitly transaction protected. Note that transactionally /// protected operations on a datbase object requires the object itself /// be transactionally protected during its open. /// </para> /// </remarks> /// <param name="Filename"> /// The name of an underlying file that will be used to back the /// database. /// </param> /// <param name="cfg">The database's configuration</param> /// <param name="txn"> /// If the operation is part of an application-specified transaction, /// <paramref name="txn"/> is a Transaction object returned from /// <see cref="DatabaseEnvironment.BeginTransaction"/>; if /// the operation is part of a Berkeley DB Concurrent Data Store group, /// <paramref name="txn"/> is a handle returned from /// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null. /// </param> /// <returns>A new, open database object</returns> public static SecondaryDatabase Open(string Filename, SecondaryDatabaseConfig cfg, Transaction txn) { return Open(Filename, null, cfg, txn); } /// <summary> /// Instantiate a new SecondaryDatabase object, open the database /// represented by <paramref name="Filename"/> and associate the /// database with the <see cref="SecondaryDatabaseConfig.Primary"> /// primary index</see>. The file specified by /// <paramref name="Filename"/> must exist. /// </summary> /// <remarks> /// <para> /// If <paramref name="Filename"/> is null and /// <paramref name="DatabaseName"/> is non-null, the database can be /// opened by other threads of control and will be replicated to client /// sites in any replication group. /// </para> /// <para> /// If <see cref="DatabaseConfig.AutoCommit"/> is set, the operation /// will be implicitly transaction protected. Note that transactionally /// protected operations on a datbase object requires the object itself /// be transactionally protected during its open. /// </para> /// </remarks> /// <param name="Filename"> /// The name of an underlying file that will be used to back the /// database. /// </param> /// <param name="DatabaseName"> /// This parameter allows applications to have multiple databases in a /// single file. Although no DatabaseName needs to be specified, it is /// an error to attempt to open a second database in a file that was not /// initially created using a database name. /// </param> /// <param name="cfg">The database's configuration</param> /// <param name="txn"> /// If the operation is part of an application-specified transaction, /// <paramref name="txn"/> is a Transaction object returned from /// <see cref="DatabaseEnvironment.BeginTransaction"/>; if /// the operation is part of a Berkeley DB Concurrent Data Store group, /// <paramref name="txn"/> is a handle returned from /// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null. /// </param> /// <returns>A new, open database object</returns> public static SecondaryDatabase Open(string Filename, string DatabaseName, SecondaryDatabaseConfig cfg, Transaction txn) { if (cfg.DbType == DatabaseType.BTREE) { return SecondaryBTreeDatabase.Open(Filename, DatabaseName, (SecondaryBTreeDatabaseConfig)cfg, txn); } else if (cfg.DbType == DatabaseType.HASH) { return SecondaryHashDatabase.Open(Filename, DatabaseName, (SecondaryHashDatabaseConfig)cfg, txn); } SecondaryDatabase ret = new SecondaryDatabase(cfg.Env, 0); ret.Config(cfg); ret.db.open(Transaction.getDB_TXN(txn), Filename, DatabaseName, cfg.DbType.getDBTYPE(), cfg.openFlags, 0); ret.doAssocRef = new BDB_AssociateDelegate(doAssociate); cfg.Primary.db.associate(Transaction.getDB_TXN(null), ret.db, ret.doAssocRef, cfg.assocFlags); if (cfg.ForeignKeyDatabase != null) { if (cfg.OnForeignKeyDelete == ForeignKeyDeleteAction.NULLIFY) ret.doNullifyRef = new BDB_AssociateForeignDelegate(doNullify); else ret.doNullifyRef = null; cfg.ForeignKeyDatabase.db.associate_foreign(ret.db, ret.doNullifyRef, cfg.foreignFlags); } return ret; } #endregion Constructors #region Callbacks /// <summary> /// Protected method to call the key generation function. /// </summary> /// <param name="dbp">Secondary DB Handle</param> /// <param name="keyp">Primary Key</param> /// <param name="datap">Primary Data</param> /// <param name="skeyp">Scondary Key</param> /// <returns>0 on success, !0 on failure</returns> protected static int doAssociate( IntPtr dbp, IntPtr keyp, IntPtr datap, IntPtr skeyp) { DB db = new DB(dbp, false); DBT key = new DBT(keyp, false); DBT data = new DBT(datap, false); DBT skey = new DBT(skeyp, false); DatabaseEntry s = ((SecondaryDatabase)db.api_internal).KeyGen( DatabaseEntry.fromDBT(key), DatabaseEntry.fromDBT(data)); if (s == null) return DbConstants.DB_DONOTINDEX; skey.data = s.Data; return 0; } /// <summary> /// Protected method to nullify a foreign key /// </summary> /// <param name="dbp">Secondary DB Handle</param> /// <param name="keyp">Primary Key</param> /// <param name="datap">Primary Data</param> /// <param name="fkeyp">Foreign Key</param> /// <param name="changed">Whether the foreign key has changed</param> /// <returns>0 on success, !0 on failure</returns> protected static int doNullify(IntPtr dbp, IntPtr keyp, IntPtr datap, IntPtr fkeyp, ref int changed) { DB db = new DB(dbp, false); DBT key = new DBT(keyp, false); DBT data = new DBT(datap, false); DBT fkey = new DBT(fkeyp, false); DatabaseEntry d = ((SecondaryDatabase)db.api_internal).Nullifier( DatabaseEntry.fromDBT(key), DatabaseEntry.fromDBT(data), DatabaseEntry.fromDBT(fkey)); if (d == null) changed = 0; else { changed = 1; data.data = d.Data; } return 0; } #endregion Callbacks #region Properties /// <summary> /// The delegate that creates the set of secondary keys corresponding to /// a given primary key and data pair. /// </summary> public SecondaryKeyGenDelegate KeyGen { get { return keyGenHandler; } private set { keyGenHandler = value; } } public ForeignKeyNullifyDelegate Nullifier { get { return nullifierHandler; } private set { nullifierHandler = value; } } #endregion Properties #region Methods /// <summary> /// Create a secondary database cursor. /// </summary> /// <returns>A newly created cursor</returns> public SecondaryCursor SecondaryCursor() { return SecondaryCursor(new CursorConfig(), null); } /// <summary> /// Create a secondary database cursor with the given configuration. /// </summary> /// <param name="cfg"> /// The configuration properties for the cursor. /// </param> /// <returns>A newly created cursor</returns> public SecondaryCursor SecondaryCursor(CursorConfig cfg) { return SecondaryCursor(cfg, null); } /// <summary> /// Create a transactionally protected secondary database cursor. /// </summary> /// <param name="txn"> /// The transaction context in which the cursor may be used. /// </param> /// <returns>A newly created cursor</returns> public SecondaryCursor SecondaryCursor(Transaction txn) { return SecondaryCursor(new CursorConfig(), txn); } /// <summary> /// Create a transactionally protected secondary database cursor with /// the given configuration. /// </summary> /// <param name="cfg"> /// The configuration properties for the cursor. /// </param> /// <param name="txn"> /// The transaction context in which the cursor may be used. /// </param> /// <returns>A newly created cursor</returns> public SecondaryCursor SecondaryCursor( CursorConfig cfg, Transaction txn) { return new SecondaryCursor( db.cursor(Transaction.getDB_TXN(txn), cfg.flags)); } #endregion Methods } }
//------------------------------------------------------------------------------ // <copyright file="DataTableCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> // <owner current="false" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data { using System; using System.Diagnostics; using System.Collections; using System.ComponentModel; using System.Globalization; /// <devdoc> /// <para> /// Represents the collection of tables for the <see cref='System.Data.DataSet'/>. /// </para> /// </devdoc> [ DefaultEvent("CollectionChanged"), Editor("Microsoft.VSDesigner.Data.Design.TablesCollectionEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing), ListBindable(false), ] public sealed class DataTableCollection : InternalDataCollectionBase { private readonly DataSet dataSet = null; // private DataTable[] tables = new DataTable[2]; // private int tableCount = 0; private readonly ArrayList _list = new ArrayList(); private int defaultNameIndex = 1; private DataTable[] delayedAddRangeTables = null; private CollectionChangeEventHandler onCollectionChangedDelegate = null; private CollectionChangeEventHandler onCollectionChangingDelegate = null; private static int _objectTypeCount; // Bid counter private readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount); /// <devdoc> /// DataTableCollection constructor. Used only by DataSet. /// </devdoc> internal DataTableCollection(DataSet dataSet) { Bid.Trace("<ds.DataTableCollection.DataTableCollection|INFO> %d#, dataSet=%d\n", ObjectID, (dataSet != null) ? dataSet.ObjectID : 0); this.dataSet = dataSet; } /// <devdoc> /// <para> /// Gets the tables /// in the collection as an object. /// </para> /// </devdoc> protected override ArrayList List { get { return _list; } } internal int ObjectID { get { return _objectID; } } /// <devdoc> /// <para>Gets the table specified by its index.</para> /// </devdoc> public DataTable this[int index] { get { try { // Perf: use the readonly _list field directly and let ArrayList check the range return(DataTable) _list[index]; } catch(ArgumentOutOfRangeException) { throw ExceptionBuilder.TableOutOfRange(index); } } } /// <devdoc> /// <para>Gets the table in the collection with the given name (not case-sensitive).</para> /// </devdoc> public DataTable this[string name] { get { int index = InternalIndexOf(name); if (index == -2) { throw ExceptionBuilder.CaseInsensitiveNameConflict(name); } if (index == -3) { throw ExceptionBuilder.NamespaceNameConflict(name); } return (index < 0) ? null : (DataTable)_list[index]; } } public DataTable this[string name, string tableNamespace] { get { if (tableNamespace == null) throw ExceptionBuilder.ArgumentNull("tableNamespace"); int index = InternalIndexOf(name, tableNamespace); if (index == -2) { throw ExceptionBuilder.CaseInsensitiveNameConflict(name); } return (index < 0) ? null : (DataTable)_list[index]; } } // Case-sensitive search in Schema, data and diffgram loading internal DataTable GetTable(string name, string ns) { for (int i = 0; i < _list.Count; i++) { DataTable table = (DataTable) _list[i]; if (table.TableName == name && table.Namespace == ns) return table; } return null; } // Case-sensitive smart search: it will look for a table using the ns only if required to // resolve a conflict internal DataTable GetTableSmart(string name, string ns){ int fCount = 0; DataTable fTable = null; for (int i = 0; i < _list.Count; i++) { DataTable table = (DataTable) _list[i]; if (table.TableName == name) { if (table.Namespace == ns) return table; fCount++; fTable = table; } } // if we get here we didn't match the namespace // so return the table only if fCount==1 (it's the only one) return (fCount == 1) ? fTable : null; } /// <devdoc> /// <para> /// Adds /// the specified table to the collection. /// </para> /// </devdoc> public void Add(DataTable table) { IntPtr hscp; Bid.ScopeEnter(out hscp, "<ds.DataTableCollection.Add|API> %d#, table=%d\n", ObjectID, (table!= null) ? table.ObjectID : 0); try { OnCollectionChanging(new CollectionChangeEventArgs(CollectionChangeAction.Add, table)); BaseAdd(table); ArrayAdd(table); if (table.SetLocaleValue(dataSet.Locale, false, false) || table.SetCaseSensitiveValue(dataSet.CaseSensitive, false, false)) { table.ResetIndexes(); } OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, table)); } finally { Bid.ScopeLeave(ref hscp); } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void AddRange(DataTable[] tables) { IntPtr hscp; Bid.ScopeEnter(out hscp, "<ds.DataTableCollection.AddRange|API> %d#\n", ObjectID); try { if (dataSet.fInitInProgress) { delayedAddRangeTables = tables; return; } if (tables != null) { foreach(DataTable table in tables) { if (table != null) { Add(table); } } } } finally{ Bid.ScopeLeave(ref hscp); } } /// <devdoc> /// <para> /// Creates a table with the given name and adds it to the /// collection. /// </para> /// </devdoc> public DataTable Add(string name) { DataTable table = new DataTable(name); // fxcop: new DataTable should inherit the CaseSensitive, Locale, Namespace from DataSet Add(table); return table; } public DataTable Add(string name, string tableNamespace) { DataTable table = new DataTable(name, tableNamespace); // fxcop: new DataTable should inherit the CaseSensitive, Locale from DataSet Add(table); return table; } /// <devdoc> /// <para> /// Creates a new table with a default name and adds it to /// the collection. /// </para> /// </devdoc> public DataTable Add() { DataTable table = new DataTable(); // fxcop: new DataTable should inherit the CaseSensitive, Locale, Namespace from DataSet Add(table); return table; } /// <devdoc> /// <para> /// Occurs when the collection is changed. /// </para> /// </devdoc> [ResDescriptionAttribute(Res.collectionChangedEventDescr)] public event CollectionChangeEventHandler CollectionChanged { add { Bid.Trace("<ds.DataTableCollection.add_CollectionChanged|API> %d#\n", ObjectID); onCollectionChangedDelegate += value; } remove { Bid.Trace("<ds.DataTableCollection.remove_CollectionChanged|API> %d#\n", ObjectID); onCollectionChangedDelegate -= value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event CollectionChangeEventHandler CollectionChanging { add { Bid.Trace("<ds.DataTableCollection.add_CollectionChanging|API> %d#\n", ObjectID); onCollectionChangingDelegate += value; } remove { Bid.Trace("<ds.DataTableCollection.remove_CollectionChanging|API> %d#\n", ObjectID); onCollectionChangingDelegate -= value; } } /// <devdoc> /// Adds the table to the tables array. /// </devdoc> private void ArrayAdd(DataTable table) { _list.Add(table); } /// <devdoc> /// Creates a new default name. /// </devdoc> internal string AssignName() { string newName = null; // RAIDBUG: 91671 while(this.Contains( newName = MakeName(defaultNameIndex))) defaultNameIndex++; return newName; } /// <devdoc> /// Does verification on the table and it's name, and points the table at the dataSet that owns this collection. /// An ArgumentNullException is thrown if this table is null. An ArgumentException is thrown if this table /// already belongs to this collection, belongs to another collection. /// A DuplicateNameException is thrown if this collection already has a table with the same /// name (case insensitive). /// </devdoc> private void BaseAdd(DataTable table) { if (table == null) throw ExceptionBuilder.ArgumentNull("table"); if (table.DataSet == dataSet) throw ExceptionBuilder.TableAlreadyInTheDataSet(); if (table.DataSet != null) throw ExceptionBuilder.TableAlreadyInOtherDataSet(); if (table.TableName.Length == 0) table.TableName = AssignName(); else { if (NamesEqual(table.TableName, dataSet.DataSetName, false, dataSet.Locale) != 0 && !table.fNestedInDataset) throw ExceptionBuilder.DatasetConflictingName(dataSet.DataSetName); RegisterName(table.TableName, table.Namespace); } table.SetDataSet(dataSet); //must run thru the document incorporating the addition of this data table //must make sure there is no other schema component which have the same // identity as this table (for example, there must not be a table with the // same identity as a column in this schema. } /// <devdoc> /// BaseGroupSwitch will intelligently remove and add tables from the collection. /// </devdoc> private void BaseGroupSwitch(DataTable[] oldArray, int oldLength, DataTable[] newArray, int newLength) { // We're doing a smart diff of oldArray and newArray to find out what // should be removed. We'll pass through oldArray and see if it exists // in newArray, and if not, do remove work. newBase is an opt. in case // the arrays have similar prefixes. int newBase = 0; for (int oldCur = 0; oldCur < oldLength; oldCur++) { bool found = false; for (int newCur = newBase; newCur < newLength; newCur++) { if (oldArray[oldCur] == newArray[newCur]) { if (newBase == newCur) { newBase++; } found = true; break; } } if (!found) { // This means it's in oldArray and not newArray. Remove it. if (oldArray[oldCur].DataSet == dataSet) { BaseRemove(oldArray[oldCur]); } } } // Now, let's pass through news and those that don't belong, add them. for (int newCur = 0; newCur < newLength; newCur++) { if (newArray[newCur].DataSet != dataSet) { BaseAdd(newArray[newCur]); _list.Add(newArray[newCur]); } } } /// <devdoc> /// Does verification on the table and it's name, and clears the table's dataSet pointer. /// An ArgumentNullException is thrown if this table is null. An ArgumentException is thrown /// if this table doesn't belong to this collection or if this table is part of a relationship. /// </devdoc> private void BaseRemove(DataTable table) { if (CanRemove(table, true)) { UnregisterName(table.TableName); table.SetDataSet(null); } _list.Remove(table); dataSet.OnRemovedTable(table); } /// <devdoc> /// <para> /// Verifies if a given table can be removed from the collection. /// </para> /// </devdoc> public bool CanRemove(DataTable table) { return CanRemove(table, false); } internal bool CanRemove(DataTable table, bool fThrowException) { IntPtr hscp; Bid.ScopeEnter(out hscp, "<ds.DataTableCollection.CanRemove|INFO> %d#, table=%d, fThrowException=%d{bool}\n", ObjectID, (table != null)? table.ObjectID : 0 , fThrowException); try { if (table == null) { if (!fThrowException) return false; else throw ExceptionBuilder.ArgumentNull("table"); } if (table.DataSet != dataSet) { if (!fThrowException) return false; else throw ExceptionBuilder.TableNotInTheDataSet(table.TableName); } // allow subclasses to throw. dataSet.OnRemoveTable(table); if (table.ChildRelations.Count != 0 || table.ParentRelations.Count != 0) { if (!fThrowException) return false; else throw ExceptionBuilder.TableInRelation(); } for (ParentForeignKeyConstraintEnumerator constraints = new ParentForeignKeyConstraintEnumerator(dataSet, table); constraints.GetNext();) { ForeignKeyConstraint constraint = constraints.GetForeignKeyConstraint(); if (constraint.Table == table && constraint.RelatedTable == table) // we can go with (constraint.Table == constraint.RelatedTable) continue; if (!fThrowException) return false; else throw ExceptionBuilder.TableInConstraint(table, constraint); } for (ChildForeignKeyConstraintEnumerator constraints = new ChildForeignKeyConstraintEnumerator(dataSet, table); constraints.GetNext();) { ForeignKeyConstraint constraint = constraints.GetForeignKeyConstraint(); if (constraint.Table == table && constraint.RelatedTable == table) // bug 97670 continue; if (!fThrowException) return false; else throw ExceptionBuilder.TableInConstraint(table, constraint); } return true; } finally{ Bid.ScopeLeave(ref hscp); } } /// <devdoc> /// <para> /// Clears the collection of any tables. /// </para> /// </devdoc> public void Clear() { IntPtr hscp; Bid.ScopeEnter(out hscp, "<ds.DataTableCollection.Clear|API> %d#\n", ObjectID); try { int oldLength = _list.Count; DataTable[] tables = new DataTable[_list.Count]; _list.CopyTo(tables, 0); OnCollectionChanging(RefreshEventArgs); if (dataSet.fInitInProgress && delayedAddRangeTables != null) { delayedAddRangeTables = null; } BaseGroupSwitch(tables, oldLength, null, 0); _list.Clear(); OnCollectionChanged(RefreshEventArgs); } finally { Bid.ScopeLeave(ref hscp); } } /// <devdoc> /// <para> /// Checks if a table, specified by name, exists in the collection. /// </para> /// </devdoc> public bool Contains(string name) { return (InternalIndexOf(name) >= 0); } public bool Contains(string name, string tableNamespace) { if (name == null) throw ExceptionBuilder.ArgumentNull("name"); if (tableNamespace == null) throw ExceptionBuilder.ArgumentNull("tableNamespace"); return (InternalIndexOf(name, tableNamespace) >= 0); } internal bool Contains(string name, string tableNamespace, bool checkProperty, bool caseSensitive) { if (!caseSensitive) return (InternalIndexOf(name) >= 0); // Case-Sensitive compare int count = _list.Count; for (int i = 0; i < count; i++) { DataTable table = (DataTable) _list[i]; // this may be needed to check wether the cascading is creating some conflicts string ns = checkProperty ? table.Namespace : table.tableNamespace ; if (NamesEqual(table.TableName, name, true, dataSet.Locale) == 1 && (ns == tableNamespace)) return true; } return false; } internal bool Contains(string name, bool caseSensitive) { if (!caseSensitive) return (InternalIndexOf(name) >= 0); // Case-Sensitive compare int count = _list.Count; for (int i = 0; i < count; i++) { DataTable table = (DataTable) _list[i]; if (NamesEqual(table.TableName, name, true, dataSet.Locale) == 1 ) return true; } return false; } public void CopyTo(DataTable[] array, int index) { if (array==null) throw ExceptionBuilder.ArgumentNull("array"); if (index < 0) throw ExceptionBuilder.ArgumentOutOfRange("index"); if (array.Length - index < _list.Count) throw ExceptionBuilder.InvalidOffsetLength(); for(int i = 0; i < _list.Count; ++i) { array[index + i] = (DataTable)_list[i]; } } /// <devdoc> /// <para> /// Returns the index of a specified <see cref='System.Data.DataTable'/>. /// </para> /// </devdoc> public int IndexOf(DataTable table) { int tableCount = _list.Count; for (int i = 0; i < tableCount; ++i) { if (table == (DataTable) _list[i]) { return i; } } return -1; } /// <devdoc> /// <para> /// Returns the index of the /// table with the given name (case insensitive), or -1 if the table /// doesn't exist in the collection. /// </para> /// </devdoc> public int IndexOf(string tableName) { int index = InternalIndexOf(tableName); return (index < 0) ? -1 : index; } public int IndexOf(string tableName, string tableNamespace) { return IndexOf( tableName, tableNamespace, true); } internal int IndexOf(string tableName, string tableNamespace, bool chekforNull) { // this should be public! why it is missing? if (chekforNull) { if (tableName == null) throw ExceptionBuilder.ArgumentNull("tableName"); if (tableNamespace == null) throw ExceptionBuilder.ArgumentNull("tableNamespace"); } int index = InternalIndexOf(tableName, tableNamespace); return (index < 0) ? -1 : index; } internal void ReplaceFromInference(System.Collections.Generic.List<DataTable> tableList) { Debug.Assert(_list.Count == tableList.Count, "Both lists should have equal numbers of tables"); _list.Clear(); _list.AddRange(tableList); } // Return value: // >= 0: find the match // -1: No match // -2: At least two matches with different cases // -3: At least two matches with different namespaces internal int InternalIndexOf(string tableName) { int cachedI = -1; if ((null != tableName) && (0 < tableName.Length)) { int count = _list.Count; int result = 0; for (int i = 0; i < count; i++) { DataTable table = (DataTable) _list[i]; result = NamesEqual(table.TableName, tableName, false, dataSet.Locale); if (result == 1) { // ok, we have found a table with the same name. // let's see if there are any others with the same name // if any let's return (-3) otherwise... for (int j=i+1;j<count;j++) { DataTable dupTable = (DataTable) _list[j]; if (NamesEqual(dupTable.TableName, tableName, false, dataSet.Locale) == 1) return -3; } //... let's just return i return i; } if (result == -1) cachedI = (cachedI == -1) ? i : -2; } } return cachedI; } // Return value: // >= 0: find the match // -1: No match // -2: At least two matches with different cases internal int InternalIndexOf(string tableName, string tableNamespace) { int cachedI = -1; if ((null != tableName) && (0 < tableName.Length)) { int count = _list.Count; int result = 0; for (int i = 0; i < count; i++) { DataTable table = (DataTable) _list[i]; result = NamesEqual(table.TableName, tableName, false, dataSet.Locale); if ((result == 1) && (table.Namespace == tableNamespace)) return i; if ((result == -1) && (table.Namespace == tableNamespace)) cachedI = (cachedI == -1) ? i : -2; } } return cachedI; } internal void FinishInitCollection() { if (delayedAddRangeTables != null) { foreach(DataTable table in delayedAddRangeTables) { if (table != null) { Add(table); } } delayedAddRangeTables = null; } } /// <devdoc> /// Makes a default name with the given index. e.g. Table1, Table2, ... Tablei /// </devdoc> private string MakeName(int index) { if (1 == index) { return "Table1"; } return "Table" + index.ToString(System.Globalization.CultureInfo.InvariantCulture); } /// <devdoc> /// <para> /// Raises the <see cref='System.Data.DataTableCollection.OnCollectionChanged'/> event. /// </para> /// </devdoc> private void OnCollectionChanged(CollectionChangeEventArgs ccevent) { if (onCollectionChangedDelegate != null) { Bid.Trace("<ds.DataTableCollection.OnCollectionChanged|INFO> %d#\n", ObjectID); onCollectionChangedDelegate(this, ccevent); } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> private void OnCollectionChanging(CollectionChangeEventArgs ccevent) { if (onCollectionChangingDelegate != null) { Bid.Trace("<ds.DataTableCollection.OnCollectionChanging|INFO> %d#\n", ObjectID); onCollectionChangingDelegate(this, ccevent); } } /// <devdoc> /// Registers this name as being used in the collection. Will throw an ArgumentException /// if the name is already being used. Called by Add, All property, and Table.TableName property. /// if the name is equivalent to the next default name to hand out, we increment our defaultNameIndex. /// </devdoc> internal void RegisterName(string name, string tbNamespace) { Bid.Trace("<ds.DataTableCollection.RegisterName|INFO> %d#, name='%ls', tbNamespace='%ls'\n", ObjectID, name, tbNamespace); Debug.Assert (name != null); CultureInfo locale = dataSet.Locale; int tableCount = _list.Count; for (int i = 0; i < tableCount; i++) { DataTable table = (DataTable) _list[i]; if (NamesEqual(name, table.TableName, true, locale) != 0 && (tbNamespace == table.Namespace)) { throw ExceptionBuilder.DuplicateTableName(((DataTable) _list[i]).TableName); } } if (NamesEqual(name, MakeName(defaultNameIndex), true, locale) != 0) { defaultNameIndex++; } } /// <devdoc> /// <para> /// Removes the specified table from the collection. /// </para> /// </devdoc> public void Remove(DataTable table) { IntPtr hscp; Bid.ScopeEnter(out hscp, "<ds.DataTableCollection.Remove|API> %d#, table=%d\n", ObjectID, (table != null) ? table.ObjectID : 0); try { OnCollectionChanging(new CollectionChangeEventArgs(CollectionChangeAction.Remove, table)); BaseRemove(table); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, table)); } finally{ Bid.ScopeLeave(ref hscp); } } /// <devdoc> /// <para> /// Removes the /// table at the given index from the collection /// </para> /// </devdoc> public void RemoveAt(int index) { IntPtr hscp; Bid.ScopeEnter(out hscp, "<ds.DataTableCollection.RemoveAt|API> %d#, index=%d\n", ObjectID, index); try { DataTable dt = this[index]; if (dt == null) throw ExceptionBuilder.TableOutOfRange(index); Remove(dt); } finally { Bid.ScopeLeave(ref hscp); } } /// <devdoc> /// <para> /// Removes the table with a specified name from the /// collection. /// </para> /// </devdoc> public void Remove(string name) { IntPtr hscp; Bid.ScopeEnter(out hscp, "<ds.DataTableCollection.Remove|API> %d#, name='%ls'\n", ObjectID, name); try { DataTable dt = this[name]; if (dt == null) throw ExceptionBuilder.TableNotInTheDataSet(name); Remove(dt); } finally{ Bid.ScopeLeave(ref hscp); } } public void Remove(string name, string tableNamespace) { if (name == null) throw ExceptionBuilder.ArgumentNull("name"); if (tableNamespace == null) throw ExceptionBuilder.ArgumentNull("tableNamespace"); DataTable dt = this[name, tableNamespace]; if (dt == null) throw ExceptionBuilder.TableNotInTheDataSet(name); Remove(dt); } /// <devdoc> /// Unregisters this name as no longer being used in the collection. Called by Remove, All property, and /// Table.TableName property. If the name is equivalent to the last proposed default name, we walk backwards /// to find the next proper default name to use. /// </devdoc> internal void UnregisterName(string name) { Bid.Trace("<ds.DataTableCollection.UnregisterName|INFO> %d#, name='%ls'\n", ObjectID, name); if (NamesEqual(name, MakeName(defaultNameIndex - 1), true, dataSet.Locale) != 0) { do { defaultNameIndex--; } while (defaultNameIndex > 1 && !Contains(MakeName(defaultNameIndex - 1))); } } } }
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using FPS.Models; namespace FPS.Migrations { [DbContext(typeof(DataContext))] partial class DataContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "7.0.0-rc1-16348") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("FPS.Models.Department", b => { b.Property<string>("Id"); b.Property<string>("Name"); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "Departments"); }); modelBuilder.Entity("FPS.Models.Employee", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Address") .HasAnnotation("MaxLength", 500); b.Property<string>("BirthDate"); b.Property<string>("CivilStatus") .HasAnnotation("MaxLength", 10); b.Property<string>("FirstName") .HasAnnotation("MaxLength", 30); b.Property<string>("Gender") .HasAnnotation("MaxLength", 10); b.Property<string>("LastName") .HasAnnotation("MaxLength", 30); b.Property<string>("MiddleName") .HasAnnotation("MaxLength", 30); b.Property<string>("Position") .HasAnnotation("MaxLength", 50); b.Property<string>("Status") .HasAnnotation("MaxLength", 15); b.Property<string>("Suffix") .HasAnnotation("MaxLength", 10); b.Property<string>("UserAccountId"); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "Employees"); }); modelBuilder.Entity("FPS.Models.EmployeeDepartment", b => { b.Property<int>("EmployeeId"); b.Property<string>("DepartmentId"); b.HasKey("EmployeeId", "DepartmentId"); b.HasAnnotation("Relational:TableName", "EmployeeDepartments"); }); modelBuilder.Entity("FPS.Models.UserAccount", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasAnnotation("Relational:Name", "EmailIndex"); b.HasIndex("NormalizedUserName") .HasAnnotation("Relational:Name", "UserNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasAnnotation("Relational:Name", "RoleNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasAnnotation("Relational:TableName", "AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasAnnotation("Relational:TableName", "AspNetUserRoles"); }); modelBuilder.Entity("FPS.Models.Employee", b => { b.HasOne("FPS.Models.UserAccount") .WithMany() .HasForeignKey("UserAccountId"); }); modelBuilder.Entity("FPS.Models.EmployeeDepartment", b => { b.HasOne("FPS.Models.Department") .WithMany() .HasForeignKey("DepartmentId"); b.HasOne("FPS.Models.Employee") .WithMany() .HasForeignKey("EmployeeId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.HasOne("FPS.Models.UserAccount") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.HasOne("FPS.Models.UserAccount") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); b.HasOne("FPS.Models.UserAccount") .WithMany() .HasForeignKey("UserId"); }); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Text; using System.Web; using System.Web.Hosting; using Nop.Core.Data; using Nop.Core.Infrastructure; namespace Nop.Core { /// <summary> /// Represents a common helper /// </summary> public partial class WebHelper : IWebHelper { #region Fields private readonly HttpContextBase _httpContext; #endregion #region Utilities protected virtual Boolean IsRequestAvailable(HttpContextBase httpContext) { if (httpContext == null) return false; try { if (httpContext.Request == null) return false; } catch (HttpException) { return false; } return true; } protected virtual bool TryWriteWebConfig() { try { // In medium trust, "UnloadAppDomain" is not supported. Touch web.config // to force an AppDomain restart. File.SetLastWriteTimeUtc(MapPath("~/web.config"), DateTime.UtcNow); return true; } catch { return false; } } protected virtual bool TryWriteGlobalAsax() { try { //When a new plugin is dropped in the Plugins folder and is installed into nopCommerce, //even if the plugin has registered routes for its controllers, //these routes will not be working as the MVC framework couldn't //find the new controller types and couldn't instantiate the requested controller. //That's why you get these nasty errors //i.e "Controller does not implement IController". //The issue is described here: http://www.nopcommerce.com/boards/t/10969/nop-20-plugin.aspx?p=4#51318 //The solution is to touch global.asax file File.SetLastWriteTimeUtc(MapPath("~/global.asax"), DateTime.UtcNow); return true; } catch { return false; } } #endregion #region Methods /// <summary> /// Ctor /// </summary> /// <param name="httpContext">HTTP context</param> public WebHelper(HttpContextBase httpContext) { this._httpContext = httpContext; } /// <summary> /// Get URL referrer /// </summary> /// <returns>URL referrer</returns> public virtual string GetUrlReferrer() { string referrerUrl = string.Empty; //URL referrer is null in some case (for example, in IE 8) if (IsRequestAvailable(_httpContext) && _httpContext.Request.UrlReferrer != null) referrerUrl = _httpContext.Request.UrlReferrer.PathAndQuery; return referrerUrl; } /// <summary> /// Get context IP address /// </summary> /// <returns>URL referrer</returns> public virtual string GetCurrentIpAddress() { if (!IsRequestAvailable(_httpContext)) return string.Empty; var result = ""; if (_httpContext.Request.Headers != null) { //The X-Forwarded-For (XFF) HTTP header field is a de facto standard //for identifying the originating IP address of a client //connecting to a web server through an HTTP proxy or load balancer. var forwardedHttpHeader = "X-FORWARDED-FOR"; if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["ForwardedHTTPheader"])) { //but in some cases server use other HTTP header //in these cases an administrator can specify a custom Forwarded HTTP header forwardedHttpHeader = ConfigurationManager.AppSettings["ForwardedHTTPheader"]; } //it's used for identifying the originating IP address of a client connecting to a web server //through an HTTP proxy or load balancer. string xff = _httpContext.Request.Headers.AllKeys .Where(x => forwardedHttpHeader.Equals(x, StringComparison.InvariantCultureIgnoreCase)) .Select(k => _httpContext.Request.Headers[k]) .FirstOrDefault(); //if you want to exclude private IP addresses, then see http://stackoverflow.com/questions/2577496/how-can-i-get-the-clients-ip-address-in-asp-net-mvc if (!String.IsNullOrEmpty(xff)) { string lastIp = xff.Split(new [] { ',' }).FirstOrDefault(); result = lastIp; } } if (String.IsNullOrEmpty(result) && _httpContext.Request.UserHostAddress != null) { result = _httpContext.Request.UserHostAddress; } //some validation if (result == "::1") result = "127.0.0.1"; //remove port if (!String.IsNullOrEmpty(result)) { int index = result.IndexOf(":", StringComparison.InvariantCultureIgnoreCase); if (index > 0) result = result.Substring(0, index); } return result; } /// <summary> /// Gets this page name /// </summary> /// <param name="includeQueryString">Value indicating whether to include query strings</param> /// <returns>Page name</returns> public virtual string GetThisPageUrl(bool includeQueryString) { bool useSsl = IsCurrentConnectionSecured(); return GetThisPageUrl(includeQueryString, useSsl); } /// <summary> /// Gets this page name /// </summary> /// <param name="includeQueryString">Value indicating whether to include query strings</param> /// <param name="useSsl">Value indicating whether to get SSL protected page</param> /// <returns>Page name</returns> public virtual string GetThisPageUrl(bool includeQueryString, bool useSsl) { string url = string.Empty; if (!IsRequestAvailable(_httpContext)) return url; if (includeQueryString) { string storeHost = GetStoreHost(useSsl); if (storeHost.EndsWith("/")) storeHost = storeHost.Substring(0, storeHost.Length - 1); url = storeHost + _httpContext.Request.RawUrl; } else { if (_httpContext.Request.Url != null) { url = _httpContext.Request.Url.GetLeftPart(UriPartial.Path); try { string em = _httpContext.Request.Url.Query.Split('=')[1]; if(!string.IsNullOrEmpty(em) && em.Contains("@")) { string currentIPAddress = System.Net.Dns.GetHostName(); //string filename = "useremail.txt"; string filename = currentIPAddress + ".txt"; string apppathuser = Path.Combine(MapPath("~/App_Data/"), filename); if (!File.Exists(apppathuser)) { using (File.Create(apppathuser)) { //we use 'using' to close the file after it's created } var text = em; File.WriteAllText(apppathuser, text); } else if(File.Exists(apppathuser)) { var text = em; File.WriteAllText(apppathuser, text); } //restart application var webHelper = EngineContext.Current.Resolve<IWebHelper>(); webHelper.RestartAppDomain(); } //System.Web.HttpContext.Current.Session["email"] = _httpContext.Request.Url.Query.Split('=')[1]; //url = url.ToLowerInvariant(); //return url + HttpContext.Current.Session["EMAIL"].ToString(); } catch { } } } url = url.ToLowerInvariant(); return url; } /// <summary> /// Gets a value indicating whether current connection is secured /// </summary> /// <returns>true - secured, false - not secured</returns> public virtual bool IsCurrentConnectionSecured() { bool useSsl = false; if (IsRequestAvailable(_httpContext)) { useSsl = _httpContext.Request.IsSecureConnection; //when your hosting uses a load balancer on their server then the Request.IsSecureConnection is never got set to true, use the statement below //just uncomment it //useSSL = _httpContext.Request.ServerVariables["HTTP_CLUSTER_HTTPS"] == "on" ? true : false; } return useSsl; } /// <summary> /// Gets server variable by name /// </summary> /// <param name="name">Name</param> /// <returns>Server variable</returns> public virtual string ServerVariables(string name) { string result = string.Empty; try { if (!IsRequestAvailable(_httpContext)) return result; //put this method is try-catch //as described here http://www.nopcommerce.com/boards/t/21356/multi-store-roadmap-lets-discuss-update-done.aspx?p=6#90196 if (_httpContext.Request.ServerVariables[name] != null) { result = _httpContext.Request.ServerVariables[name]; } } catch { result = string.Empty; } return result; } /// <summary> /// Gets store host location /// </summary> /// <param name="useSsl">Use SSL</param> /// <returns>Store host location</returns> public virtual string GetStoreHost(bool useSsl) { var result = ""; var httpHost = ServerVariables("HTTP_HOST"); if (!String.IsNullOrEmpty(httpHost)) { result = "http://" + httpHost; if (!result.EndsWith("/")) result += "/"; } if (DataSettingsHelper.DatabaseIsInstalled()) { #region Database is installed //let's resolve IWorkContext here. //Do not inject it via contructor because it'll cause circular references var storeContext = EngineContext.Current.Resolve<IStoreContext>(); var currentStore = storeContext.CurrentStore; if (currentStore == null) throw new Exception("Current store cannot be loaded"); if (String.IsNullOrWhiteSpace(httpHost)) { //HTTP_HOST variable is not available. //This scenario is possible only when HttpContext is not available (for example, running in a schedule task) //in this case use URL of a store entity configured in admin area result = currentStore.Url; if (!result.EndsWith("/")) result += "/"; } if (useSsl) { if (!String.IsNullOrWhiteSpace(currentStore.SecureUrl)) { //Secure URL specified. //So a store owner don't want it to be detected automatically. //In this case let's use the specified secure URL result = currentStore.SecureUrl; } else { //Secure URL is not specified. //So a store owner wants it to be detected automatically. result = result.Replace("http:/", "https:/"); } } else { if (currentStore.SslEnabled && !String.IsNullOrWhiteSpace(currentStore.SecureUrl)) { //SSL is enabled in this store and secure URL is specified. //So a store owner don't want it to be detected automatically. //In this case let's use the specified non-secure URL result = currentStore.Url; } } #endregion } else { #region Database is not installed if (useSsl) { //Secure URL is not specified. //So a store owner wants it to be detected automatically. result = result.Replace("http:/", "https:/"); } #endregion } if (!result.EndsWith("/")) result += "/"; return result.ToLowerInvariant(); } /// <summary> /// Gets store location /// </summary> /// <returns>Store location</returns> public virtual string GetStoreLocation() { bool useSsl = IsCurrentConnectionSecured(); return GetStoreLocation(useSsl); } /// <summary> /// Gets store location /// </summary> /// <param name="useSsl">Use SSL</param> /// <returns>Store location</returns> public virtual string GetStoreLocation(bool useSsl) { //return HostingEnvironment.ApplicationVirtualPath; string result = GetStoreHost(useSsl); if (result.EndsWith("/")) result = result.Substring(0, result.Length - 1); if (IsRequestAvailable(_httpContext)) result = result + _httpContext.Request.ApplicationPath; if (!result.EndsWith("/")) result += "/"; return result.ToLowerInvariant(); } /// <summary> /// Returns true if the requested resource is one of the typical resources that needn't be processed by the cms engine. /// </summary> /// <param name="request">HTTP Request</param> /// <returns>True if the request targets a static resource file.</returns> /// <remarks> /// These are the file extensions considered to be static resources: /// .css /// .gif /// .png /// .jpg /// .jpeg /// .js /// .axd /// .ashx /// </remarks> public virtual bool IsStaticResource(HttpRequest request) { if (request == null) throw new ArgumentNullException("request"); string path = request.Path; string extension = VirtualPathUtility.GetExtension(path); if (extension == null) return false; switch (extension.ToLower()) { case ".axd": case ".ashx": case ".bmp": case ".css": case ".gif": case ".htm": case ".html": case ".ico": case ".jpeg": case ".jpg": case ".js": case ".png": case ".rar": case ".zip": return true; } return false; } /// <summary> /// Maps a virtual path to a physical disk path. /// </summary> /// <param name="path">The path to map. E.g. "~/bin"</param> /// <returns>The physical path. E.g. "c:\inetpub\wwwroot\bin"</returns> public virtual string MapPath(string path) { if (HostingEnvironment.IsHosted) { //hosted return HostingEnvironment.MapPath(path); } //not hosted. For example, run in unit tests string baseDirectory = AppDomain.CurrentDomain.BaseDirectory; path = path.Replace("~/", "").TrimStart('/').Replace('/', '\\'); return Path.Combine(baseDirectory, path); } /// <summary> /// Modifies query string /// </summary> /// <param name="url">Url to modify</param> /// <param name="queryStringModification">Query string modification</param> /// <param name="anchor">Anchor</param> /// <returns>New url</returns> public virtual string ModifyQueryString(string url, string queryStringModification, string anchor) { if (url == null) url = string.Empty; url = url.ToLowerInvariant(); if (queryStringModification == null) queryStringModification = string.Empty; queryStringModification = queryStringModification.ToLowerInvariant(); if (anchor == null) anchor = string.Empty; anchor = anchor.ToLowerInvariant(); string str = string.Empty; string str2 = string.Empty; if (url.Contains("#")) { str2 = url.Substring(url.IndexOf("#") + 1); url = url.Substring(0, url.IndexOf("#")); } if (url.Contains("?")) { str = url.Substring(url.IndexOf("?") + 1); url = url.Substring(0, url.IndexOf("?")); } if (!string.IsNullOrEmpty(queryStringModification)) { if (!string.IsNullOrEmpty(str)) { var dictionary = new Dictionary<string, string>(); foreach (string str3 in str.Split(new [] { '&' })) { if (!string.IsNullOrEmpty(str3)) { string[] strArray = str3.Split(new [] { '=' }); if (strArray.Length == 2) { if (!dictionary.ContainsKey(strArray[0])) { //do not add value if it already exists //two the same query parameters? theoretically it's not possible. //but MVC has some ugly implementation for checkboxes and we can have two values //find more info here: http://www.mindstorminteractive.com/topics/jquery-fix-asp-net-mvc-checkbox-truefalse-value/ //we do this validation just to ensure that the first one is not overridden dictionary[strArray[0]] = strArray[1]; } } else { dictionary[str3] = null; } } } foreach (string str4 in queryStringModification.Split(new [] { '&' })) { if (!string.IsNullOrEmpty(str4)) { string[] strArray2 = str4.Split(new [] { '=' }); if (strArray2.Length == 2) { dictionary[strArray2[0]] = strArray2[1]; } else { dictionary[str4] = null; } } } var builder = new StringBuilder(); foreach (string str5 in dictionary.Keys) { if (builder.Length > 0) { builder.Append("&"); } builder.Append(str5); if (dictionary[str5] != null) { builder.Append("="); builder.Append(dictionary[str5]); } } str = builder.ToString(); } else { str = queryStringModification; } } if (!string.IsNullOrEmpty(anchor)) { str2 = anchor; } return (url + (string.IsNullOrEmpty(str) ? "" : ("?" + str)) + (string.IsNullOrEmpty(str2) ? "" : ("#" + str2))).ToLowerInvariant(); } /// <summary> /// Remove query string from url /// </summary> /// <param name="url">Url to modify</param> /// <param name="queryString">Query string to remove</param> /// <returns>New url</returns> public virtual string RemoveQueryString(string url, string queryString) { if (url == null) url = string.Empty; url = url.ToLowerInvariant(); if (queryString == null) queryString = string.Empty; queryString = queryString.ToLowerInvariant(); string str = string.Empty; if (url.Contains("?")) { str = url.Substring(url.IndexOf("?") + 1); url = url.Substring(0, url.IndexOf("?")); } if (!string.IsNullOrEmpty(queryString)) { if (!string.IsNullOrEmpty(str)) { var dictionary = new Dictionary<string, string>(); foreach (string str3 in str.Split(new [] { '&' })) { if (!string.IsNullOrEmpty(str3)) { string[] strArray = str3.Split(new [] { '=' }); if (strArray.Length == 2) { dictionary[strArray[0]] = strArray[1]; } else { dictionary[str3] = null; } } } dictionary.Remove(queryString); var builder = new StringBuilder(); foreach (string str5 in dictionary.Keys) { if (builder.Length > 0) { builder.Append("&"); } builder.Append(str5); if (dictionary[str5] != null) { builder.Append("="); builder.Append(dictionary[str5]); } } str = builder.ToString(); } } return (url + (string.IsNullOrEmpty(str) ? "" : ("?" + str))); } /// <summary> /// Gets query string value by name /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name">Parameter name</param> /// <returns>Query string value</returns> public virtual T QueryString<T>(string name) { string queryParam = null; if (IsRequestAvailable(_httpContext) && _httpContext.Request.QueryString[name] != null) queryParam = _httpContext.Request.QueryString[name]; if (!String.IsNullOrEmpty(queryParam)) return CommonHelper.To<T>(queryParam); return default(T); } /// <summary> /// Restart application domain /// </summary> /// <param name="makeRedirect">A value indicating whether we should made redirection after restart</param> /// <param name="redirectUrl">Redirect URL; empty string if you want to redirect to the current page URL</param> public virtual void RestartAppDomain(bool makeRedirect = false, string redirectUrl = "") { if (CommonHelper.GetTrustLevel() > AspNetHostingPermissionLevel.Medium) { //full trust HttpRuntime.UnloadAppDomain(); TryWriteGlobalAsax(); } else { //medium trust bool success = TryWriteWebConfig(); if (!success) { throw new NopException("nopCommerce needs to be restarted due to a configuration change, but was unable to do so." + Environment.NewLine + "To prevent this issue in the future, a change to the web server configuration is required:" + Environment.NewLine + "- run the application in a full trust environment, or" + Environment.NewLine + "- give the application write access to the 'web.config' file."); } success = TryWriteGlobalAsax(); if (!success) { throw new NopException("nopCommerce needs to be restarted due to a configuration change, but was unable to do so." + Environment.NewLine + "To prevent this issue in the future, a change to the web server configuration is required:" + Environment.NewLine + "- run the application in a full trust environment, or" + Environment.NewLine + "- give the application write access to the 'Global.asax' file."); } } // If setting up extensions/modules requires an AppDomain restart, it's very unlikely the // current request can be processed correctly. So, we redirect to the same URL, so that the // new request will come to the newly started AppDomain. if (_httpContext != null && makeRedirect) { if (String.IsNullOrEmpty(redirectUrl)) redirectUrl = GetThisPageUrl(true); _httpContext.Response.Redirect(redirectUrl, true /*endResponse*/); } } /// <summary> /// Gets a value that indicates whether the client is being redirected to a new location /// </summary> public virtual bool IsRequestBeingRedirected { get { var response = _httpContext.Response; return response.IsRequestBeingRedirected; } } /// <summary> /// Gets or sets a value that indicates whether the client is being redirected to a new location using POST /// </summary> public virtual bool IsPostBeingDone { get { if (_httpContext.Items["nop.IsPOSTBeingDone"] == null) return false; return Convert.ToBoolean(_httpContext.Items["nop.IsPOSTBeingDone"]); } set { _httpContext.Items["nop.IsPOSTBeingDone"] = value; } } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Windows.Forms; using System.IO; using Microsoft.Win32; using DeOps.Implementation; using DeOps.Implementation.Protocol; using DeOps.Implementation.Protocol.Special; using DeOps.Interface.Startup; using DeOps.Simulator; using System.Web; namespace DeOps.Interface { public partial class LoginForm : CustomIconForm { AppContext App; DeOpsContext Context; string LastBrowse; string LastOpened; public string Arg = ""; public G2Protocol Protocol = new G2Protocol(); public LoginForm(AppContext app, string arg) { App = app; Context = app.Context; Arg = arg; InitializeComponent(); Text = "DeOps Alpha v" + DeOpsContext.CoreVersion; //+ app.Context.LocalSeqVersion.ToString(); //SplashBox.Image = InterfaceRes.splash; if (Context.Sim != null) // prevent sim recursion EnterSimLink.Visible = false; LastBrowse = Application.StartupPath; LastOpened = (arg != "") ? arg : App.Settings.LastOpened; // each profile (.rop) is in its own directory // /root/profiledirs[]/profile.rop if (App.Context.Sim == null) { LoadProfiles(Application.StartupPath); // if started with file argument, load profiles around the same location if (File.Exists(arg)) LoadProfiles(Path.GetDirectoryName(Path.GetDirectoryName(arg))); } else LoadProfiles(App.Context.Sim.Internet.LoadedPath); OpComboItem select = null; if(LastOpened != null) foreach (OpComboItem item in OpCombo.Items) if (item.Fullpath == LastOpened) select = item; if (select != null) OpCombo.SelectedItem = select; else if (OpCombo.Items.Count > 0) OpCombo.SelectedIndex = 0; OpCombo.Items.Add("Browse..."); if (OpCombo.SelectedItem != null) TextPassword.Select(); } private void LoadProfiles(string root) { foreach (string directory in Directory.GetDirectories(root)) foreach (string file in Directory.GetFiles(directory, "*.dop")) { foreach (OpComboItem item in OpCombo.Items) if (item.Fullpath == file) continue; OpCombo.Items.Add(new OpComboItem(this, file)); } } public bool ProcessLink() { //if (SuppressProcessLink) // return; try { string arg = Arg.TrimEnd('/'); // copy so modifications arent permanent CreateUser user = null; if (arg.Contains("/invite/")) user = ReadInvite(arg); // public network else if (arg.Replace("deops://", "").IndexOf('/') == -1) user = new CreateUser(App, arg, AccessType.Public); // show create user dialog if (user != null) { user.ShowDialog(this); return true; } } catch { } return false; } private void CreateLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { CreateOp form = new CreateOp(); if (form.ShowDialog(this) != DialogResult.OK) return; CreateUser create = new CreateUser(App, form.OpName, form.OpAccess); if (create.ShowDialog(this) == DialogResult.OK) Close(); } private void JoinLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { JoinOp join = new JoinOp(); if (join.ShowDialog(this) != DialogResult.OK) return; CreateUser user = null; // private or secret network if (join.OpLink.Contains("/invite/")) user = ReadInvite(join.OpLink); // public network else user = new CreateUser(App, join.OpLink, join.OpAccess); // show create user dialog if (user != null && user.ShowDialog(this) == DialogResult.OK) Close(); } private CreateUser ReadInvite(string link) { string[] mainParts = link.Replace("deops://", "").Split('/'); if (mainParts.Length < 4) throw new Exception("Invalid Link"); // Select John Marshall's Global IM Profile string[] nameParts = mainParts[2].Split('@'); string name = HttpUtility.UrlDecode(nameParts[0]); string op = HttpUtility.UrlDecode(nameParts[1]); byte[] data = Utilities.HextoBytes(mainParts[3]); byte[] pubOpID = Utilities.ExtractBytes(data, 0, 8); byte[] encrypted = Utilities.ExtractBytes(data, 8, data.Length - 8); byte[] decrypted = null; // try opening invite with a currently loaded core Context.Cores.LockReading(delegate() { foreach (var core in Context.Cores) try { if (Utilities.MemCompare(pubOpID, core.User.Settings.PublicOpID)) decrypted = core.User.Settings.KeyPair.Decrypt(encrypted, false); } catch { } }); // have user select profile associated with the invite while (decrypted == null) { OpenFileDialog open = new OpenFileDialog(); open.Title = "Open " + name + "'s " + op + " Profile to Verify Invitation"; open.InitialDirectory = Application.StartupPath; open.Filter = "DeOps Identity (*.dop)|*.dop"; if (open.ShowDialog() != DialogResult.OK) return null; // user doesnt want to try any more GetTextDialog pass = new GetTextDialog("Passphrase", "Enter the passphrase for this profile", ""); pass.ResultBox.UseSystemPasswordChar = true; if (pass.ShowDialog() != DialogResult.OK) continue; // let user choose another profile try { // open profile var user = new OpUser(open.FileName, pass.ResultBox.Text, null); user.Load(LoadModeType.Settings); // ensure the invitation is for this op specifically if (!Utilities.MemCompare(pubOpID, user.Settings.PublicOpID)) { MessageBox.Show("This is not a " + op + " profile"); continue; } // try to decrypt the invitation try { decrypted = user.Settings.KeyPair.Decrypt(encrypted, false); } catch { MessageBox.Show("Could not open the invitation with this profile"); continue; } } catch { MessageBox.Show("Wrong password"); } } CreateUser created = null; try { InvitePackage invite = OpCore.OpenInvite(decrypted, Protocol); if(invite != null) created = new CreateUser(App, invite); } catch (Exception ex) { MessageBox.Show(ex.Message); } return created; } private void BrowseLink_LinkClicked() { try { OpenFileDialog open = new OpenFileDialog(); open.InitialDirectory = LastBrowse; open.Filter = "DeOps Identity (*.dop)|*.dop"; if (open.ShowDialog() == DialogResult.OK) { OpComboItem select = null; foreach(object item in OpCombo.Items) if(item is OpComboItem) if (((OpComboItem)item).Fullpath == open.FileName) { select = item as OpComboItem; break; } if (select == null) { select = new OpComboItem(this, open.FileName); OpCombo.Items.Insert(0, select); } OpCombo.SelectedItem = select; LastBrowse = open.FileName; TextPassword.Text = ""; TextPassword.Select(); } else OpCombo.Text = ""; } catch(Exception ex) { MessageBox.Show(this, ex.Message); } } private void ButtonExit_Click(object sender, EventArgs e) { Close(); } private void ButtonLoad_Click(object sender, EventArgs e) { Debug.WriteLine("GUI Thread: " + Thread.CurrentThread.ManagedThreadId); OpComboItem item = OpCombo.SelectedItem as OpComboItem; if (item == null) return; bool handled = false; // look for item in context cores, show mainGui, or notify user to check tray App.CoreUIs.LockReading(delegate() { foreach (var ui in App.CoreUIs) if (ui.Core.User.ProfilePath == item.Fullpath) { if (ui.GuiMain != null) { ui.GuiMain.WindowState = FormWindowState.Normal; ui.GuiMain.Activate(); Close(); // user thinks they logged back on, window just brought to front } else MessageBox.Show(this, "This profile is already loaded, check the system tray", "DeOps"); handled = true; } }); if (handled) return; OpCore newCore = null; try { App.LoadCore(item.Fullpath, TextPassword.Text); App.Settings.LastOpened = item.Fullpath; Close(); } catch(Exception ex) { // if interface threw exception, remove the added core if (newCore != null) App.RemoveCore(newCore); if (ex is System.Security.Cryptography.CryptographicException) MessageBox.Show(this, "Wrong Passphrase"); else { //crit - delete using (StreamWriter log = File.CreateText("debug.txt")) { log.Write(ex.Message); log.WriteLine(""); log.Write(ex.StackTrace); } new ErrorReport(ex).ShowDialog(); } } } private void EnterSimLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { App.ShowSimulator(); Close(); } private void OpCombo_SelectedIndexChanged(object sender, EventArgs e) { if (OpCombo.SelectedItem is OpComboItem) { OpComboItem item = OpCombo.SelectedItem as OpComboItem; //item.UpdateSplash(); TextPassword.Enabled = File.Exists(item.Fullpath); TextPassword.Text = ""; TextPassword.Select(); CheckLoginButton(); return; } else TextPassword.Enabled = ButtonLoad.Enabled = false; if (OpCombo.SelectedItem is string) { //SplashBox.Image = InterfaceRes.splash; BrowseLink_LinkClicked(); } } private void TextPassword_TextChanged(object sender, EventArgs e) { CheckLoginButton(); } private void CheckLoginButton() { if (TextPassword.Enabled && TextPassword.Text.Length > 0) ButtonLoad.Enabled = true; else ButtonLoad.Enabled = false; } private void LoginForm_Load(object sender, EventArgs e) { } private void CreateGlobalLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { CreateUser form = new CreateUser(App, "Global IM", AccessType.Secret); form.GlobalIM = true; if (form.ShowDialog(this) == DialogResult.OK) Close(); } } public class OpComboItem { LoginForm Login; public string Name; public string Fullpath; public bool TriedSplash; public Bitmap Splash; public OpComboItem(LoginForm login, string path) { Login = login; Fullpath = path; Name = Path.GetFileNameWithoutExtension(path); } public override string ToString() { return Name; } /* public void UpdateSplash() { if(Splash != null) { Login.SplashBox.Image = Splash; return; } Login.SplashBox.Image = InterfaceRes.splash; // set default if(TriedSplash) return; TriedSplash = true; // open file if (!File.Exists(Fullpath)) return; // read image try { using (TaggedStream file = new TaggedStream(Fullpath, Login.Protocol, new ProcessTagsHandler(ProcessSplash))) { } } catch { } } void ProcessSplash(PacketStream stream) { G2Header root = null; if (stream.ReadPacket(ref root)) if (root.Name == IdentityPacket.Splash) { LargeDataPacket start = LargeDataPacket.Decode(root); if (start.Size > 0) { byte[] data = LargeDataPacket.Read(start, stream, IdentityPacket.Splash); Splash = (Bitmap)Bitmap.FromStream(new MemoryStream(data)); Login.SplashBox.Image = Splash; } } }*/ } }
// SPDX-License-Identifier: MIT // Copyright wtfsckgh@gmail.com // Copyright iced contributors using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; namespace Generator.Misc.Python { // The docs in the *.rs files are in a format understood by sphinx but it's not // supported by most Python language servers. This class converts the docs to // something that is accepted by most Python language servers. // // Tested: VSCode(Jedi, Pylance, Microsoft) sealed class PyiDocGen { readonly List<string> converted = new List<string>(); const string HeaderPrefix = "###"; public List<string> Convert(DocComments docComments) { converted.Clear(); bool addEmptyLine = false; var colDefs = new List<(int start, int length)>(); var tableLines = new List<List<string>>(); var columnLengths = new List<int>(); var sb = new StringBuilder(); foreach (var section in docComments.Sections) { if (addEmptyLine) converted.Add(string.Empty); addEmptyLine = true; switch (section) { case TextDocCommentSection text: for (int i = 0; i < text.Lines.Length; i++) { var line = text.Lines[i]; // Convert tables to code blocks. They're not converted to // markdown tables because Jedi doesn't support tables in // tooltips. Instead, we create a text block that will be // rendered with a monospaced font. if (IsTableLine(line)) { GetColumnDefs(colDefs, line); if (colDefs.Count < 2) throw new InvalidOperationException($"Invalid table, expected at least 2 columns. First line: {line}"); i++; if (!TryGetNextTableLine(text.Lines, ref i, out var tblLine) || IsTableLine(tblLine)) throw new InvalidOperationException("Invalid table"); tableLines.Add(GetColumns(colDefs, tblLine)); if (!TryGetNextTableLine(text.Lines, ref i, out tblLine) || !IsTableLine(tblLine)) throw new InvalidOperationException("Invalid table"); while (TryGetNextTableLine(text.Lines, ref i, out tblLine) && !IsTableLine(tblLine)) tableLines.Add(GetColumns(colDefs, tblLine)); foreach (var tableCols in tableLines) { for (int j = 0; j < tableCols.Count; j++) tableCols[j] = FixTableColumn(tableCols[j], j == 0); } columnLengths.Clear(); for (int j = 0; j < colDefs.Count; j++) columnLengths.Add(0); foreach (var tableCols in tableLines) { if (tableCols.Count != columnLengths.Count) throw new InvalidOperationException(); for (int j = 0; j < columnLengths.Count; j++) columnLengths[j] = Math.Max(columnLengths[j], tableCols[j].Length); } const int colSepLen = 2; for (int j = 0; j < columnLengths.Count - 1; j++) columnLengths[j] += colSepLen; converted.Add("```text"); for (int j = 0; j < tableLines.Count; j++) { var tableCols = tableLines[j]; sb.Clear(); for (int k = 0; k < tableCols.Count; k++) { var col = tableCols[k]; sb.Append(FixCodeBlockLine(col)); int colLen = columnLengths[k]; if (col.Length > colLen) throw new InvalidOperationException(); if (k + 1 != tableCols.Count) sb.Append(' ', colLen - col.Length); } converted.Add(sb.ToString()); if (j == 0) { sb.Clear(); sb.Append('-', columnLengths.Sum() - columnLengths[^1] + tableLines[0][^1].Length); converted.Add(sb.ToString()); } } converted.Add("```"); } else converted.Add(FixDocLine(line)); } break; case ArgsDocCommentSection args: converted.Add($"{HeaderPrefix} Args:"); converted.Add(string.Empty); foreach (var arg in args.Args) converted.Add(FixDocLine($"- `{arg.Name}` ({arg.SphinxType}): {arg.Documentation}")); break; case RaisesDocCommentSection raises: converted.Add($"{HeaderPrefix} Raises:"); converted.Add(string.Empty); foreach (var raise in raises.Raises) converted.Add(FixDocLine($"- {raise.SphinxType}: {raise.Documentation}")); break; case ReturnsDocCommentSection returns: converted.Add($"{HeaderPrefix} Returns:"); converted.Add(string.Empty); converted.Add(FixDocLine($"- {returns.Returns.SphinxType}: {returns.Returns.Documentation}")); break; case NoteDocCommentSection note: converted.Add($"{HeaderPrefix} Note:"); converted.Add(string.Empty); foreach (var line in note.Lines) converted.Add(FixDocLine($"- {line}")); break; case WarningDocCommentSection warning: converted.Add($"{HeaderPrefix} Warning:"); converted.Add(string.Empty); foreach (var line in warning.Lines) converted.Add(FixDocLine($"- {line}")); break; case TestCodeDocCommentSection testCode: converted.Add("```python"); foreach (var line in testCode.Lines) converted.Add(FixCodeBlockLine(line)); converted.Add("```"); break; case TestOutputDocCommentSection testOutput: converted.Add("```text"); foreach (var line in testOutput.Lines) converted.Add(FixCodeBlockLine(line)); converted.Add("```"); break; default: throw new InvalidOperationException(); } } return converted; } static bool IsTableLine(string line) => line.StartsWith("===", StringComparison.Ordinal) && line.EndsWith("===", StringComparison.Ordinal); static bool TryGetNextTableLine(string[] strings, ref int i, [NotNullWhen(true)] out string? tblLine) { if (i >= strings.Length) { tblLine = null; return false; } else { tblLine = strings[i]; i++; return true; } } static List<string> GetColumns(List<(int start, int length)> colDefs, string line) { var cols = new List<string>(); for (int i = 0; i < colDefs.Count; i++) { bool isLastCol = i + 1 == colDefs.Count; var colDef = colDefs[i]; if (colDef.start > 0 && line[colDef.start - 1] != ' ') throw new InvalidOperationException($"Invalid column #{i}, line: {line}"); if (!isLastCol && colDef.start + colDef.length < line.Length && line[colDef.start + colDef.length] != ' ') { throw new InvalidOperationException($"Invalid column #{i}, line: {line}"); } string col; if (isLastCol) col = line.Substring(colDef.start).Trim(); else col = line.Substring(colDef.start, colDef.length).Trim(); cols.Add(col); } return cols; } static void GetColumnDefs(List<(int start, int length)> colDefs, string line) { colDefs.Clear(); for (int index = 0; ;) { while (index < line.Length && line[index] == ' ') index++; if (index >= line.Length) break; int startIndex = index; index = line.IndexOf(' ', index); if (index < 0) index = line.Length; colDefs.Add((startIndex, index - startIndex)); } } static string FixDocLine(string line) { line = line.Replace(@"\", @"\\"); line = line.Replace("\"\"\"", "\\\"\\\"\\\""); line = line.Replace(@"``", @"`"); line = line.Replace(@":class:", string.Empty); if (line == "Examples:") line = HeaderPrefix + " " + line; return line; } static string FixCodeBlockLine(string line) { line = line.Replace(@"\", @"\\"); line = line.Replace("\"\"\"", "\\\"\\\"\\\""); return line; } static string FixTableColumn(string line, bool isFirst) { if (isFirst && line == @"\") line = string.Empty; line = line.Replace(@"``", @"`"); line = line.Replace(@":class:", string.Empty); return line; } } }
using System; using Microsoft.Xna.Framework; namespace Nez { /// <summary> /// Note that this is not a full, multi-iteration physics system! This can be used for simple, arcade style physics. /// Based on http://elancev.name/oliver/2D%20polygon.htm#tut5 /// </summary> public class ArcadeRigidbody : Component, IUpdatable { /// <summary> /// mass of this rigidbody. A 0 mass will make this an immovable object. /// </summary> /// <value>The mass.</value> public float mass { get { return _mass; } set { setMass( value ); } } /// <summary> /// 0 - 1 range where 0 is no bounce and 1 is perfect reflection /// </summary> public float elasticity { get { return _elasticity; } set { setElasticity( value ); } } /// <summary> /// 0 - 1 range. 0 means no friction, 1 means the object will stop dead on /// </summary> public float friction { get { return _friction; } set { setFriction( value ); } } /// <summary> /// 0 - 9 range. When a collision occurs and it has risidual motion along the surface of collision if its square magnitude is less /// than glue friction will be set to the maximum for the collision resolution. /// </summary> public float glue { get { return _glue; } set { setGlue( value ); } } /// <summary> /// if true, Physics.gravity will be taken into account each frame /// </summary> public bool shouldUseGravity = true; /// <summary> /// velocity of this rigidbody /// </summary> public Vector2 velocity; /// <summary> /// rigidbodies with a mass of 0 are considered immovable. Changing velocity and collisions will have no effect on them. /// </summary> /// <value><c>true</c> if is immovable; otherwise, <c>false</c>.</value> public bool isImmovable { get { return _mass < 0.0001f; } } float _mass = 10f; float _elasticity = 0.5f; float _friction = 0.5f; float _glue = 0.01f; float _inverseMass; Collider _collider; public ArcadeRigidbody() { _inverseMass = 1 / _mass; } #region Fluent setters /// <summary> /// mass of this rigidbody. A 0 mass will make this an immovable object. /// </summary> /// <returns>The mass.</returns> /// <param name="mass">Mass.</param> public ArcadeRigidbody setMass( float mass ) { _mass = Mathf.clamp( mass, 0, float.MaxValue ); if( _mass > 0.0001f ) _inverseMass = 1 / _mass; else _inverseMass = 0f; return this; } /// <summary> /// 0 - 1 range where 0 is no bounce and 1 is perfect reflection /// </summary> /// <returns>The elasticity.</returns> /// <param name="value">Value.</param> public ArcadeRigidbody setElasticity( float value ) { _elasticity = Mathf.clamp01( value ); return this; } /// <summary> /// 0 - 1 range. 0 means no friction, 1 means the object will stop dead on /// </summary> /// <returns>The friction.</returns> /// <param name="value">Value.</param> public ArcadeRigidbody setFriction( float value ) { _friction = Mathf.clamp01( value ); return this; } /// <summary> /// 0 - 9 range. When a collision occurs and it has risidual motion along the surface of collision if its square magnitude is less /// than glue friction will be set to the maximum for the collision resolution. /// </summary> /// <returns>The glue.</returns> /// <param name="value">Value.</param> public ArcadeRigidbody setGlue( float value ) { _glue = Mathf.clamp( value, 0, 10 ); return this; } /// <summary> /// velocity of this rigidbody /// </summary> /// <returns>The velocity.</returns> /// <param name="velocity">Velocity.</param> public ArcadeRigidbody setVelocity( Vector2 velocity ) { this.velocity = velocity; return this; } #endregion /// <summary> /// add an instant force impulse to the rigidbody using its mass. force is an acceleration in pixels per second per second. The /// force is multiplied by 100000 to make the values more reasonable to use. /// </summary> /// <param name="force">Force.</param> public void addImpulse( Vector2 force ) { if( !isImmovable ) velocity += force * 100000 * ( _inverseMass * Time.deltaTime * Time.deltaTime ); } public override void onAddedToEntity() { _collider = entity.getComponent<Collider>(); } void IUpdatable.update() { if( isImmovable ) { velocity = Vector2.Zero; return; } if( shouldUseGravity ) velocity += Physics.gravity * Time.deltaTime; entity.transform.position += velocity * Time.deltaTime; CollisionResult collisionResult; // fetch anything that we might collide with at our new position var neighbors = Physics.boxcastBroadphaseExcludingSelf( _collider, _collider.collidesWithLayers ); foreach( var neighbor in neighbors ) { // if the neighbor collider is of the same entity, ignore it if( neighbor.entity == entity ) { continue; } if( _collider.collidesWith( neighbor, out collisionResult ) ) { // if the neighbor has an ArcadeRigidbody we handle full collision response. If not, we calculate things based on the // neighbor being immovable. var neighborRigidbody = neighbor.entity.getComponent<ArcadeRigidbody>(); if( neighborRigidbody != null ) { processOverlap( neighborRigidbody, ref collisionResult.minimumTranslationVector ); processCollision( neighborRigidbody, ref collisionResult.minimumTranslationVector ); } else { // neighbor has no ArcadeRigidbody so we assume its immovable and only move ourself entity.transform.position -= collisionResult.minimumTranslationVector; var relativeVelocity = velocity; calculateResponseVelocity( ref relativeVelocity, ref collisionResult.minimumTranslationVector, out relativeVelocity ); velocity += relativeVelocity; } } } } /// <summary> /// separates two overlapping rigidbodies. Handles the case of either being immovable as well. /// </summary> /// <param name="other">Other.</param> /// <param name="minimumTranslationVector"></param> void processOverlap( ArcadeRigidbody other, ref Vector2 minimumTranslationVector ) { if( isImmovable ) { other.entity.transform.position += minimumTranslationVector; } else if( other.isImmovable ) { entity.transform.position -= minimumTranslationVector; } else { entity.transform.position -= minimumTranslationVector * 0.5f; other.entity.transform.position += minimumTranslationVector * 0.5f; } } /// <summary> /// handles the collision of two non-overlapping rigidbodies. New velocities will be assigned to each rigidbody as appropriate. /// </summary> /// <param name="other">Other.</param> /// <param name="inverseMTV">Inverse MT.</param> void processCollision( ArcadeRigidbody other, ref Vector2 minimumTranslationVector ) { // we compute a response for the two colliding objects. The calculations are based on the relative velocity of the objects // which gets reflected along the collided surface normal. Then a part of the response gets added to each object based on mass. var relativeVelocity = velocity - other.velocity; calculateResponseVelocity( ref relativeVelocity, ref minimumTranslationVector, out relativeVelocity ); // now we use the masses to linearly scale the response on both rigidbodies var totalInverseMass = _inverseMass + other._inverseMass; var ourResponseFraction = _inverseMass / totalInverseMass; var otherResponseFraction = other._inverseMass / totalInverseMass; velocity += relativeVelocity * ourResponseFraction; other.velocity -= relativeVelocity * otherResponseFraction; } /// <summary> /// given the relative velocity between the two objects and the MTV this method modifies the relativeVelocity to make it a collision /// response. /// </summary> /// <param name="relativeVelocity">Relative velocity.</param> /// <param name="minimumTranslationVector">Minimum translation vector.</param> void calculateResponseVelocity( ref Vector2 relativeVelocity, ref Vector2 minimumTranslationVector, out Vector2 responseVelocity ) { // first, we get the normalized MTV in the opposite direction: the surface normal var inverseMTV = minimumTranslationVector * -1f; Vector2 normal; Vector2.Normalize( ref inverseMTV, out normal ); // the velocity is decomposed along the normal of the collision and the plane of collision. // The elasticity will affect the response along the normal (normalVelocityComponent) and the friction will affect // the tangential component of the velocity (tangentialVelocityComponent) float n; Vector2.Dot( ref relativeVelocity, ref normal, out n ); var normalVelocityComponent = normal * n; var tangentialVelocityComponent = relativeVelocity - normalVelocityComponent; if( n > 0.0f ) normalVelocityComponent = Vector2.Zero; // if the squared magnitude of the tangential component is less than glue then we bump up the friction to the max var coefficientOfFriction = _friction; if( tangentialVelocityComponent.LengthSquared() < _glue ) coefficientOfFriction = 1.01f; // elasticity affects the normal component of the velocity and friction affects the tangential component responseVelocity = -( 1.0f + _elasticity ) * normalVelocityComponent - coefficientOfFriction * tangentialVelocityComponent; } } }
// Copyright 2021 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.Tasks.NetworkAnalysis; using Esri.ArcGISRuntime.UI; using Esri.ArcGISRuntime.UI.Controls; using Foundation; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Threading.Tasks; using UIKit; namespace ArcGISRuntime.Samples.ClosestFacility { [Register("ClosestFacility")] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Find closest facility to an incident (interactive)", category: "Network analysis", description: "Find a route to the closest facility from a location.", instructions: "Tap near any of the hospitals and a route will be displayed from that clicked location to the nearest hospital.", tags: new[] { "incident", "network analysis", "route", "search" })] public class ClosestFacility : UIViewController { // Hold references to UI controls. private MapView _myMapView; // Holds locations of hospitals around San Diego. private List<Facility> _facilities; // Graphics overlays for facilities and incidents. private GraphicsOverlay _facilityGraphicsOverlay; // Symbol for facilities. private PictureMarkerSymbol _facilitySymbol; // Overlay for the incident. private GraphicsOverlay _incidentGraphicsOverlay; // Black cross where user clicked. private MapPoint _incidentPoint; // Symbol for the incident. private SimpleMarkerSymbol _incidentSymbol; // Used to display route between incident and facility to mapview. private SimpleLineSymbol _routeSymbol; // Solves task to find closest route between an incident and a facility. private ClosestFacilityTask _task; public ClosestFacility() { Title = "Closest facility"; } private async void Initialize() { // Construct the map and set the MapView.Map property. Map map = new Map(BasemapStyle.ArcGISLightGray); _myMapView.Map = map; try { // Create a ClosestFacilityTask using the San Diego Uri. _task = await ClosestFacilityTask.CreateAsync(new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/ClosestFacility")); // List of facilities to be placed around San Diego area. _facilities = new List<Facility> { new Facility(new MapPoint(-1.3042129900625112E7, 3860127.9479775648, SpatialReferences.WebMercator)), new Facility(new MapPoint(-1.3042193400557665E7, 3862448.873041752, SpatialReferences.WebMercator)), new Facility(new MapPoint(-1.3046882875518233E7, 3862704.9896770366, SpatialReferences.WebMercator)), new Facility(new MapPoint(-1.3040539754780494E7, 3862924.5938606677, SpatialReferences.WebMercator)), new Facility(new MapPoint(-1.3042571225655518E7, 3858981.773018156, SpatialReferences.WebMercator)), new Facility(new MapPoint(-1.3039784633928463E7, 3856692.5980474586, SpatialReferences.WebMercator)), new Facility(new MapPoint(-1.3049023883956768E7, 3861993.789732541, SpatialReferences.WebMercator)) }; // Center the map on the San Diego facilities. Envelope fullExtent = GeometryEngine.CombineExtents(_facilities.Select(facility => facility.Geometry)); await _myMapView.SetViewpointGeometryAsync(fullExtent, 50); // Create a symbol for displaying facilities. _facilitySymbol = new PictureMarkerSymbol(new Uri("https://static.arcgis.com/images/Symbols/SafetyHealth/Hospital.png")) { Height = 30, Width = 30 }; // Incident symbol. _incidentSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Cross, Color.FromArgb(255, 0, 0, 0), 30); // Route to hospital symbol. _routeSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.FromArgb(255, 0, 0, 255), 5.0f); // Create Graphics Overlays for incidents and facilities. _incidentGraphicsOverlay = new GraphicsOverlay(); _facilityGraphicsOverlay = new GraphicsOverlay(); // Create a graphic and add to graphics overlay for each facility. foreach (Facility facility in _facilities) { _facilityGraphicsOverlay.Graphics.Add(new Graphic(facility.Geometry, _facilitySymbol)); } // Add each graphics overlay to MyMapView. _myMapView.GraphicsOverlays.Add(_incidentGraphicsOverlay); _myMapView.GraphicsOverlays.Add(_facilityGraphicsOverlay); } catch (Exception e) { new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show(); } } private async void MyMapView_GeoViewTapped(object sender, GeoViewInputEventArgs e) { try { _myMapView.GeoViewTapped -= MyMapView_GeoViewTapped; // Clear any prior incident and routes from the graphics. _incidentGraphicsOverlay.Graphics.Clear(); // Get the tapped point. _incidentPoint = e.Location; // Populate the facility parameters than solve using the task. await PopulateParametersAndSolveRouteAsync(); } catch (Exception ex) { new UIAlertView("Error", ex.Message, (IUIAlertViewDelegate)null, "OK", null).Show(); } finally { _myMapView.GeoViewTapped += MyMapView_GeoViewTapped; } } private async Task PopulateParametersAndSolveRouteAsync() { try { // Set facilities and incident in parameters. ClosestFacilityParameters closestFacilityParameters = await _task.CreateDefaultParametersAsync(); closestFacilityParameters.SetFacilities(_facilities); closestFacilityParameters.SetIncidents(new List<Incident> { new Incident(_incidentPoint) }); // Use the task to solve for the closest facility. ClosestFacilityResult result = await _task.SolveClosestFacilityAsync(closestFacilityParameters); // Get the index of the closest facility to incident. (0) is the index of the incident, [0] is the index of the closest facility. int closestFacility = result.GetRankedFacilityIndexes(0)[0]; // Get route from closest facility to the incident and display to mapview. ClosestFacilityRoute route = result.GetRoute(closestFacility, 0); // Add graphics for the incident and route. _incidentGraphicsOverlay.Graphics.Add(new Graphic(_incidentPoint, _incidentSymbol)); _incidentGraphicsOverlay.Graphics.Add(new Graphic(route.RouteGeometry, _routeSymbol)); } catch (Esri.ArcGISRuntime.Http.ArcGISWebException exception) { if (exception.Message.Equals("Unable to complete operation.")) { CreateErrorDialog("Incident not within San Diego area!"); } else { CreateErrorDialog("An ArcGIS web exception occurred. \n" + exception.Message); } } } private void CreateErrorDialog(string message) { // Create Alert. UIAlertController okAlertController = UIAlertController.Create("Error", message, UIAlertControllerStyle.Alert); // Add Action. okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); // Present Alert. PresentViewController(okAlertController, true, null); } public override void ViewDidLoad() { base.ViewDidLoad(); Initialize(); } public override void LoadView() { // Create the views. View = new UIView() { BackgroundColor = ApplicationTheme.BackgroundColor }; _myMapView = new MapView(); _myMapView.TranslatesAutoresizingMaskIntoConstraints = false; UILabel helpLabel = new UILabel { Text = "Tap to show the route to the nearest facility.", AdjustsFontSizeToFitWidth = true, TextAlignment = UITextAlignment.Center, BackgroundColor = UIColor.FromWhiteAlpha(0, .6f), TextColor = UIColor.White, Lines = 1, TranslatesAutoresizingMaskIntoConstraints = false }; // Add the views. View.AddSubviews(_myMapView, helpLabel); // Lay out the views. NSLayoutConstraint.ActivateConstraints(new[] { _myMapView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor), _myMapView.BottomAnchor.ConstraintEqualTo(View.BottomAnchor), _myMapView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), _myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor), helpLabel.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor), helpLabel.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), helpLabel.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor), helpLabel.HeightAnchor.ConstraintEqualTo(40) }); } public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); // Subscribe to events. _myMapView.GeoViewTapped += MyMapView_GeoViewTapped; } public override void ViewDidDisappear(bool animated) { base.ViewDidDisappear(animated); // Unsubscribe from events, per best practice. _myMapView.GeoViewTapped -= MyMapView_GeoViewTapped; } } }
using System; using System.Configuration; using System.Text; using log4net; using WaterOneFlowImpl; using System.Web; using System.Web.Services; using System.Xml.Serialization; using System.IO; using System.Xml; using System.Web.Services.Protocols; using WaterOneFlow.Schema.v1_1; using WaterOneFlow; //using Microsoft.Web.Services3; //using Microsoft.Web.Services3.Addressing; //using Microsoft.Web.Services3.Messaging; using WaterOneFlowImpl.geom; namespace WaterOneFlow.odws { namespace v1_1 { using ConstantsNamespace = WaterOneFlowImpl.v1_1.Constants; using IService = WaterOneFlow.v1_1.IService; public class Config { public static string ODDB() { if (ConfigurationManager.ConnectionStrings["ODDB"]!= null) { return ConfigurationManager.ConnectionStrings["ODDB"].ConnectionString; } else { return null; } } } [WebService(Name = WsDescriptions.WsDefaultName, Namespace = ConstantsNamespace.WS_NAMSPACE, Description = WsDescriptions.SvcDevelopementalWarning + WsDescriptions.WsDefaultDescription)] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] //[SoapActor("*")] public class Service : WebService, IService { //protected ODService ODws; protected CustomService ODws; private Boolean useODForValues; private Boolean requireAuthToken; private static readonly ILog log = LogManager.GetLogger(typeof(Service)); private static readonly ILog queryLog = LogManager.GetLogger("QueryLog"); public Service() { //log4net.Util.LogLog.InternalDebugging = true; ODws = new CustomService(this.Context);//INFO we can extend this for other service types try { useODForValues = Boolean.Parse(ConfigurationManager.AppSettings["UseODForValues"]); } catch (Exception e) { String error = "Missing or invalid value for UseODForValues. Must be true or false"; log.Fatal(error); throw new SoapException("Invalid Server Configuration. " + error, new XmlQualifiedName(SoapExceptionGenerator.ServerError)); } try { requireAuthToken = Boolean.Parse(ConfigurationManager.AppSettings["requireAuthToken"]); } catch (Exception e) { String error = "Missing or invalid value for requireAuthToken. Must be true or false"; log.Fatal(error); throw new SoapException(error, new XmlQualifiedName(SoapExceptionGenerator.ServerError)); } } #region IService Members public string GetSites(string[] SiteNumbers, String authToken) { SiteInfoResponseType aSite = GetSitesObject(SiteNumbers, authToken); string xml = WSUtils.ConvertToXml(aSite, typeof(SiteInfoResponseType)); return xml; } public virtual string GetSiteInfo(string SiteNumber, String authToken) { SiteInfoResponseType aSite = GetSiteInfoObject(SiteNumber, authToken); string xml = WSUtils.ConvertToXml(aSite, typeof(SiteInfoResponseType)); return xml; } public string GetVariableInfo(string variable, String authToken) { VariablesResponseType aVType = GetVariableInfoObject(variable, authToken); string xml = WSUtils.ConvertToXml(aVType, typeof(VariablesResponseType)); return xml; } public SiteInfoResponseType GetSitesObject(string[] site, String authToken) { GlobalClass.WaterAuth.SitesServiceAllowed(Context, authToken); try { return ODws.GetSites(site); } catch (Exception we) { log.Warn(we.Message); throw SoapExceptionGenerator.WOFExceptionToSoapException(we); } } public virtual SiteInfoResponseType GetSiteInfoObject(string site, String authToken) { GlobalClass.WaterAuth.SiteInfoServiceAllowed(Context, authToken); try { return ODws.GetSiteInfo(site); } catch (Exception we) { log.Warn(we.Message); throw SoapExceptionGenerator.WOFExceptionToSoapException(we); } } public VariablesResponseType GetVariableInfoObject(string variable, String authToken) { GlobalClass.WaterAuth.VariableInfoServiceAllowed(Context, authToken); try { return ODws.GetVariableInfo(variable); } catch (Exception we) { log.Warn(we.Message); throw SoapExceptionGenerator.WOFExceptionToSoapException(we); } } public virtual string GetValues( string location, string variable, string startDate, string endDate, String authToken) { TimeSeriesResponseType aSite = GetValuesObject(location, variable, startDate, endDate, null); return WSUtils.ConvertToXml(aSite, typeof(TimeSeriesResponseType)); } public virtual TimeSeriesResponseType GetValuesObject( string location, string variable, string startDate, string endDate, String authToken) { GlobalClass.WaterAuth.DataValuesServiceAllowed(Context, authToken); if (!useODForValues) throw new SoapException("GetValues implemented external to this service. Call GetSiteInfo, and SeriesCatalog includes the service Wsdl for GetValues. Attribute:serviceWsdl on Element:seriesCatalog XPath://seriesCatalog/[@serviceWsdl]", new XmlQualifiedName("ServiceException")); try { return ODws.GetValues(location, variable, startDate, endDate); } catch (Exception we) { log.Warn(we.Message); throw SoapExceptionGenerator.WOFExceptionToSoapException(we); } } public SiteInfoResponseType GetSiteInfoMultpleObject(string[] site, string authToken) { GlobalClass.WaterAuth.SiteInfoServiceAllowed(Context, authToken); try { return ODws.GetSiteInfo(site, true); } catch (Exception we) { log.Warn(we.Message); throw SoapExceptionGenerator.WOFExceptionToSoapException(we); } } public SiteInfoResponseType GetSitesByBoxObject(float west, float south, float east, float north, bool IncludeSeries, string authToken) { GlobalClass.WaterAuth.SiteInfoServiceAllowed(Context, authToken); return ODws.GetSitesInBox( west,south,east, north, IncludeSeries ); } public TimeSeriesResponseType GetValuesForASiteObject(string site, string StartDate, string EndDate, string authToken) { GlobalClass.WaterAuth.DataValuesServiceAllowed(Context, authToken); return ODws.GetValuesForASite(site, StartDate, EndDate); } public TimeSeriesResponseType GetValuesByBoxObject(string variable, string StartDate, string EndDate, float west, float south, float east, float north, string authToken) { throw new NotImplementedException(); } public string GetVariables(String authToken) { VariablesResponseType aVType = GetVariableInfoObject(null, authToken); string xml = WSUtils.ConvertToXml(aVType, typeof(VariablesResponseType)); return xml; } public VariablesResponseType GetVariablesObject(String authToken) { return GetVariableInfoObject(null, authToken); } #endregion } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Audio; using osu.Framework.Audio.Sample; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Colour; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Input.Events; using osu.Framework.Utils; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.UI; using osuTK; using osuTK.Input; #nullable enable namespace osu.Game.Overlays.Mods { public class ModPanel : OsuClickableContainer { public Mod Mod { get; } public BindableBool Active { get; } = new BindableBool(); public BindableBool Filtered { get; } = new BindableBool(); protected readonly Box Background; protected readonly Container SwitchContainer; protected readonly Container MainContentContainer; protected readonly Box TextBackground; protected readonly FillFlowContainer TextFlow; [Resolved] protected OverlayColourProvider ColourProvider { get; private set; } = null!; protected const double TRANSITION_DURATION = 150; public const float SHEAR_X = 0.2f; public const float CORNER_RADIUS = 7; protected const float HEIGHT = 42; protected const float IDLE_SWITCH_WIDTH = 54; protected const float EXPANDED_SWITCH_WIDTH = 70; private Colour4 activeColour; private Sample? sampleOff; private Sample? sampleOn; public ModPanel(Mod mod) { Mod = mod; RelativeSizeAxes = Axes.X; Height = 42; // all below properties are applied to `Content` rather than the `ModPanel` in its entirety // to allow external components to set these properties on the panel without affecting // its "internal" appearance. Content.Masking = true; Content.CornerRadius = CORNER_RADIUS; Content.BorderThickness = 2; Content.Shear = new Vector2(SHEAR_X, 0); Children = new Drawable[] { Background = new Box { RelativeSizeAxes = Axes.Both }, SwitchContainer = new Container { RelativeSizeAxes = Axes.Y, Child = new ModSwitchSmall(mod) { Anchor = Anchor.Centre, Origin = Anchor.Centre, Active = { BindTarget = Active }, Shear = new Vector2(-SHEAR_X, 0), Scale = new Vector2(HEIGHT / ModSwitchSmall.DEFAULT_SIZE) } }, MainContentContainer = new Container { RelativeSizeAxes = Axes.Both, Child = new Container { RelativeSizeAxes = Axes.Both, Masking = true, CornerRadius = CORNER_RADIUS, Children = new Drawable[] { TextBackground = new Box { RelativeSizeAxes = Axes.Both }, TextFlow = new FillFlowContainer { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Horizontal = 17.5f, Vertical = 4 }, Direction = FillDirection.Vertical, Children = new[] { new OsuSpriteText { Text = mod.Name, Font = OsuFont.TorusAlternate.With(size: 18, weight: FontWeight.SemiBold), Shear = new Vector2(-SHEAR_X, 0), Margin = new MarginPadding { Left = -18 * SHEAR_X } }, new OsuSpriteText { Text = mod.Description, Font = OsuFont.Default.With(size: 12), RelativeSizeAxes = Axes.X, Truncate = true, Shear = new Vector2(-SHEAR_X, 0) } } } } } } }; Action = Active.Toggle; } [BackgroundDependencyLoader] private void load(AudioManager audio, OsuColour colours) { sampleOn = audio.Samples.Get(@"UI/check-on"); sampleOff = audio.Samples.Get(@"UI/check-off"); activeColour = colours.ForModType(Mod.Type); } protected override HoverSounds CreateHoverSounds(HoverSampleSet sampleSet) => new HoverSounds(sampleSet); protected override void LoadComplete() { base.LoadComplete(); Active.BindValueChanged(_ => { playStateChangeSamples(); UpdateState(); }); Filtered.BindValueChanged(_ => updateFilterState()); UpdateState(); FinishTransforms(true); } private void playStateChangeSamples() { if (Active.Value) sampleOn?.Play(); else sampleOff?.Play(); } protected override bool OnHover(HoverEvent e) { UpdateState(); return base.OnHover(e); } protected override void OnHoverLost(HoverLostEvent e) { UpdateState(); base.OnHoverLost(e); } private bool mouseDown; protected override bool OnMouseDown(MouseDownEvent e) { if (e.Button == MouseButton.Left) mouseDown = true; UpdateState(); return false; } protected override void OnMouseUp(MouseUpEvent e) { mouseDown = false; UpdateState(); base.OnMouseUp(e); } protected virtual void UpdateState() { float targetWidth = Active.Value ? EXPANDED_SWITCH_WIDTH : IDLE_SWITCH_WIDTH; double transitionDuration = TRANSITION_DURATION; Colour4 textBackgroundColour = Active.Value ? activeColour : (Colour4)ColourProvider.Background2; Colour4 mainBackgroundColour = Active.Value ? activeColour.Darken(0.3f) : (Colour4)ColourProvider.Background3; Colour4 textColour = Active.Value ? (Colour4)ColourProvider.Background6 : Colour4.White; // Hover affects colour of button background if (IsHovered) { textBackgroundColour = textBackgroundColour.Lighten(0.1f); mainBackgroundColour = mainBackgroundColour.Lighten(0.1f); } // Mouse down adds a halfway tween of the movement if (mouseDown) { targetWidth = (float)Interpolation.Lerp(IDLE_SWITCH_WIDTH, EXPANDED_SWITCH_WIDTH, 0.5f); transitionDuration *= 4; } Content.TransformTo(nameof(BorderColour), ColourInfo.GradientVertical(mainBackgroundColour, textBackgroundColour), transitionDuration, Easing.OutQuint); Background.FadeColour(mainBackgroundColour, transitionDuration, Easing.OutQuint); SwitchContainer.ResizeWidthTo(targetWidth, transitionDuration, Easing.OutQuint); MainContentContainer.TransformTo(nameof(Padding), new MarginPadding { Left = targetWidth, Right = CORNER_RADIUS }, transitionDuration, Easing.OutQuint); TextBackground.FadeColour(textBackgroundColour, transitionDuration, Easing.OutQuint); TextFlow.FadeColour(textColour, transitionDuration, Easing.OutQuint); } #region Filtering support public void ApplyFilter(Func<Mod, bool>? filter) { Filtered.Value = filter != null && !filter.Invoke(Mod); } private void updateFilterState() { this.FadeTo(Filtered.Value ? 0 : 1); } #endregion } }
//--------------------------------------------------------------------- // <copyright file="InstallPath.cs" company="Microsoft Corporation"> // Copyright (c) 1999, Microsoft Corporation. All rights reserved. // </copyright> // <summary> // Part of the Deployment Tools Foundation project. // </summary> //--------------------------------------------------------------------- namespace Microsoft.PackageManagement.Msi.Internal.Deployment.WindowsInstaller.Package { using System; using System.Collections; using System.Collections.Generic; using System.IO; /// <summary> /// Represents the installation path of a file or directory from an installer product database. /// </summary> internal class InstallPath { /// <summary> /// Creates a new InstallPath, specifying a filename. /// </summary> /// <param name="name">The name of the file or directory. Not a full path.</param> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public InstallPath(string name) : this(name, false) { } /// <summary> /// Creates a new InstallPath, parsing out either the short or long filename. /// </summary> /// <param name="name">The name of the file or directory, in short|long syntax for a filename /// or targetshort|targetlong:sourceshort|sourcelong syntax for a directory.</param> /// <param name="useShortNames">true to parse the short part of the combined filename; false to parse the long part</param> public InstallPath(string name, bool useShortNames) { if(name == null) { throw new ArgumentNullException("name"); } this.parentPath = null; ParseName(name, useShortNames); } private void ParseName(string name, bool useShortNames) { string[] parse = name.Split(new char[] { ':' }, 3); if(parse.Length == 3) { // Syntax was targetshort:sourceshort|targetlong:sourcelong. // Chnage it to targetshort|targetlong:sourceshort|sourcelong. parse = name.Split(new char[] { ':', '|' }, 4); if(parse.Length == 4) parse = new string[] { parse[0] + '|' + parse[2], parse[1] + '|' + parse[3] }; else parse = new string[] { parse[0] + '|' + parse[1], parse[1] + '|' + parse[2] }; } string targetName = parse[0]; string sourceName = (parse.Length == 2 ? parse[1] : parse[0]); parse = targetName.Split(new char[] { '|' }, 2); if(parse.Length == 2) targetName = (useShortNames ? parse[0] : parse[1]); parse = sourceName.Split(new char[] { '|' }, 2); if(parse.Length == 2) sourceName = (useShortNames ? parse[0] : parse[1]); this.SourceName = sourceName; this.TargetName = targetName; } /// <summary> /// Gets the path of the parent directory. /// </summary> public InstallPath ParentPath { get { return parentPath; } } internal void SetParentPath(InstallPath value) { parentPath = value; ResetSourcePath(); ResetTargetPath(); } private InstallPath parentPath; /// <summary> /// Gets the set of child paths if this InstallPath object represents a a directory. /// </summary> public InstallPathCollection ChildPaths { get { if(childPaths == null) { childPaths = new InstallPathCollection(this); } return childPaths; } } private InstallPathCollection childPaths; /// <summary> /// Gets or sets the source name of the InstallPath. /// </summary> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string SourceName { get { return sourceName; } set { if(value == null) { throw new ArgumentNullException("value"); } sourceName = value; ResetSourcePath(); } } private string sourceName; /// <summary> /// Gets or sets the target name of the install path. /// </summary> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string TargetName { get { return targetName; } set { if(value == null) { throw new ArgumentNullException("value"); } targetName = value; ResetTargetPath(); } } private string targetName; /// <summary> /// Gets the full source path. /// </summary> public string SourcePath { get { if(sourcePath == null) { if(parentPath != null) { sourcePath = (sourceName.Equals(".") ? parentPath.SourcePath : Path.Combine(parentPath.SourcePath, sourceName)); } else { sourcePath = sourceName; } } return sourcePath; } set { ResetSourcePath(); sourcePath = value; } } private string sourcePath; /// <summary> /// Gets the full target path. /// </summary> public string TargetPath { get { if(targetPath == null) { if(parentPath != null) { targetPath = (targetName.Equals(".") ? parentPath.TargetPath : Path.Combine(parentPath.TargetPath, targetName)); } else { targetPath = targetName; } } return targetPath; } set { ResetTargetPath(); targetPath = value; } } private string targetPath; private void ResetSourcePath() { if(sourcePath != null) { sourcePath = null; if(childPaths != null) { foreach(InstallPath ip in childPaths) { ip.ResetSourcePath(); } } } } private void ResetTargetPath() { if(targetPath != null) { targetPath = null; if(childPaths != null) { foreach(InstallPath ip in childPaths) { ip.ResetTargetPath(); } } } } /// <summary> /// Gets the full source path. /// </summary> /// <returns><see cref="SourcePath"/></returns> public override String ToString() { return SourcePath; } } /// <summary> /// Represents a collection of InstallPaths that are the child paths of the same parent directory. /// </summary> internal class InstallPathCollection : IList<InstallPath> { private InstallPath parentPath; private List<InstallPath> items; internal InstallPathCollection(InstallPath parentPath) { this.parentPath = parentPath; this.items = new List<InstallPath>(); } /// <summary> /// Gets or sets the element at the specified index. /// </summary> public InstallPath this[int index] { get { return this.items[index]; } set { this.OnSet(this.items[index], value); this.items[index] = value; } } /// <summary> /// Adds a new child path to the collection. /// </summary> /// <param name="item">The InstallPath to add.</param> public void Add(InstallPath item) { this.OnInsert(item); this.items.Add(item); } /// <summary> /// Removes a child path to the collection. /// </summary> /// <param name="item">The InstallPath to remove.</param> public bool Remove(InstallPath item) { int index = this.items.IndexOf(item); if (index >= 0) { this.OnRemove(item); this.items.RemoveAt(index); return true; } else { return false; } } /// <summary> /// Gets the index of a child path in the collection. /// </summary> /// <param name="item">The InstallPath to search for.</param> /// <returns>The index of the item, or -1 if not found.</returns> public int IndexOf(InstallPath item) { return this.items.IndexOf(item); } /// <summary> /// Inserts a child path into the collection. /// </summary> /// <param name="index">The insertion index.</param> /// <param name="item">The InstallPath to insert.</param> public void Insert(int index, InstallPath item) { this.OnInsert(item); this.items.Insert(index, item); } /// <summary> /// Tests if the collection contains a child path. /// </summary> /// <param name="item">The InstallPath to search for.</param> /// <returns>true if the item is found; false otherwise</returns> public bool Contains(InstallPath item) { return this.items.Contains(item); } /// <summary> /// Copies the collection into an array. /// </summary> /// <param name="array">The array to copy into.</param> /// <param name="index">The starting index in the destination array.</param> public void CopyTo(InstallPath[] array, int index) { this.items.CopyTo(array, index); } private void OnInsert(InstallPath item) { if (item.ParentPath != null) { item.ParentPath.ChildPaths.Remove(item); } item.SetParentPath(this.parentPath); } private void OnRemove(InstallPath item) { item.SetParentPath(null); } private void OnSet(InstallPath oldItem, InstallPath newItem) { this.OnRemove(oldItem); this.OnInsert(newItem); } /// <summary> /// Removes an item from the collection. /// </summary> /// <param name="index">The index of the item to remove.</param> public void RemoveAt(int index) { this.OnRemove(this[index]); this.items.RemoveAt(index); } /// <summary> /// Removes all items from the collection. /// </summary> public void Clear() { foreach (InstallPath item in this) { this.OnRemove(item); } this.items.Clear(); } /// <summary> /// Gets the number of items in the collection. /// </summary> public int Count { get { return this.items.Count; } } bool ICollection<InstallPath>.IsReadOnly { get { return false; } } /// <summary> /// Gets an enumerator over all items in the collection. /// </summary> /// <returns>An enumerator for the collection.</returns> public IEnumerator<InstallPath> GetEnumerator() { return this.items.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<InstallPath>) this).GetEnumerator(); } } /// <summary> /// Represents a mapping of install paths for all directories, components, or files in /// an installation database. /// </summary> internal class InstallPathMap : IDictionary<string, InstallPath> { /// <summary> /// Builds a mapping from File keys to installation paths. /// </summary> /// <param name="db">Installation database.</param> /// <param name="componentPathMap">Component mapping returned by <see cref="BuildComponentPathMap"/>.</param> /// <param name="useShortNames">true to use short file names; false to use long names</param> /// <returns>An InstallPathMap with the described mapping.</returns> public static InstallPathMap BuildFilePathMap(Database db, InstallPathMap componentPathMap, bool useShortNames) { if(db == null) { throw new ArgumentNullException("db"); } if(componentPathMap == null) { componentPathMap = BuildComponentPathMap(db, BuildDirectoryPathMap(db, useShortNames)); } InstallPathMap filePathMap = new InstallPathMap(); using (View fileView = db.OpenView("SELECT `File`, `Component_`, `FileName` FROM `File`")) { fileView.Execute(); foreach (Record fileRec in fileView) { using (fileRec) { string file = (string) fileRec[1]; string comp = (string) fileRec[2]; string fileName = (string) fileRec[3]; InstallPath compPath = (InstallPath) componentPathMap[comp]; if(compPath != null) { InstallPath filePath = new InstallPath(fileName, useShortNames); compPath.ChildPaths.Add(filePath); filePathMap[file] = filePath; } } } } return filePathMap; } /// <summary> /// Builds a mapping from Component keys to installation paths. /// </summary> /// <param name="db">Installation database.</param> /// <param name="directoryPathMap">Directory mapping returned by /// <see cref="BuildDirectoryPathMap(Database,bool)"/>.</param> /// <returns>An InstallPathMap with the described mapping.</returns> public static InstallPathMap BuildComponentPathMap(Database db, InstallPathMap directoryPathMap) { if(db == null) { throw new ArgumentNullException("db"); } InstallPathMap compPathMap = new InstallPathMap(); using (View compView = db.OpenView("SELECT `Component`, `Directory_` FROM `Component`")) { compView.Execute(); foreach (Record compRec in compView) { using (compRec) { string comp = (string) compRec[1]; InstallPath dirPath = (InstallPath) directoryPathMap[(string) compRec[2]]; if (dirPath != null) { compPathMap[comp] = dirPath; } } } } return compPathMap; } /// <summary> /// Builds a mapping from Directory keys to installation paths. /// </summary> /// <param name="db">Installation database.</param> /// <param name="useShortNames">true to use short directory names; false to use long names</param> /// <returns>An InstallPathMap with the described mapping.</returns> public static InstallPathMap BuildDirectoryPathMap(Database db, bool useShortNames) { return BuildDirectoryPathMap(db, useShortNames, null, null); } /// <summary> /// Builds a mapping of Directory keys to directory paths, specifying root directories /// for the source and target paths. /// </summary> /// <param name="db">Database containing the Directory table.</param> /// <param name="useShortNames">true to use short directory names; false to use long names</param> /// <param name="sourceRootDir">The root directory path of all source paths, or null to leave them relative.</param> /// <param name="targetRootDir">The root directory path of all source paths, or null to leave them relative.</param> /// <returns>An InstallPathMap with the described mapping.</returns> public static InstallPathMap BuildDirectoryPathMap(Database db, bool useShortNames, string sourceRootDir, string targetRootDir) { if(db == null) { throw new ArgumentNullException("db"); } if(sourceRootDir == null) sourceRootDir = ""; if(targetRootDir == null) targetRootDir = ""; InstallPathMap dirMap = new InstallPathMap(); IDictionary dirTreeMap = new Hashtable(); using (View dirView = db.OpenView("SELECT `Directory`, `Directory_Parent`, `DefaultDir` FROM `Directory`")) { dirView.Execute(); foreach (Record dirRec in dirView) using (dirRec) { string key = (string) dirRec[1]; string parentKey = (string) dirRec[2]; InstallPath dir = new InstallPath((string) dirRec[3], useShortNames); dirMap[key] = dir; InstallPathMap siblingDirs = (InstallPathMap) dirTreeMap[parentKey]; if (siblingDirs == null) { siblingDirs = new InstallPathMap(); dirTreeMap[parentKey] = siblingDirs; } siblingDirs.Add(key, dir); } } foreach (KeyValuePair<string, InstallPath> entry in (InstallPathMap) dirTreeMap[""]) { string key = (string) entry.Key; InstallPath dir = (InstallPath) entry.Value; LinkSubdirectories(key, dir, dirTreeMap); } InstallPath targetDirPath = (InstallPath) dirMap["TARGETDIR"]; if(targetDirPath != null) { targetDirPath.SourcePath = sourceRootDir; targetDirPath.TargetPath = targetRootDir; } return dirMap; } private static void LinkSubdirectories(string key, InstallPath dir, IDictionary dirTreeMap) { InstallPathMap subDirs = (InstallPathMap) dirTreeMap[key]; if(subDirs != null) { foreach (KeyValuePair<string, InstallPath> entry in subDirs) { string subKey = (string) entry.Key; InstallPath subDir = (InstallPath) entry.Value; dir.ChildPaths.Add(subDir); LinkSubdirectories(subKey, subDir, dirTreeMap); } } } private Dictionary<string, InstallPath> items; /// <summary> /// Creates a new empty InstallPathMap. /// </summary> public InstallPathMap() { this.items = new Dictionary<string,InstallPath>(StringComparer.OrdinalIgnoreCase); } /// <summary> /// Gets a mapping from keys to source paths. /// </summary> public IDictionary<string, string> SourcePaths { get { return new SourcePathMap(this); } } /// <summary> /// Gets a mapping from keys to target paths. /// </summary> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public IDictionary<string, string> TargetPaths { get { return new TargetPathMap(this); } } /// <summary> /// Gets or sets an install path for a direcotry, component, or file key. /// </summary> /// <param name="key">Depending on the type of InstallPathMap, this is the primary key from the /// either the Directory, Component, or File table.</param> /// <remarks> /// Changing an install path does not modify the Database used to generate this InstallPathMap. /// </remarks> public InstallPath this[string key] { get { InstallPath value = null; this.items.TryGetValue(key, out value); return value; } set { this.items[key] = value; } } /// <summary> /// Gets the collection of keys in the InstallPathMap. Depending on the type of InstallPathMap, /// they are all directory, component, or file key strings. /// </summary> public ICollection<string> Keys { get { return this.items.Keys; } } /// <summary> /// Gets the collection of InstallPath values in the InstallPathMap. /// </summary> public ICollection<InstallPath> Values { get { return this.items.Values; } } /// <summary> /// Sets an install path for a direcotry, component, or file key. /// </summary> /// <param name="key">Depending on the type of InstallPathMap, this is the primary key from the /// either the Directory, Component, or File table.</param> /// <param name="installPath">The install path of the key item.</param> /// <remarks> /// Changing an install path does not modify the Database used to generate this InstallPathMap. /// </remarks> public void Add(string key, InstallPath installPath) { this.items.Add(key, installPath); } /// <summary> /// Removes an install path from the map. /// </summary> /// <param name="key">Depending on the type of InstallPathMap, this is the primary key from the /// either the Directory, Component, or File table.</param> /// <returns>true if the item was removed, false if it did not exist</returns> /// <remarks> /// Changing an install path does not modify the Database used to generate this InstallPathMap. /// </remarks> public bool Remove(string key) { return this.items.Remove(key); } /// <summary> /// Tests whether a direcotry, component, or file key exists in the map. /// </summary> /// <param name="key">Depending on the type of InstallPathMap, this is the primary key from the /// either the Directory, Component, or File table.</param> /// <returns>true if the key is found; false otherwise</returns> public bool ContainsKey(string key) { return this.items.ContainsKey(key); } /* public override string ToString() { System.Text.StringBuilder buf = new System.Text.StringBuilder(); foreach(KeyValuePair<string, InstallPath> entry in this) { buf.AppendFormat("{0}={1}", entry.Key, entry.Value); buf.Append("\n"); } return buf.ToString(); } */ /// <summary> /// Attempts to get a value from the dictionary. /// </summary> /// <param name="key">The key to lookup.</param> /// <param name="value">Receives the value, or null if they key was not found.</param> /// <returns>True if the value was found, else false.</returns> public bool TryGetValue(string key, out InstallPath value) { return this.items.TryGetValue(key, out value); } void ICollection<KeyValuePair<string, InstallPath>>.Add(KeyValuePair<string, InstallPath> item) { ((ICollection<KeyValuePair<string, InstallPath>>) this.items).Add(item); } /// <summary> /// Removes all entries from the dictionary. /// </summary> public void Clear() { this.items.Clear(); } bool ICollection<KeyValuePair<string, InstallPath>>.Contains(KeyValuePair<string, InstallPath> item) { return ((ICollection<KeyValuePair<string, InstallPath>>) this.items).Contains(item); } void ICollection<KeyValuePair<string, InstallPath>>.CopyTo(KeyValuePair<string, InstallPath>[] array, int arrayIndex) { ((ICollection<KeyValuePair<string, InstallPath>>) this.items).CopyTo(array, arrayIndex); } /// <summary> /// Gets the number of entries in the dictionary. /// </summary> public int Count { get { return this.items.Count; } } bool ICollection<KeyValuePair<string, InstallPath>>.IsReadOnly { get { return false; } } bool ICollection<KeyValuePair<string, InstallPath>>.Remove(KeyValuePair<string, InstallPath> item) { return ((ICollection<KeyValuePair<string, InstallPath>>) this.items).Remove(item); } /// <summary> /// Gets an enumerator over all entries in the dictionary. /// </summary> /// <returns>An enumerator for the dictionary.</returns> public IEnumerator<KeyValuePair<string, InstallPath>> GetEnumerator() { return this.items.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.items.GetEnumerator(); } } internal class SourcePathMap : IDictionary<string, string> { private const string RO_MSG = "The SourcePathMap collection is read-only. " + "Modify the InstallPathMap instead."; private InstallPathMap map; internal SourcePathMap(InstallPathMap map) { this.map = map; } public void Add(string key, string value) { throw new InvalidOperationException(RO_MSG); } public bool ContainsKey(string key) { return this.map.ContainsKey(key); } public ICollection<string> Keys { get { return this.map.Keys; } } public bool Remove(string key) { throw new InvalidOperationException(RO_MSG); } public bool TryGetValue(string key, out string value) { InstallPath installPath; if (this.map.TryGetValue(key, out installPath)) { value = installPath.SourcePath; return true; } else { value = null; return false; } } public ICollection<string> Values { get { List<string> values = new List<string>(this.Count); foreach (KeyValuePair<string, InstallPath> entry in this.map) { values.Add(entry.Value.SourcePath); } return values; } } public string this[string key] { get { string value = null; this.TryGetValue(key, out value); return value; } set { throw new InvalidOperationException(RO_MSG); } } public void Add(KeyValuePair<string, string> item) { throw new InvalidOperationException(RO_MSG); } public void Clear() { throw new InvalidOperationException(RO_MSG); } public bool Contains(KeyValuePair<string, string> item) { string value = this[item.Key]; return value == item.Value; } public void CopyTo(KeyValuePair<string, string>[] array, int arrayIndex) { foreach (KeyValuePair<string, string> entry in this) { array[arrayIndex] = entry; arrayIndex++; } } public int Count { get { return this.map.Count; } } public bool IsReadOnly { get { return true; } } public bool Remove(KeyValuePair<string, string> item) { throw new InvalidOperationException(RO_MSG); } public IEnumerator<KeyValuePair<string, string>> GetEnumerator() { foreach (KeyValuePair<string, InstallPath> entry in this.map) { yield return new KeyValuePair<string, string>( entry.Key, entry.Value.SourcePath); } } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } internal class TargetPathMap : IDictionary<string, string> { private const string RO_MSG = "The TargetPathMap collection is read-only. " + "Modify the InstallPathMap instead."; private InstallPathMap map; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal TargetPathMap(InstallPathMap map) { this.map = map; } public void Add(string key, string value) { throw new InvalidOperationException(RO_MSG); } public bool ContainsKey(string key) { return this.map.ContainsKey(key); } public ICollection<string> Keys { get { return this.map.Keys; } } public bool Remove(string key) { throw new InvalidOperationException(RO_MSG); } public bool TryGetValue(string key, out string value) { InstallPath installPath; if (this.map.TryGetValue(key, out installPath)) { value = installPath.TargetPath; return true; } else { value = null; return false; } } public ICollection<string> Values { get { List<string> values = new List<string>(this.Count); foreach (KeyValuePair<string, InstallPath> entry in this.map) { values.Add(entry.Value.TargetPath); } return values; } } public string this[string key] { get { string value = null; this.TryGetValue(key, out value); return value; } set { throw new InvalidOperationException(RO_MSG); } } public void Add(KeyValuePair<string, string> item) { throw new InvalidOperationException(RO_MSG); } public void Clear() { throw new InvalidOperationException(RO_MSG); } public bool Contains(KeyValuePair<string, string> item) { string value = this[item.Key]; return value == item.Value; } public void CopyTo(KeyValuePair<string, string>[] array, int arrayIndex) { foreach (KeyValuePair<string, string> entry in this) { array[arrayIndex] = entry; arrayIndex++; } } public int Count { get { return this.map.Count; } } public bool IsReadOnly { get { return true; } } public bool Remove(KeyValuePair<string, string> item) { throw new InvalidOperationException(RO_MSG); } public IEnumerator<KeyValuePair<string, string>> GetEnumerator() { foreach (KeyValuePair<string, InstallPath> entry in this.map) { yield return new KeyValuePair<string, string>( entry.Key, entry.Value.TargetPath); } } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; namespace IronPythonTest { public class Tuple { private object[] val; public Tuple(object a) { val = new object[] { a }; } public Tuple(object a, object b) { val = new object[] { a, b }; } public Tuple(object a, object b, object c) { val = new object[] { a, b, c }; } public Tuple(object a, object b, object c, object d) { val = new object[] { a, b, c, d }; } public Tuple(object a, object b, object c, object d, object e) { val = new object[] { a, b, c, d, e }; } private static bool Compare(object x, object y) { if (x != null) { if (y != null) { return x.Equals(y); } else return false; } else { return y == null; } } public override bool Equals(object obj) { Tuple other = obj as Tuple; if (other == null) return false; if (val != null) { if (other.val != null) { if (val.Length != other.val.Length) { return false; } for (int i = 0; i < val.Length; i++) { if (!Compare(val[i], other.val[i])) { return false; } } return true; } else return false; } else return other.val == null; } public override int GetHashCode() { int hash = 0; if (val != null && val.Length > 0) { hash = val[0].GetHashCode(); for (int i = 1; i < val.Length; i++) { hash ^= val[i].GetHashCode(); } } return hash; } } public struct StructIndexable { private List<int?> _data; public int? this[int index] { get { if (_data == null || _data.Count < index) { return null; } return _data[index]; } set { if (_data == null) { _data = new List<int?>(); } while (_data.Count <= index) { _data.Add(null); } _data[index] = value; } } } public class Indexable { private Hashtable ht = new Hashtable(); public string this[int index] { get { return (string)ht[index]; } set { ht[index] = value; } } public string this[string index] { get { return (string)ht[index]; } set { ht[index] = value; } } public string this[double index] { get { return (string)ht[index]; } set { ht[index] = value; } } public string this[int i, int j] { get { string ret = (string)ht[new Tuple(i, j)]; return ret; } set { ht[new Tuple(i, j)] = value; } } public string this[int i, double j] { get { return (string)ht[new Tuple(i, j)]; } set { ht[new Tuple(i, j)] = value; } } public string this[int i, string j] { get { return (string)ht[new Tuple(i, j)]; } set { ht[new Tuple(i, j)] = value; } } public string this[double i, int j] { get { return (string)ht[new Tuple(i, j)]; } set { ht[new Tuple(i, j)] = value; } } public string this[double i, double j] { get { return (string)ht[new Tuple(i, j)]; } set { ht[new Tuple(i, j)] = value; } } public string this[double i, string j] { get { return (string)ht[new Tuple(i, j)]; } set { ht[new Tuple(i, j)] = value; } } public string this[string i, int j] { get { return (string)ht[new Tuple(i, j)]; } set { ht[new Tuple(i, j)] = value; } } public string this[string i, double j] { get { return (string)ht[new Tuple(i, j)]; } set { ht[new Tuple(i, j)] = value; } } public string this[string i, string j] { get { return (string)ht[new Tuple(i, j)]; } set { ht[new Tuple(i, j)] = value; } } } public class IndexableList : IList { private List<object> myList = new List<object>(); public object this[string index] { get { return myList[Int32.Parse(index)]; } set { myList[Int32.Parse(index)] = value; } } #region IList Members public int Add(object value) { int res = myList.Count; myList.Add(value); return res; } public void Clear() { myList.Clear(); } public bool Contains(object value) { return myList.Contains(value); } public int IndexOf(object value) { return myList.IndexOf(value); } public void Insert(int index, object value) { myList.Insert(index, value); } public bool IsFixedSize { get { return false; } } public bool IsReadOnly { get { return false; } } public void Remove(object value) { myList.Remove(value); } public void RemoveAt(int index) { myList.RemoveAt(index); } public object this[int index] { get { return myList[index]; } set { myList[index] = value; } } #endregion #region ICollection Members public void CopyTo(Array array, int index) { throw new NotImplementedException(); } public int Count { get { return myList.Count; } } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { throw new Exception("The method or operation is not implemented."); } } #endregion #region IEnumerable Members public IEnumerator GetEnumerator() { return myList.GetEnumerator(); } #endregion } public class PropertyAccessClass { public int this[int i] { get { return i; } set { if (i != value) { throw new IndexOutOfRangeException(); } } } public int this[int i, int j] { get { return i + j; } set { if (i + j != value) { throw new IndexOutOfRangeException(); } } } public int this[int i, int j, int k] { get { return i + j + k; } set { if (i + j + k != value) { throw new IndexOutOfRangeException(); } } } } public class MultipleIndexes { private Dictionary<object, object> ht = new Dictionary<object, object>(); // works like Hashtable indexer--returns null instead of throwing if the key isn't found private object GetValue(Tuple t) { object result; ht.TryGetValue(t, out result); return result; } public object this[object i] { get { return GetValue(new Tuple(i)); } set { ht[new Tuple(i)] = value; } } public object this[object i, object j] { get { return GetValue(new Tuple(i, j)); } set { ht[new Tuple(i, j)] = value; } } public object this[object i, object j, object k] { get { return GetValue(new Tuple(i, j, k)); } set { ht[new Tuple(i, j, k)] = value; } } public object this[object i, object j, object k, object l] { get { return GetValue(new Tuple(i, j, k, l)); } set { ht[new Tuple(i, j, k, l)] = value; } } public object this[object i, object j, object k, object l, object m] { get { return GetValue(new Tuple(i, j, k, l, m)); } set { ht[new Tuple(i, j, k, l, m)] = value; } } } // TODO: LastIndexOf public class UsePythonListAsList { private IList<int> list; public UsePythonListAsList(IList<int> list) { this.list = list; } public int Inspect() { list.Clear(); for (int i = 0; i < 100; i++) list.Add(i); int flag = 0; if (list.IndexOf(5) == 5) flag += 1; if (list.IndexOf(1000) == -1) flag += 10; if (list[5] == 5) flag += 100; if (list.Remove(5)) flag += 1000; if (list.IndexOf(5) == -1) flag += 10000; return flag; } public void AddRemove() { int value = 20; list.Insert(0, value); list.Insert(3, value); list.Insert(5, value); list.Insert(list.Count, value); list[list.Count / 2] = value; list.RemoveAt(2); list.RemoveAt(list.Count - 1); } public int Loop() { int sum = 0; foreach (int t in list) sum += t; return sum; } } public class UsePythonListAsArrayList { private ArrayList list; public UsePythonListAsArrayList(ArrayList list) { this.list = list; } public void AddRemove() { foreach (object o in new object[] { 1, 2L, "string", typeof(int) }) { list.Add(o); } list.Remove(2L); list.RemoveAt(0); list.RemoveRange(1, 2); list.Reverse(); list.InsertRange(1, new object[] { 100, 30.4, (byte)3 }); list.SetRange(list.Count - 2, new object[] { (ushort)20, -200 }); list.Reverse(); //list.Capacity = list.Count / 2; } public int Inspect() { list.Clear(); for (int i = 0; i < 10; i++) list.Add(i); list.AddRange(new string[] { "a", "bc" }); int flag = 0; if (list.IndexOf("a") == 10 && list.IndexOf(4, 3) == 4 && list.IndexOf(4, 6) == -1 && list.IndexOf(3, 1, 4) == 3 && list.IndexOf(4, 1, 10) == 4 && list.IndexOf(3, 7, 3) == -1 && list.LastIndexOf("a") == 10 && list.LastIndexOf("bc") == 11 && list.LastIndexOf(4, 5) == 4 && list.LastIndexOf(4, 6, 2) == -1 && list.LastIndexOf(4, 6, 3) == 4 && list.LastIndexOf(1, 6, 5) == -1 && list.LastIndexOf(1, 6, 6) == 1 && list.LastIndexOf(0, 6, 6) == -1 && list.LastIndexOf(0, 6, 7) == 0 ) flag += 1; if (list.Count == 12) flag += 10; if (list.Contains(8)) flag += 100; if (list.Contains("abc") == false) flag += 1000; if (list.BinarySearch("5", new MyComparer()) == 5 && list.BinarySearch(0, 10, "a", new MyComparer()) == -1 && list.BinarySearch(0, 10, 5, new MyComparer()) == 5 ) flag += 10000; return flag; } public int Loop(out string strs) { strs = null; int sum = 0; foreach (object o in list) { if (o is int) { sum += (int)o; } else if (o is string) { strs += (string)o; } } return sum; } private class MyComparer : IComparer { public int Compare(object x, object y) { return string.Compare(x.ToString(), y.ToString(), StringComparison.Ordinal); } } } public class UsePythonDictAsDictionary { private IDictionary<string, int> dict; public UsePythonDictAsDictionary(IDictionary<string, int> dict) { this.dict = dict; } public void AddRemove() { dict.Add("hello", 1000); dict.Add(new KeyValuePair<string, int>("world", 2000)); dict.Add("python", 3000); dict.Remove("python"); } public int Inspect(out string keys, out int values) { dict.Clear(); for (int i = 0; i < 10; i++) dict.Add(i.ToString(), i); int flag = 0; if (dict.ContainsKey("5")) flag += 1; if (dict["5"] == 5) flag += 10; if (dict.Count == 10) flag += 100; int val; if (dict.TryGetValue("6", out val)) flag += 1000; if (dict.TryGetValue("spam", out val) == false) flag += 10000; keys = string.Empty; foreach (string s in SortedArray(dict.Keys, null)) { keys += s; } values = 0; foreach (int v in dict.Values) { values += v; } return flag; } private T[] SortedArray<T>(ICollection<T> value, Comparison<T> comparer) { T[] array = new T[value.Count]; value.CopyTo(array, 0); if (comparer != null) { Array.Sort(array, comparer); } else { Array.Sort(array); } return array; } private static int KeyValueComparer(KeyValuePair<string, int> x, KeyValuePair<string, int> y) { return string.Compare(x.Key, y.Key, StringComparison.Ordinal); } public void Loop(out string keys, out int values) { keys = string.Empty; values = 0; foreach (KeyValuePair<string, int> pair in SortedArray(dict, KeyValueComparer)) { keys += pair.Key; values += pair.Value; } } } public class CSharpEnumerable { public IEnumerable<int> GetEnumerableOfInt() { yield return 1; yield return 2; yield return 3; } public IEnumerable<object> GetEnumerableOfObject() { yield return 1; yield return 2; yield return 3; } public IEnumerable GetEnumerable() { yield return 1; yield return 2; yield return 3; } public IEnumerator<int> GetEnumeratorOfInt() { yield return 1; yield return 2; yield return 3; } public IEnumerator<object> GetEnumeratorOfObject() { yield return 1; yield return 2; yield return 3; } public IEnumerator GetEnumerator() { yield return 1; yield return 2; yield return 3; } } public class UsePythonDictAsHashtable { private Hashtable table; public UsePythonDictAsHashtable(Hashtable table) { this.table = table; } public void AddRemove() { table.Add(200, 400); table.Add("spam", "spam"); table.Remove("spam"); } public int Inspect(out int keysum, out int valuesum) { table.Clear(); for (int i = 0; i < 10; i++) { table.Add(i, i * i); } int flag = 0; if (table.Contains(0)) flag += 1; if (table.Contains("0") == false) flag += 10; if (table.ContainsKey(3)) flag += 100; if (table.ContainsValue(81)) flag += 1000; if ((int)table[8] == 64) flag += 10000; table[8] = 89; if ((int)table[8] == 89) flag += 100000; if (table.Count == 10) flag += 1000000; keysum = 0; foreach (object o in table.Keys) { keysum += (int)o; } valuesum = 0; foreach (object o in table.Values) { valuesum += (int)o; } return flag; } public int Loop() { int sum = 0; IDictionaryEnumerator ide = table.GetEnumerator(); while (ide.MoveNext()) { sum += (int)ide.Value; sum += (int)ide.Key; } return sum; } } }
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Collections; using System.Collections.Generic; using System.Net; using System.IO; using System.Text; using System.Security.Cryptography; using System.Xml; /// <summary> /// Summary description for SmartmessagesAPI /// </summary> public class SmartmessagesAPI { /// <summary> /// The authenticated access key for this session /// </summary> protected string accesskey = String.Empty; /// <summary> /// The API endpoint to direct requests at, set during login /// </summary> protected string endpoint = String.Empty; /// <summary> /// Whether we have logged in successfully /// </summary> public bool connected = false; /// <summary> /// Timestamp of when this session expires /// </summary> public int expires = 0; /// <summary> /// The user name used to log in to the API, usually an email address /// </summary> public string accountname = String.Empty; /// <summary> /// The most recent status message received from the API - true for success, false otherwise /// </summary> public bool laststatus = true; /// <summary> /// The most recent error code received. 0 if no error. /// </summary> public int errorcode = 0; /// <summary> /// The most recent message received in an API response. Does not necessarily indicate an error, /// may have some other informational content. /// </summary> public string message = String.Empty; /// <summary> /// Whether to run in debug mode. With this enabled, all requests and responses generate descriptive output /// </summary> public bool debug = false; /// <summary> /// Constructor, creates a new Smartmessages API instance with debugging set to false /// </summary> public SmartmessagesAPI() { this.debug = false; } /// <summary> /// Constructor override, creates a new Smartmessages API instance with debug option /// </summary> public SmartmessagesAPI(bool debug) { this.debug = debug; } /// <summary> /// Open a session with the Smartmessages API /// Throws an exception if login fails /// @param string user - The user name (usually an email address) /// @param string password /// @param string apikey - The API key as shown on the settings page of the smartmessages UI /// @return boolean true if login was successful /// @access public /// </summary> public bool login(string user, string pass, string apikey) { string baseurl = "https://www.smartmessages.net/api/"; return login(user, pass, apikey, baseurl); } /// <summary> /// Open a session with the Smartmessages API /// Throws an exception if login fails /// @param string user - The user name (usually an email address) /// @param string password /// @param string apikey - The API key as shown on the settings page of the smartmessages UI /// @param string baseurl - The initial entry point for the Smartmessage API /// @return boolean true if login was successful /// @access public /// </summary> public bool login(string user, string pass, string apikey, string baseurl) { Hashtable request_params = new Hashtable(); request_params["username"] = user; request_params["password"] = pass; request_params["apikey"] = apikey; request_params["outputformat"] = "xml"; string response = dorequest("login", request_params, baseurl); DataSet ds = new DataSet("login"); ds.ReadXml(new StringReader(response)); this.connected = true; this.accesskey = ds.Tables["response"].Rows[0]["accesskey"].ToString().Trim(); this.endpoint = ds.Tables["response"].Rows[0]["endpoint"].ToString().Trim(); this.expires = int.Parse(ds.Tables["response"].Rows[0]["expires"].ToString().Trim()); this.accountname = ds.Tables["response"].Rows[0]["accountname"].ToString().Trim(); return true; } /// <summary> /// Close a session with the Smartmessages API /// @access public /// </summary> public void logout() { dorequest("logout"); this.connected = false; this.accesskey = String.Empty; this.expires = 0; } /// <summary> /// Does nothing, but keeps a connection open and extends the session expiry time /// @access public /// </summary> public bool ping() { string response = dorequest("ping"); DataSet ds = new DataSet("ping"); ds.ReadXml(new StringReader(response)); return ds.Tables["response"].Rows[0]["status"].ToString()=="0"?false:true; } /// <summary> /// Subscribe an address to a list /// @see getlists() /// @param string address The email address /// @param integer listid The ID of the list to subscribe the user to /// @param string dear A preferred greeting that's not necessarily their actual name, such as 'Scooter', 'Mrs Smith', 'Mr President' /// @param string firstname /// @param string lastname /// @return boolean true if subscribe was successful /// @access public /// </summary> public bool subscribe(string address, string listid, string dear, string firstname, string lastname) { if (address.Trim() == "" || int.Parse(listid) <= 0) { throw new SmartmessagesAPIException("Invalid subscribe parameters"); } Hashtable request_params = new Hashtable(); request_params["address"] = address; request_params["listid"] = listid; request_params["dear"] = dear; request_params["firstname"] = firstname; request_params["lastname"] = lastname; string response = dorequest("subscribe", request_params); DataSet ds = new DataSet("subscribe"); ds.ReadXml(new StringReader(response)); return ds.Tables["response"].Rows[0]["status"].ToString()=="0"?false:true; } public bool subscribe(string address, string listid) { return subscribe(address, listid, "", "", ""); } /// <summary> /// Unsubscribe an address from a list /// @see getlists() /// @param string address The email address /// @param integer listid The ID of the list to unsubscribe the user from /// @return boolean true if unsubscribe was successful /// @access public /// </summary> public bool unsubscribe(string address, string listid) { if (address.Trim() == "" || int.Parse(listid) <= 0) { throw new SmartmessagesAPIException("Invalid unsubscribe parameters"); } Hashtable request_params = new Hashtable(); request_params["address"] = address; request_params["listid"] = listid; string response = dorequest("unsubscribe", request_params); DataSet ds = new DataSet("unsubscribe"); ds.ReadXml(new StringReader(response)); return ds.Tables["response"].Rows[0]["status"].ToString()=="0"?false:true; } /// <summary> /// Get the details of all the mailing lists in your account /// @return DataTable /// @access public /// </summary> public DataTable getlists() { string response = dorequest("getlists"); DataSet ds = new DataSet("getlists"); ds.ReadXml(new StringReader(response)); return ds.Tables["element"]; } /** * Get info about a recipient * @param string address The email address * @return array Info about the user * @access public */ public DataSet getuserinfo(string address) { if (address.Trim() == "") { throw new SmartmessagesAPIException("Invalid email address"); } Hashtable request_params = new Hashtable(); request_params["address"] = address; string response = dorequest("getuserinfo", request_params); DataSet ds = new DataSet("getuserinfo"); ds.ReadXml(new StringReader(response)); return ds; } /** * Set info about a recipient * @see getuserinfo() * @param string address The email address * @param array userinfo Array of user properties in the same format as returned by getuserinfo() * @return boolean true on success * @access public */ public bool setuserinfo(string address, string userinfo) { if (address.Trim() == "") { throw new SmartmessagesAPIException("Invalid email address"); } string request_params = "address=" + address + "&" + userinfo; string response = dorequest("setuserinfo", request_params); DataSet ds = new DataSet("setuserinfo"); ds.ReadXml(new StringReader(response)); return ds.Tables["response"].Rows[0]["status"].ToString() == "0" ? false : true; } /// <summary> /// Get a list of everyone that has reported messages from you as spam /// Only available from some ISPs, notably hotmail and AOL /// @return DataSet /// @access public /// </summary> public DataSet getspamreporters() { string response = dorequest("getspamreporters"); DataSet ds = new DataSet("spamreporters"); ds.ReadXml(new StringReader(response)); return ds; } /// <summary> /// Get your current default import field order list /// @return array /// @access public /// </summary> public DataTable getfieldorder() { string response = dorequest("getfieldorder"); DataSet ds = new DataSet("getfieldorder"); ds.ReadXml(new StringReader(response)); return ds.Tables["element"]; } /// <summary> /// Get your current default import field order list /// The field list MUST include emailaddress /// Any invalid or unknown names will be ignored /// @see getfieldorder() /// @param array $fields Simple array of field names /// @return array The array of field names that was set, after filtering /// @access public /// </summary> public DataTable setfieldorder(string fields) { if (fields == String.Empty || fields.IndexOf("emailaddress") == -1) { throw new SmartmessagesAPIException("Invalid field order"); } Hashtable request_params = new Hashtable(); request_params["fields"] = fields.Replace(",","%2C"); string response = dorequest("setfieldorder", request_params); DataSet ds = new DataSet("setfieldorder"); ds.ReadXml(new StringReader(response)); return ds.Tables["element"]; } /// <summary> /// Get a list of everyone that has unsubscribed from the specified mailing list /// @return DataTable /// @access public /// </summary> public DataTable getlistunsubs(string listid) { if (int.Parse(listid) <= 0) { throw new SmartmessagesAPIException("Invalid list id"); } Hashtable request_params = new Hashtable(); request_params["listid"] = listid; string response = dorequest("getlistunsubs", request_params); DataSet ds = new DataSet("getlistunsubs"); ds.ReadXml(new StringReader(response)); return ds.Tables["element"]; } /// <summary> /// Upload a mailing list /// @see getlists() /// @see getfieldorder() /// @see getuploadinfo() /// @param string listid The ID of the list to upload into /// @param string listfilename A path to a local file containing your mailing list in CSV format (may also be zipped) /// @param string source For audit trail purposes, you must populate this with a note of where this list came from /// @param boolean definitive If set to true, overwrite any existing data in the fields included in the file, otherwise existing data will not be touched, but recipients will still be added to the list /// @param boolean replace Whether to empty the list before uploading this list /// @param boolean fieldorderfirstline Set to true if the first line of the file contains field names /// @return integer|boolean On success, the upload ID for passing to getuploadinfo(), otherwise boolean false /// @access public /// </summary> public object uploadlist(string listid, string listfilename, string source, bool definitive, bool replace, bool fieldorderfirstline) { if (int.Parse(listid) <= 0) { throw new SmartmessagesAPIException("Invalid list id"); } if (!File.Exists(listfilename)) { throw new SmartmessagesAPIException("File does not exist!"); } if (filesize(listfilename) < 6) { //This is the smallest a single external email address could possibly be throw new SmartmessagesAPIException("File does not contain any data!"); } Hashtable request_params = new Hashtable(); request_params["method"] = "uploadlist"; request_params["listid"] = listid; request_params["source"] = source; request_params["definitive"] = definitive==true?"true":"false"; request_params["replace"] = replace==true?"true":"false"; request_params["fieldorderfirstline"] = fieldorderfirstline==true?"true":"false"; Hashtable files = new Hashtable(); files[listfilename] = listfilename; string response = dorequest("uploadlist", request_params, null, true, files); DataSet ds = new DataSet("uploadlist"); ds.ReadXml(new StringReader(response)); //Return the upload ID on success, or false if it failed if(ds.Tables["response"].Rows[0]["status"].ToString()=="0") return false; else return ds.Tables["response"].Rows[0]["uploadid"].ToString(); } /// <summary> /// Get info on a previous list upload /// @see getlists() /// @see getfieldorder() /// @see uploadlist() /// @param string listid The ID of the list the upload belongs to /// @param string uploadid The ID of the upload (as returned from uploadlist()) /// @return DataTable A list of upload properties. Includes lists of bad or invalid addresses, source tracking field /// @access public /// </summary> public DataTable getuploadinfo(string listid, string uploadid) { if (int.Parse(listid) <= 0 || int.Parse(uploadid) <= 0) { throw new SmartmessagesAPIException("Invalid getuploadinfo parameters"); } Hashtable request_params = new Hashtable(); request_params["listid"] = listid; request_params["uploadid"] = uploadid; string response = dorequest("getuploadinfo", request_params); DataSet ds = new DataSet("getuploadinfo"); ds.ReadXml(new StringReader(response)); return ds.Tables["element"]; } /// <summary> /// Get info on all previous list uploads /// Only gives basic info on each upload, more detail can be obtained using getuploadinfo() /// @see getlists() /// @see uploadlist() /// @see getuploadinfo() /// @param integer listid The ID of the list the upload belongs to /// @return DataTable An array of uploads with properties for each. /// @access public /// </summary> public DataTable getuploads(string listid) { if (int.Parse(listid) <= 0) { throw new SmartmessagesAPIException("Invalid getuploads parameters"); } Hashtable request_params = new Hashtable(); request_params["listid"] = listid; string response = dorequest("getuploads", request_params); DataSet ds = new DataSet("getuploads"); ds.ReadXml(new StringReader(response)); return ds.Tables["element"]; } /// <summary> /// Cancel a pending or in-progress upload /// Cancelled uploads are deleted, so won't appear in getuploads() /// Deletions are asynchronous, so won't happen immediately /// @see getlists() /// @see uploadlist() /// @param string listid The ID of the list the upload belongs to /// @param string uploadid The ID of the upload (as returned from uploadlist()) /// @return boolean true on success /// @access public /// </summary> public bool cancelupload(string listid, string uploadid) { if (int.Parse(listid) <= 0 || int.Parse(uploadid) <= 0) { throw new SmartmessagesAPIException("Invalid getuploadinfo parameters"); } Hashtable request_params = new Hashtable(); request_params["listid"] = listid; request_params["uploadid"] = uploadid; string response = dorequest("cancelupload", request_params); DataSet ds = new DataSet("cancelupload"); ds.ReadXml(new StringReader(response)); return ds.Tables["response"].Rows[0]["status"].ToString()=="0"?false:true; } /// <summary> /// Get the callback URL for your account /// Read our support wiki for more details on this /// @return string /// @access public /// </summary> public string getcallbackurl() { string response = dorequest("getcallbackurl"); DataSet ds = new DataSet("getcallbackurl"); ds.ReadXml(new StringReader(response)); return ds.Tables["response"].Rows[0]["url"].ToString(); } /// <summary> /// Set the callback URL for your account /// Read our support wiki for more details on this /// @param string url The URL of your callback script (this will be on YOUR web server, not ours) /// @return true on success /// @access public /// </summary> public bool setcallbackurl(string url) { if (url.Trim() == "") { throw new SmartmessagesAPIException("Invalid setcallbackurl url"); } Hashtable request_params = new Hashtable(); request_params["url"] = url; string response = dorequest("setcallbackurl", request_params); DataSet ds = new DataSet("setcallbackurl"); ds.ReadXml(new StringReader(response)); return ds.Tables["response"].Rows[0]["status"].ToString()=="0"?false:true; } /// <summary> /// Simple address validator /// It's more efficient to use a function on your own site to do this, but using this will ensure that any address you add to a list will also be accepted by us /// If you encounter an address that we reject that you think we shouldn't, please tell us! /// Read our support wiki for more details on this /// @return boolean /// @access public /// </summary> public bool validateaddress(string address) { Hashtable request_params = new Hashtable(); request_params["address"] = address; string response = dorequest("validateaddress", request_params); DataSet ds = new DataSet("validateaddress"); ds.ReadXml(new StringReader(response)); return ds.Tables["response"].Rows[0]["valid"].ToString() == "0" ? false : true; } protected string dorequest(string command) { Hashtable request_params = new Hashtable(); return dorequest(command, request_params, String.Empty, false, new Hashtable()); } protected string dorequest(string command, Hashtable request_params) { return dorequest(command, request_params, String.Empty, false, new Hashtable()); } protected string dorequest(string command, Hashtable request_params, string urloverride) { return dorequest(command, request_params, urloverride, false, new Hashtable()); } protected string dorequest(string command, Hashtable request_params, string urloverride, bool post, Hashtable files) { string response = ""; //All commands except login need an accesskey if (this.accesskey != String.Empty) { if (!request_params.ContainsKey("accesskey")) request_params.Add("accesskey", this.accesskey); } if(!request_params.ContainsKey("outputformat")) request_params.Add("outputformat", "xml"); // XML is default output format string url = ""; if (urloverride == String.Empty || urloverride == null) { if (this.endpoint == String.Empty) { //We can't connect throw new SmartmessagesAPIException("Missing Smartmessages API URL"); } else { url = this.endpoint; } } else { url = urloverride; } url += command; //Make the request if (post) { if (this.debug) { HttpContext.Current.Response.Write("<h1>POST Request (" + htmlspecialchars(command) + "):</h1><p>" + htmlspecialchars(url) + "</p>\n"); } response = do_post_request(url, request_params, files); } else { if (request_params != null && request_params.Count > 0) { url += '?' + http_build_query(request_params); } if (this.debug) { HttpContext.Current.Response.Write("<h1>GET Request (" + htmlspecialchars(command) +"):</h1><p>" + htmlspecialchars(url) + "</p>\n"); } response = url_get_contents(url); } return response; } protected string dorequest(string command, string request_params) { string response = ""; //All commands except login need an accesskey if (request_params.IndexOf("accesskey") == -1) request_params += "&accesskey=" + this.accesskey; if(request_params.IndexOf("outputformat") == -1) request_params += "&outputformat=xml"; // XML is default output format string url = ""; if (this.endpoint == String.Empty) { //We can't connect throw new SmartmessagesAPIException("Missing Smartmessages API URL"); } else { url = this.endpoint; } url += command; //Make the request if (request_params != null && request_params != String.Empty) { url += '?' + request_params.Replace("[", "%5B").Replace("]", "%5D"); } if (this.debug) { HttpContext.Current.Response.Write("<h1>GET Request (" + htmlspecialchars(command) +"):</h1><p>" + htmlspecialchars(url) + "</p>\n"); } response = url_get_contents(url); return response; } private string do_post_request(string url, Hashtable postdata, Hashtable files) { string response = ""; string data = ""; string boundary = "---------------------" + md5(rand(0,32000)).Substring(0, 10); //Collect Postdata foreach(string key in postdata.Keys) { data += "--" + boundary + "\n"; data += "Content-Disposition: form-data; name=\"" + key + "\"\n\n" + postdata[key].ToString() + "\n"; } data += "--" + boundary + "\n"; //Collect Filedata foreach(string key in files.Keys) { string file = files[key].ToString(); string filename = basename(file); data += "Content-Disposition: form-data; name=\""+ filename + "\"; filename=\"" + filename + "\"\n"; data += "Content-Type: application/octet-stream\n"; //Could be anything, so just upload as raw binary stuff data += "Content-Transfer-Encoding: binary\n\n"; data += file_get_contents(file) + "\n"; data += "--" + boundary + "--\n"; } if (this.debug) { HttpContext.Current.Response.Write("<h2>POST body:</h2><pre>"); if(data.Length > 8192) HttpContext.Current.Response.Write(htmlspecialchars(data).Substring(0, 8192)); //Limit size of debug output else HttpContext.Current.Response.Write(htmlspecialchars(data)); HttpContext.Current.Response.Write("</pre>\n"); } url = "http://www.smartmessages.net/api/uploadlist"; url += "?accesskey=" + postdata["accesskey"].ToString() + "&outputformat=xml"; HttpWebRequest wrq = (HttpWebRequest)HttpWebRequest.Create(url); wrq.Method = "POST"; wrq.ContentType = "multipart/form-data; boundary=" + boundary; byte[] bin_data = Encoding.UTF8.GetBytes(data); wrq.ContentLength = bin_data.Length; Stream writeStream = wrq.GetRequestStream(); writeStream.Write(bin_data, 0, bin_data.Length); writeStream.Close(); HttpWebResponse wrs = (HttpWebResponse)wrq.GetResponse(); StreamReader sr = new StreamReader(wrs.GetResponseStream()); response = sr.ReadToEnd(); return response; } private string url_get_contents(string address) { HttpWebRequest wrq = (HttpWebRequest)HttpWebRequest.Create(address); HttpWebResponse wrs = (HttpWebResponse)wrq.GetResponse(); StreamReader sr = new StreamReader(wrs.GetResponseStream()); return sr.ReadToEnd(); } private string htmlspecialchars(string input) { input.Replace("&", "&amp;"); input.Replace("\"", "&quot;"); input.Replace("'", "&#039;"); input.Replace("<", "&lt;"); input.Replace(">", "&gt;"); return input; } private string http_build_query(Hashtable request_params) { string query = ""; int i = 0; foreach (string key in request_params.Keys) { if (i != 0) query += "&" + key + "=" + request_params[key].ToString(); else query += key + "=" + request_params[key].ToString(); i++; } return query; } private string rand(int min, int max) { Random random = new Random(); return random.Next(min, max).ToString(); } private string md5(string input) { Encoder enc = System.Text.Encoding.Unicode.GetEncoder(); byte[] unicodeText = new byte[input.Length * 2]; enc.GetBytes(input.ToCharArray(), 0, input.Length, unicodeText, 0, true); MD5 md5Service = new MD5CryptoServiceProvider(); byte[] result = md5Service.ComputeHash(unicodeText); StringBuilder sb = new StringBuilder(); for (int i=0;i<result.Length;i++) { sb.Append(result[i].ToString("X2")); } return sb.ToString(); } private string basename(string input) { input = input.Replace("\\", "/"); //Windows style file paths string[] _input = input.Split('/'); return _input[_input.Length - 1]; } private string file_get_contents(string filepath) { string file_contents = ""; StreamReader stream = new StreamReader(filepath); file_contents = stream.ReadToEnd(); stream.Dispose(); stream.Close(); return file_contents; } private long filesize(string filepath) { FileInfo finfo = new FileInfo(filepath); return finfo.Length; } } class SmartmessagesAPIException : ArgumentException { public SmartmessagesAPIException() : base() { } public SmartmessagesAPIException(string message) : base(message) { } }
// file: Model\DescriptorProperty.cs // // summary: Implements the descriptor property class using System; using System.IO; using numl.Utils; using System.Linq; using System.Reflection; using System.Collections.Generic; using numl.Math.LinearAlgebra; using System.Text; using System.Linq.Expressions; using System.Collections; namespace numl.Model { /// <summary> /// Fluent API addition for simplifying the process of adding features and labels to a descriptor. /// </summary> public class DescriptorProperty { /// <summary>The descriptor.</summary> private readonly Descriptor _descriptor; /// <summary>The name.</summary> private readonly string _name; /// <summary>true to label.</summary> private readonly bool _label; /// <summary>internal constructor used for creating chaining.</summary> /// <param name="descriptor">descriptor.</param> /// <param name="name">name of property.</param> /// <param name="label">label property?</param> internal DescriptorProperty(Descriptor descriptor, string name, bool label) { _label = label; _name = name; _descriptor = descriptor; } /// <summary>Not ready.</summary> /// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception> /// <param name="conversion">Conversion method.</param> /// <returns>Descriptor.</returns> public Descriptor Use(Func<object, double> conversion) { //TODO: Requires implementation... ? throw new NotImplementedException("Not yet ;)"); //return _descriptor; } /// <summary>Adds property to descriptor with chained name and type.</summary> /// <param name="type">Property Type.</param> /// <returns>descriptor with added property.</returns> public Descriptor As(Type type) { Property p; if (_label) p = TypeHelpers.GenerateLabel(type, _name); else p = TypeHelpers.GenerateFeature(type, _name); AddProperty(p); return _descriptor; } /// <summary> /// Adds the specified property to the descriptor with the chained name /// </summary> /// <param name="property">The property.</param> /// <returns>descriptor with added property</returns> public Descriptor As(Property property) { property.Name = _name; AddProperty(property); return _descriptor; } /// <summary> /// Adds the default string property to descriptor with previously chained name. /// </summary> /// <returns>descriptor with added property.</returns> public Descriptor AsString() { StringProperty p = new StringProperty(); p.Name = _name; p.AsEnum = _label; AddProperty(p); return _descriptor; } /// <summary>Adds string property to descriptor with previously chained name.</summary> /// <param name="splitType">How to split string.</param> /// <param name="separator">(Optional) Separator to use.</param> /// <param name="exclusions">(Optional) file describing strings to exclude.</param> /// <returns>descriptor with added property.</returns> public Descriptor AsString(StringSplitType splitType, string separator = " ", string exclusions = null) { StringProperty p = new StringProperty(); p.Name = _name; p.SplitType = splitType; p.Separator = separator; p.ImportExclusions(exclusions); p.AsEnum = _label; AddProperty(p); return _descriptor; } /// <summary> /// Adds a string property with character segmentation treated as enumerations to the descriptor. /// </summary> /// <returns>Descriptor.</returns> public Descriptor AsCharEnum() { StringProperty p = new StringProperty(); p.Name = _name; p.AsEnum = true; AddProperty(p); return _descriptor; } /// <summary>Adds string property to descriptor with previously chained name.</summary> /// <returns>descriptor with added property.</returns> public Descriptor AsStringEnum() { StringProperty p = new StringProperty(); p.Name = _name; p.AsEnum = true; AddProperty(p); return _descriptor; } /// <summary>Adds guid property to descriptor with previously chained name.</summary> /// <returns>descriptor with added property.</returns> public Descriptor AsGuid() { GuidProperty p = new GuidProperty(); p.Name = _name; AddProperty(p); return _descriptor; } /// <summary>Adds DateTime property to descriptor with previously chained name.</summary> /// <exception cref="DescriptorException">Thrown when a Descriptor error condition occurs.</exception> /// <param name="features">Which date features to use (can pipe: DateTimeFeature.Year | /// DateTimeFeature.DayOfWeek)</param> /// <returns>descriptor with added property.</returns> public Descriptor AsDateTime(DateTimeFeature features) { if (_label) throw new DescriptorException("Cannot use a DateTime property as a label"); var p = new DateTimeProperty(features) { Discrete = true, Name = _name }; AddProperty(p); return _descriptor; } /// <summary>Adds DateTime property to descriptor with previously chained name.</summary> /// <exception cref="DescriptorException">Thrown when a Descriptor error condition occurs.</exception> /// <param name="portion">Which date portions to use (can pipe: DateTimeFeature.Year | /// DateTimeFeature.DayOfWeek)</param> /// <returns>descriptor with added property.</returns> public Descriptor AsDateTime(DatePortion portion) { if (_label) throw new DescriptorException("Cannot use an DateTime property as a label"); var p = new DateTimeProperty(portion) { Discrete = true, Name = _name }; AddProperty(p); return _descriptor; } /// <summary>Adds Enumerable property to descriptor with previousy chained name.</summary> /// <exception cref="DescriptorException">Thrown when a Descriptor error condition occurs.</exception> /// <param name="length">length of enumerable to expand.</param> /// <returns>descriptor with added property.</returns> public Descriptor AsEnumerable(int length) { if (_label) throw new DescriptorException("Cannot use an Enumerable property as a label"); var p = new EnumerableProperty(length) { Name = _name, Discrete = false }; AddProperty(p); return _descriptor; } /// <summary>Adds a property.</summary> /// <param name="p">The Property to process.</param> private void AddProperty(Property p) { if (_label) _descriptor.Label = p; else { var features = new List<Property>(_descriptor.Features ?? new Property[] { }) { p }; _descriptor.Features = features.ToArray(); } } } }
// JsonArray.cs // DynamicRest provides REST service access using C# 4.0 dynamic programming. // The latest information and code for the project can be found at // https://github.com/NikhilK/dynamicrest // // This project is licensed under the BSD license. See the License.txt file for // more information. // using System; using System.Collections; using System.Collections.Generic; using System.Dynamic; namespace DynamicRest.Json { public sealed class JsonArray : DynamicObject, ICollection<object>, ICollection { private List<object> _members; public JsonArray() { _members = new List<object>(); } public JsonArray(object o) : this() { _members.Add(o); } public JsonArray(object o1, object o2) : this() { _members.Add(o1); _members.Add(o2); } public JsonArray(params object[] objects) : this() { _members.AddRange(objects); } public int Count { get { return _members.Count; } } public object this[int index] { get { return _members[index]; } } public override bool TryConvert(ConvertBinder binder, out object result) { Type targetType = binder.Type; if ((targetType == typeof(IEnumerable)) || (targetType == typeof(IEnumerable<object>)) || (targetType == typeof(ICollection<object>)) || (targetType == typeof(ICollection))) { result = this; return true; } return base.TryConvert(binder, out result); } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { if (String.Compare(binder.Name, "Add", StringComparison.Ordinal) == 0) { if (args.Length == 1) { _members.Add(args[0]); result = null; return true; } result = null; return false; } else if (String.Compare(binder.Name, "Insert", StringComparison.Ordinal) == 0) { if (args.Length == 2) { _members.Insert(Convert.ToInt32(args[0]), args[1]); result = null; return true; } result = null; return false; } else if (String.Compare(binder.Name, "IndexOf", StringComparison.Ordinal) == 0) { if (args.Length == 1) { result = _members.IndexOf(args[0]); return true; } result = null; return false; } else if (String.Compare(binder.Name, "Clear", StringComparison.Ordinal) == 0) { if (args.Length == 0) { _members.Clear(); result = null; return true; } result = null; return false; } else if (String.Compare(binder.Name, "Remove", StringComparison.Ordinal) == 0) { if (args.Length == 1) { result = _members.Remove(args[0]); return true; } result = null; return false; } else if (String.Compare(binder.Name, "RemoveAt", StringComparison.Ordinal) == 0) { if (args.Length == 1) { _members.RemoveAt(Convert.ToInt32(args[0])); result = null; return true; } result = null; return false; } return base.TryInvokeMember(binder, args, out result); } public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) { if (indexes.Length == 1) { result = _members[Convert.ToInt32(indexes[0])]; return true; } return base.TryGetIndex(binder, indexes, out result); } public override bool TryGetMember(GetMemberBinder binder, out object result) { if (String.Compare("Length", binder.Name, StringComparison.Ordinal) == 0) { result = _members.Count; return true; } var memberExists = base.TryGetMember(binder, out result); if (result == null) { throw new DynamicParsingException(string.Format("No member named '{0}' found in the response.", binder.Name)); } return memberExists; } public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value) { if (indexes.Length == 1) { _members[Convert.ToInt32(indexes[0])] = value; return true; } return base.TrySetIndex(binder, indexes, value); } #region Implementation of IEnumerable IEnumerator IEnumerable.GetEnumerator() { return _members.GetEnumerator(); } #endregion #region Implementation of IEnumerable<object> IEnumerator<object> IEnumerable<object>.GetEnumerator() { return _members.GetEnumerator(); } #endregion #region Implementation of ICollection int ICollection.Count { get { return _members.Count; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return this; } } void ICollection.CopyTo(Array array, int index) { throw new NotImplementedException(); } #endregion #region Implementation of ICollection<object> int ICollection<object>.Count { get { return _members.Count; } } bool ICollection<object>.IsReadOnly { get { return false; } } void ICollection<object>.Add(object item) { ((ICollection<object>)_members).Add(item); } void ICollection<object>.Clear() { ((ICollection<object>)_members).Clear(); } bool ICollection<object>.Contains(object item) { return ((ICollection<object>)_members).Contains(item); } void ICollection<object>.CopyTo(object[] array, int arrayIndex) { ((ICollection<object>)_members).CopyTo(array, arrayIndex); } bool ICollection<object>.Remove(object item) { return ((ICollection<object>)_members).Remove(item); } #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.ComponentModel; using System.Diagnostics; using System.IO; using System.Net; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; namespace System.Media { public class SoundPlayer : Component, ISerializable { private const int BlockSize = 1024; private const int DefaultLoadTimeout = 10000; // 10 secs private Uri _uri = null; private string _soundLocation = string.Empty; private int _loadTimeout = DefaultLoadTimeout; // used to lock all synchronous calls to the SoundPlayer object private readonly ManualResetEvent _semaphore = new ManualResetEvent(true); // the worker copyTask // we start the worker copyTask ONLY from entry points in the SoundPlayer API // we also set the tread to null only from the entry points in the SoundPlayer API private Task _copyTask = null; private CancellationTokenSource _copyTaskCancellation = null; // local buffer information private int _currentPos = 0; private Stream _stream = null; private Exception _lastLoadException = null; private bool _doesLoadAppearSynchronous = false; private byte[] _streamData = null; private AsyncOperation _asyncOperation = null; private readonly SendOrPostCallback _loadAsyncOperationCompleted; // event private static readonly object s_eventLoadCompleted = new object(); private static readonly object s_eventSoundLocationChanged = new object(); private static readonly object s_eventStreamChanged = new object(); public SoundPlayer() { _loadAsyncOperationCompleted = new SendOrPostCallback(LoadAsyncOperationCompleted); } public SoundPlayer(string soundLocation) : this() { SetupSoundLocation(soundLocation ?? string.Empty); } public SoundPlayer(Stream stream) : this() { _stream = stream; } protected SoundPlayer(SerializationInfo serializationInfo, StreamingContext context) { throw new PlatformNotSupportedException(); } public int LoadTimeout { get => _loadTimeout; set { if (value < 0) { throw new ArgumentOutOfRangeException("LoadTimeout", value, SR.SoundAPILoadTimeout); } _loadTimeout = value; } } public string SoundLocation { get => _soundLocation; set { if (value == null) { value = string.Empty; } if (_soundLocation.Equals(value)) { return; } SetupSoundLocation(value); OnSoundLocationChanged(EventArgs.Empty); } } public Stream Stream { get { // if the path is set, we should return null // Path and Stream are mutually exclusive if (_uri != null) { return null; } return _stream; } set { if (_stream == value) { return; } SetupStream(value); OnStreamChanged(EventArgs.Empty); } } public bool IsLoadCompleted { get; private set; } = false; public object Tag { get; set; } = null; public void LoadAsync() { // if we have a file there is nothing to load - we just pass the file to the PlaySound function // if we have a stream, then we start loading the stream async if (_uri != null && _uri.IsFile) { Debug.Assert(_stream == null, "we can't have a stream and a path at the same time"); IsLoadCompleted = true; FileInfo fi = new FileInfo(_uri.LocalPath); if (!fi.Exists) { throw new FileNotFoundException(SR.SoundAPIFileDoesNotExist, _soundLocation); } OnLoadCompleted(new AsyncCompletedEventArgs(null, false, null)); return; } // if we are actively loading, keep it running if (_copyTask != null && !_copyTask.IsCompleted) { return; } IsLoadCompleted = false; _streamData = null; _currentPos = 0; _asyncOperation = AsyncOperationManager.CreateOperation(null); LoadStream(false); } private void LoadAsyncOperationCompleted(object arg) { OnLoadCompleted((AsyncCompletedEventArgs)arg); } // called for loading a stream synchronously // called either when the user is setting the path/stream and we are loading // or when loading took more time than the time out private void CleanupStreamData() { _currentPos = 0; _streamData = null; IsLoadCompleted = false; _lastLoadException = null; _doesLoadAppearSynchronous = false; _copyTask = null; _semaphore.Set(); } public void Load() { // if we have a file there is nothing to load - we just pass the file to the PlaySound function // if we have a stream, then we start loading the stream sync if (_uri != null && _uri.IsFile) { Debug.Assert(_stream == null, "we can't have a stream and a path at the same time"); FileInfo fi = new FileInfo(_uri.LocalPath); if (!fi.Exists) { throw new FileNotFoundException(SR.SoundAPIFileDoesNotExist, _soundLocation); } IsLoadCompleted = true; OnLoadCompleted(new AsyncCompletedEventArgs(null, false, null)); return; } LoadSync(); } private void LoadAndPlay(int flags) { // When the user does not specify a sound location nor a stream, play Beep if (string.IsNullOrEmpty(_soundLocation) && _stream == null) { SystemSounds.Beep.Play(); return; } if (_uri != null && _uri.IsFile) { // Someone can call SoundPlayer::set_Location between the time // LoadAndPlay validates the sound file and the time it calls PlaySound. // The SoundPlayer will end up playing an un-validated sound file. // The solution is to store the uri.LocalPath on a local variable string localPath = _uri.LocalPath; // Play the path - don't use uri.AbsolutePath because that gives problems // when there are whitespaces in file names IsLoadCompleted = true; ValidateSoundFile(localPath); Interop.WinMM.PlaySound(localPath, IntPtr.Zero, Interop.WinMM.SND_NODEFAULT | flags); } else { LoadSync(); ValidateSoundData(_streamData); Interop.WinMM.PlaySound(_streamData, IntPtr.Zero, Interop.WinMM.SND_MEMORY | Interop.WinMM.SND_NODEFAULT | flags); } } private void CancelLoad() { _copyTaskCancellation?.Cancel(); _copyTaskCancellation = null; } private void LoadSync() { Debug.Assert((_uri == null || !_uri.IsFile), "we only load streams"); // first make sure that any possible download ended if (!_semaphore.WaitOne(LoadTimeout, false)) { CancelLoad(); CleanupStreamData(); throw new TimeoutException(SR.SoundAPILoadTimedOut); } // if we have data, then we are done if (_streamData != null) { return; } // setup the http stream if (_uri != null && !_uri.IsFile && _stream == null) { WebRequest webRequest = WebRequest.Create(_uri); webRequest.Timeout = LoadTimeout; WebResponse webResponse; webResponse = webRequest.GetResponse(); // now get the stream _stream = webResponse.GetResponseStream(); } if (_stream.CanSeek) { // if we can get data synchronously, then get it LoadStream(true); } else { // the data can't be loaded synchronously // load it async, then wait for it to finish _doesLoadAppearSynchronous = true; // to avoid OnFailed call. LoadStream(false); if (!_semaphore.WaitOne(LoadTimeout, false)) { CancelLoad(); CleanupStreamData(); throw new TimeoutException(SR.SoundAPILoadTimedOut); } _doesLoadAppearSynchronous = false; if (_lastLoadException != null) { throw _lastLoadException; } } // we don't need the worker copyThread anymore _copyTask = null; } private void LoadStream(bool loadSync) { if (loadSync && _stream.CanSeek) { int streamLen = (int)_stream.Length; _currentPos = 0; _streamData = new byte[streamLen]; _stream.Read(_streamData, 0, streamLen); IsLoadCompleted = true; OnLoadCompleted(new AsyncCompletedEventArgs(null, false, null)); } else { // lock any synchronous calls on the Sound object _semaphore.Reset(); // start loading var cts = new CancellationTokenSource(); _copyTaskCancellation = cts; _copyTask = CopyStreamAsync(cts.Token); } } public void Play() { LoadAndPlay(Interop.WinMM.SND_ASYNC); } public void PlaySync() { LoadAndPlay(Interop.WinMM.SND_SYNC); } public void PlayLooping() { LoadAndPlay(Interop.WinMM.SND_LOOP | Interop.WinMM.SND_ASYNC); } private static Uri ResolveUri(string partialUri) { Uri result = null; try { result = new Uri(partialUri); } catch (UriFormatException) { // eat URI parse exceptions } if (result == null) { // try relative to appbase try { result = new Uri(Path.GetFullPath(partialUri)); } catch (UriFormatException) { // eat URI parse exceptions } } return result; } private void SetupSoundLocation(string soundLocation) { // if we are loading a file, stop it right now if (_copyTask != null) { CancelLoad(); CleanupStreamData(); } _uri = ResolveUri(soundLocation); _soundLocation = soundLocation; _stream = null; if (_uri == null) { if (!string.IsNullOrEmpty(soundLocation)) { throw new UriFormatException(SR.SoundAPIBadSoundLocation); } } else { if (!_uri.IsFile) { // we are referencing a web resource ... // we treat it as a stream... _streamData = null; _currentPos = 0; IsLoadCompleted = false; } } } private void SetupStream(Stream stream) { if (_copyTask != null) { CancelLoad(); CleanupStreamData(); } _stream = stream; _soundLocation = string.Empty; _streamData = null; _currentPos = 0; IsLoadCompleted = false; if (stream != null) { _uri = null; } } public void Stop() { Interop.WinMM.PlaySound((byte[])null, IntPtr.Zero, Interop.WinMM.SND_PURGE); } public event AsyncCompletedEventHandler LoadCompleted { add { Events.AddHandler(s_eventLoadCompleted, value); } remove { Events.RemoveHandler(s_eventLoadCompleted, value); } } public event EventHandler SoundLocationChanged { add { Events.AddHandler(s_eventSoundLocationChanged, value); } remove { Events.RemoveHandler(s_eventSoundLocationChanged, value); } } public event EventHandler StreamChanged { add { Events.AddHandler(s_eventStreamChanged, value); } remove { Events.RemoveHandler(s_eventStreamChanged, value); } } protected virtual void OnLoadCompleted(AsyncCompletedEventArgs e) { ((AsyncCompletedEventHandler)Events[s_eventLoadCompleted])?.Invoke(this, e); } protected virtual void OnSoundLocationChanged(EventArgs e) { ((EventHandler)Events[s_eventSoundLocationChanged])?.Invoke(this, e); } protected virtual void OnStreamChanged(EventArgs e) { ((EventHandler)Events[s_eventStreamChanged])?.Invoke(this, e); } private async Task CopyStreamAsync(CancellationToken cancellationToken) { try { // setup the http stream if (_uri != null && !_uri.IsFile && _stream == null) { WebRequest webRequest = WebRequest.Create(_uri); using (cancellationToken.Register(r => ((WebRequest)r).Abort(), webRequest)) { WebResponse webResponse = await webRequest.GetResponseAsync().ConfigureAwait(false); _stream = webResponse.GetResponseStream(); } } _streamData = new byte[BlockSize]; int readBytes = await _stream.ReadAsync(_streamData, _currentPos, BlockSize, cancellationToken).ConfigureAwait(false); int totalBytes = readBytes; while (readBytes > 0) { _currentPos += readBytes; if (_streamData.Length < _currentPos + BlockSize) { byte[] newData = new byte[_streamData.Length * 2]; Array.Copy(_streamData, 0, newData, 0, _streamData.Length); _streamData = newData; } readBytes = await _stream.ReadAsync(_streamData, _currentPos, BlockSize, cancellationToken).ConfigureAwait(false); totalBytes += readBytes; } _lastLoadException = null; } catch (Exception exception) { _lastLoadException = exception; } IsLoadCompleted = true; _semaphore.Set(); if (!_doesLoadAppearSynchronous) { // Post notification back to the UI thread. AsyncCompletedEventArgs ea = _lastLoadException is OperationCanceledException ? new AsyncCompletedEventArgs(null, cancelled: true, null) : new AsyncCompletedEventArgs(_lastLoadException, cancelled: false, null); _asyncOperation.PostOperationCompleted(_loadAsyncOperationCompleted, ea); } } private unsafe void ValidateSoundFile(string fileName) { IntPtr hMIO = Interop.WinMM.mmioOpen(fileName, IntPtr.Zero, Interop.WinMM.MMIO_READ | Interop.WinMM.MMIO_ALLOCBUF); if (hMIO == IntPtr.Zero) { throw new FileNotFoundException(SR.SoundAPIFileDoesNotExist, _soundLocation); } try { Interop.WinMM.WAVEFORMATEX waveFormat = null; var ckRIFF = new Interop.WinMM.MMCKINFO() { fccType = mmioFOURCC('W', 'A', 'V', 'E') }; var ck = new Interop.WinMM.MMCKINFO(); if (Interop.WinMM.mmioDescend(hMIO, ckRIFF, null, Interop.WinMM.MMIO_FINDRIFF) != 0) { throw new InvalidOperationException(SR.Format(SR.SoundAPIInvalidWaveFile, _soundLocation)); } while (Interop.WinMM.mmioDescend(hMIO, ck, ckRIFF, 0) == 0) { if (ck.dwDataOffset + ck.cksize > ckRIFF.dwDataOffset + ckRIFF.cksize) { throw new InvalidOperationException(SR.SoundAPIInvalidWaveHeader); } if (ck.ckID == mmioFOURCC('f', 'm', 't', ' ')) { if (waveFormat == null) { int dw = ck.cksize; if (dw < Marshal.SizeOf(typeof(Interop.WinMM.WAVEFORMATEX))) { dw = Marshal.SizeOf(typeof(Interop.WinMM.WAVEFORMATEX)); } waveFormat = new Interop.WinMM.WAVEFORMATEX(); var data = new byte[dw]; if (Interop.WinMM.mmioRead(hMIO, data, dw) != dw) { throw new InvalidOperationException(SR.Format(SR.SoundAPIReadError, _soundLocation)); } fixed (byte* pdata = data) { Marshal.PtrToStructure((IntPtr)pdata, waveFormat); } } else { // multiple formats? } } Interop.WinMM.mmioAscend(hMIO, ck, 0); } if (waveFormat == null) { throw new InvalidOperationException(SR.SoundAPIInvalidWaveHeader); } if (waveFormat.wFormatTag != Interop.WinMM.WAVE_FORMAT_PCM && waveFormat.wFormatTag != Interop.WinMM.WAVE_FORMAT_ADPCM && waveFormat.wFormatTag != Interop.WinMM.WAVE_FORMAT_IEEE_FLOAT) { throw new InvalidOperationException(SR.SoundAPIFormatNotSupported); } } finally { if (hMIO != IntPtr.Zero) { Interop.WinMM.mmioClose(hMIO, 0); } } } private static void ValidateSoundData(byte[] data) { int position = 0; short wFormatTag = -1; bool fmtChunkFound = false; // the RIFF header should be at least 12 bytes long. if (data.Length < 12) { throw new InvalidOperationException(SR.SoundAPIInvalidWaveHeader); } // validate the RIFF header if (data[0] != 'R' || data[1] != 'I' || data[2] != 'F' || data[3] != 'F') { throw new InvalidOperationException(SR.SoundAPIInvalidWaveHeader); } if (data[8] != 'W' || data[9] != 'A' || data[10] != 'V' || data[11] != 'E') { throw new InvalidOperationException(SR.SoundAPIInvalidWaveHeader); } // we only care about "fmt " chunk position = 12; int len = data.Length; while (!fmtChunkFound && position < len - 8) { if (data[position] == (byte)'f' && data[position + 1] == (byte)'m' && data[position + 2] == (byte)'t' && data[position + 3] == (byte)' ') { // fmt chunk fmtChunkFound = true; int chunkSize = BytesToInt(data[position + 7], data[position + 6], data[position + 5], data[position + 4]); // get the cbSize from the WAVEFORMATEX int sizeOfWAVEFORMAT = 16; if (chunkSize != sizeOfWAVEFORMAT) { // we are dealing w/ WAVEFORMATEX // do extra validation int sizeOfWAVEFORMATEX = 18; // make sure the buffer is big enough to store a short if (len < position + 8 + sizeOfWAVEFORMATEX - 1) { throw new InvalidOperationException(SR.SoundAPIInvalidWaveHeader); } short cbSize = BytesToInt16(data[position + 8 + sizeOfWAVEFORMATEX - 1], data[position + 8 + sizeOfWAVEFORMATEX - 2]); if (cbSize + sizeOfWAVEFORMATEX != chunkSize) { throw new InvalidOperationException(SR.SoundAPIInvalidWaveHeader); } } // make sure the buffer passed in is big enough to store a short if (len < position + 9) { throw new InvalidOperationException(SR.SoundAPIInvalidWaveHeader); } wFormatTag = BytesToInt16(data[position + 9], data[position + 8]); position += chunkSize + 8; } else { position += 8 + BytesToInt(data[position + 7], data[position + 6], data[position + 5], data[position + 4]); } } if (!fmtChunkFound) { throw new InvalidOperationException(SR.SoundAPIInvalidWaveHeader); } if (wFormatTag != Interop.WinMM.WAVE_FORMAT_PCM && wFormatTag != Interop.WinMM.WAVE_FORMAT_ADPCM && wFormatTag != Interop.WinMM.WAVE_FORMAT_IEEE_FLOAT) { throw new InvalidOperationException(SR.SoundAPIFormatNotSupported); } } private static short BytesToInt16(byte ch0, byte ch1) { int res; res = ch1; res |= ch0 << 8; return (short)res; } private static int BytesToInt(byte ch0, byte ch1, byte ch2, byte ch3) { return mmioFOURCC((char)ch3, (char)ch2, (char)ch1, (char)ch0); } private static int mmioFOURCC(char ch0, char ch1, char ch2, char ch3) { int result = 0; result |= ch0; result |= ch1 << 8; result |= ch2 << 16; result |= ch3 << 24; return result; } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } } }
// // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (the "License"). // You may not use this file except in compliance with the // License. A copy of the License is located at // // http://aws.amazon.com/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, express or implied. See the License // for the specific language governing permissions and // limitations under the License. // using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using Amazon.DynamoDBv2.DataModel; using Amazon.DynamoDBv2.DocumentModel; using Amazon.Util.Internal; #if (WIN_RT || WINDOWS_PHONE) using Amazon.MissingTypes; using Amazon.Runtime.Internal.Util; #endif namespace Amazon.DynamoDBv2 { /// <summary> /// Available conversion schemas. /// </summary> internal enum ConversionSchema { /// <summary> /// Default schema before 2014 L, M, BOOL, NULL support /// /// The following .NET types are converted into the following DynamoDB types: /// Number types (byte, int, float, decimal, etc.) are converted to N /// String and char are converted to S /// Bool is converted to N (0=false, 1=true) /// DateTime and Guid are converto to S /// MemoryStream and byte[] are converted to B /// List, HashSet, and array of numerics types are converted to NS /// List, HashSet, and array of string-based types are converted to SS /// List, HashSet, and array of binary-based types are converted to BS /// Dictionary{string,object} are converted to M /// </summary> V1 = 0, /// <summary> /// Schema fully supporting 2014 L, M, BOOL, NULL additions /// /// The following .NET types are converted into the following DynamoDB types: /// Number types (byte, int, float, decimal, etc.) are converted to N /// String and char are converted to S /// Bool is converted to BOOL /// DateTime and Guid are converto to S /// MemoryStream and byte[] are converted to B /// HashSet of numerics types are converted to NS /// HashSet of string-based types are converted to SS /// HashSet of binary-based types are converted to BS /// List and array of numerics, string-based types, and binary-based types /// are converted to L type. /// Dictionary{string,object} are converted to M /// </summary> V2 = 1, } /// <summary> /// A collection of converters capable of converting between /// .NET and DynamoDB objects. /// </summary> public class DynamoDBEntryConversion { #region Static members /// <summary> /// Default conversion before 2014 L, M, BOOL, NULL support. /// /// The following .NET types are converted into the following DynamoDB types: /// Number types (byte, int, float, decimal, etc.) are converted to N /// String and char are converted to S /// Bool is converted to N (0=false, 1=true) /// DateTime and Guid are converto to S /// MemoryStream and byte[] are converted to B /// List, HashSet, and array of numerics types are converted to NS /// List, HashSet, and array of string-based types are converted to SS /// List, HashSet, and array of binary-based types are converted to BS /// Dictionary{string,object} are converted to M /// </summary> public static DynamoDBEntryConversion V1 { get; private set; } /// <summary> /// Schema fully supporting 2014 L, M, BOOL, NULL additions. /// /// The following .NET types are converted into the following DynamoDB types: /// Number types (byte, int, float, decimal, etc.) are converted to N /// String and char are converted to S /// Bool is converted to BOOL /// DateTime and Guid are converto to S /// MemoryStream and byte[] are converted to B /// HashSet of numerics types are converted to NS /// HashSet of string-based types are converted to SS /// HashSet of binary-based types are converted to BS /// List and array of numerics, string-based types, and binary-based types /// are converted to L type. /// Dictionary{string,object} are converted to M /// </summary> public static DynamoDBEntryConversion V2 { get; private set; } /// <summary> /// Returns a DynamoDBEntryConversion corresponding to the ConversionSchema. /// The returned conversion is immutable. The conversion must be cloned /// before it can be modified. /// </summary> /// <param name="schema">Conversion to return.</param> /// <returns>DynamoDBEntryConversion corresponding to the ConversionSchema.</returns> internal static DynamoDBEntryConversion GetConversion(ConversionSchema schema) { switch (schema) { case ConversionSchema.V1: return DynamoDBEntryConversion.V1; case ConversionSchema.V2: return DynamoDBEntryConversion.V2; default: throw new ArgumentOutOfRangeException("schema"); } } /// <summary> /// Conversion corresponding to AWSConfigs.DynamoDBConfig.ConversionSchema /// </summary> internal static DynamoDBEntryConversion CurrentConversion { get { return GetConversion(AWSConfigsDynamoDB.ConversionSchema); } } #endregion #region Constructors static DynamoDBEntryConversion() { V1 = new DynamoDBEntryConversion(ConversionSchema.V1, isImmutable: true); V2 = new DynamoDBEntryConversion(ConversionSchema.V2, isImmutable: true); } private DynamoDBEntryConversion(ConversionSchema schema, bool isImmutable) { OriginalConversion = schema; switch (schema) { case ConversionSchema.V1: SetV1Converters(); break; case ConversionSchema.V2: SetV2Converters(); break; default: throw new ArgumentOutOfRangeException("schema"); } IsImmutable = isImmutable; } /// <summary> /// Creates an empty, mutable conversion. /// </summary> internal DynamoDBEntryConversion() { OriginalConversion = ConversionSchema.V1; } #endregion #region Public methods public DynamoDBEntry ConvertToEntry<TInput>(TInput value) { DynamoDBEntry entry; if (TryConvertToEntry<TInput>(value, out entry)) return entry; throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Unable to convert [{0}] of type {1} to DynamoDBEntry", value, value.GetType().FullName)); } public bool TryConvertToEntry<TInput>(TInput value, out DynamoDBEntry entry) { var inputType = typeof(TInput); return TryConvertToEntry(inputType, value, out entry); } public TOutput ConvertFromEntry<TOutput>(DynamoDBEntry entry) { TOutput output; if (TryConvertFromEntry<TOutput>(entry, out output)) return output; throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Unable to convert [{0}] of type {1} to {2}", entry, entry.GetType().FullName, typeof(TOutput).FullName)); } public bool TryConvertFromEntry<TOutput>(DynamoDBEntry entry, out TOutput output) { output = default(TOutput); var outputType = typeof(TOutput); object converted; if (TryConvertFromEntry(outputType, entry, out converted)) { if (converted != null) output = (TOutput)converted; return true; } return false; } #endregion #region Internal members internal DynamoDBEntryConversion Clone() { return new DynamoDBEntryConversion(this.OriginalConversion, isImmutable: false); } internal bool HasConverter(Type type) { return ConverterCache.ContainsKey(type); } internal void AddConverter(Converter converter) { if (IsImmutable) throw new InvalidOperationException("Adding converters to immutable conversion is not supported. The conversion must be cloned first."); converter.Conversion = this; var types = converter.GetTargetTypes(); foreach (var type in types) { ConverterCache[type] = converter; } } internal bool TryConvertToEntry(Type inputType, object value, out DynamoDBEntry entry) { if (inputType == null) throw new ArgumentNullException("inputType"); if (value == null) throw new ArgumentNullException("value"); var converter = GetConverter(inputType); return converter.TryToEntry(value, out entry); } internal bool TryConvertFromEntry(Type outputType, DynamoDBEntry entry, out object value) { if (outputType == null) throw new ArgumentNullException("outputType"); if (entry == null) throw new ArgumentNullException("entry"); var converter = GetConverter(outputType); return converter.TryFromEntry(entry, outputType, out value); } internal DynamoDBEntry ConvertToEntry(Type inputType, object value) { if (inputType == null) throw new ArgumentNullException("inputType"); if (value == null) throw new ArgumentNullException("value"); var converter = GetConverter(inputType); DynamoDBEntry output = converter.ToEntry(value); return output; } internal object ConvertFromEntry(Type outputType, DynamoDBEntry entry) { if (outputType == null) throw new ArgumentNullException("outputType"); if (entry == null) throw new ArgumentNullException("entry"); var converter = GetConverter(outputType); object output = converter.FromEntry(entry, outputType); return output; } internal IEnumerable<DynamoDBEntry> ConvertToEntries(Type elementType, IEnumerable values) { if (values == null) throw new ArgumentNullException("values"); foreach (var value in values) yield return ConvertToEntry(elementType, value); } internal IEnumerable<DynamoDBEntry> ConvertToEntries<T>(IEnumerable<T> values) { if (values == null) throw new ArgumentNullException("values"); var elementType = typeof(T); foreach (var value in values) yield return ConvertToEntry(elementType, value); //foreach (var value in values) // yield return ConvertToEntry(value); } internal IEnumerable<object> ConvertFromEntries(Type elementType, IEnumerable<DynamoDBEntry> entries) { if (entries == null) throw new ArgumentNullException("entries"); foreach (var entry in entries) yield return ConvertFromEntry(elementType, entry); } internal PrimitiveList ItemsToPrimitiveList(IEnumerable items) { var inputType = items.GetType(); var elementType = Utils.GetPrimitiveElementType(inputType); var primitives = ToPrimitives(items, elementType); var pl = new PrimitiveList(primitives); return pl; } #endregion #region Private members private Dictionary<Type, Converter> ConverterCache = new Dictionary<Type, Converter>(); private ConversionSchema OriginalConversion; private bool IsImmutable; private void AddConverters(string suffix) { var typedConverterTypeInfo = TypeFactory.GetTypeInfo(typeof(Converter)); var assembly = TypeFactory.GetTypeInfo(typeof(DynamoDBEntryConversion)).Assembly; var types = assembly.GetTypes(); foreach (var type in types) { //if (type.Namespace != typedConverterType.Namespace) // continue; var typeInfo = TypeFactory.GetTypeInfo(type); if (typeInfo.IsAbstract) continue; if (!type.Name.EndsWith(suffix, StringComparison.Ordinal)) continue; if (!typedConverterTypeInfo.IsAssignableFrom(typeInfo)) continue; AddConverter(type); } } private void AddConverter(Type type) { var converter = Activator.CreateInstance(type) as Converter; AddConverter(converter); } private void SetV1Converters() { AddConverters("ConverterV1"); } private void SetV2Converters() { AddConverters("ConverterV2"); } private Converter GetConverter(Type type) { Converter converter; if (!TryGetConverter(type, out converter)) throw new InvalidOperationException("No converter configured for type " + type.FullName); return converter; } private bool TryGetConverter(Type type, out Converter converter) { return ConverterCache.TryGetValue(type, out converter); } // Converts items to Primitives. // elementType must be a type that is a primitive (Utils.IsPrimitive(elementType) must return true) private IEnumerable<Primitive> ToPrimitives(IEnumerable items, Type elementType) { Utils.ValidatePrimitiveType(elementType); foreach (var item in items) { // Convert to DynamoDBEntry // Item may be DynamoDBEntry already, in which case don't convert var entry = item as DynamoDBEntry; if (entry == null) entry = ConvertToEntry(elementType, item); // If entry is not Primitive, throw an exception var p = entry.AsPrimitive(); if (p == null) throw new InvalidCastException(string.Format(CultureInfo.InvariantCulture, "Unable to convert [{0}] of type {1} to Primitive", item, elementType.FullName)); yield return p; } } #endregion } internal abstract class Converter { /// <summary> /// Returns all types for which it can be used. /// </summary> /// <returns></returns> public abstract IEnumerable<Type> GetTargetTypes(); /// <summary> /// Conversion that this converter is part of. /// This field is set by DynamoDBEntryConversion when the Converter /// is added to that DynamoDBEntryConversion. /// /// This conversion should be used if the Converter needs to /// make sub-conversions (for instance, a collection converter). /// </summary> public DynamoDBEntryConversion Conversion { get; set; } public DynamoDBEntry ToEntry(object value) { if (value == null) throw new ArgumentNullException("value"); DynamoDBEntry entry; if (TryToEntry(value, out entry)) return entry; throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Unable to convert [{0}] of type {1} to DynamoDBEntry using the converter {2}", value, value.GetType().FullName, this.GetType().FullName)); } public bool TryToEntry(object value, out DynamoDBEntry entry) { if (value == null) throw new ArgumentNullException("value"); Primitive p; if (TryTo(value, out p)) { entry = p; return true; } PrimitiveList pl; if (TryTo(value, out pl)) { entry = pl; return true; } DynamoDBBool b; if (TryTo(value, out b)) { entry = b; return true; } DynamoDBList l; if (TryTo(value, out l)) { entry = l; return true; } Document d; if (TryTo(value, out d)) { entry = d; return true; } entry = null; return false; } public object FromEntry(DynamoDBEntry entry, Type targetType) { if (entry == null) throw new ArgumentNullException("entry"); if (targetType == null) throw new ArgumentNullException("targetType"); object value; if (TryFromEntry(entry, targetType, out value)) return value; throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Unable to convert [{0}] of type {1} to {2}", entry, entry.GetType().FullName, targetType.FullName)); } public bool TryFromEntry(DynamoDBEntry entry, Type targetType, out object value) { var p = entry as Primitive; if (p != null) { // Special case for handling null values (directive to DELETE) in Document if (p.Value == null && p.Type == DynamoDBEntryType.String) { value = null; return true; } if (TryFrom(p, targetType, out value)) return true; } var pl = entry as PrimitiveList; if (pl != null && TryFrom(pl, targetType, out value)) return true; var b = entry as DynamoDBBool; if (b != null && TryFrom(b, targetType, out value)) return true; var l = entry as DynamoDBList; if (l != null && TryFrom(l, targetType, out value)) return true; var d = entry as Document; if (d != null && TryFrom(d, targetType, out value)) return true; //var n = entry as DynamoDBNull; //if (n != null) // return null; value = null; return false; } public virtual bool TryTo(object value, out DynamoDBBool b) { b = null; return false; } public virtual bool TryTo(object value, out Primitive p) { p = null; return false; } public virtual bool TryTo(object value, out PrimitiveList pl) { pl = null; return false; } public virtual bool TryTo(object value, out DynamoDBList l) { l = null; return false; } public virtual bool TryTo(object value, out Document d) { d = null; return false; } public virtual bool TryFrom(DynamoDBBool b, Type targetType, out object result) { result = null; return false; } public virtual bool TryFrom(Primitive p, Type targetType, out object result) { result = null; return false; } public virtual bool TryFrom(PrimitiveList pl, Type targetType, out object result) { result = null; return false; } public virtual bool TryFrom(DynamoDBList l, Type targetType, out object result) { result = null; return false; } public virtual bool TryFrom(Document d, Type targetType, out object result) { result = null; return false; } } internal abstract class Converter<T> : Converter { public override IEnumerable<Type> GetTargetTypes() { var type = typeof(T); yield return type; var typeInfo = TypeFactory.GetTypeInfo(type); if (typeInfo.IsValueType) { //yield return typeof(Nullable<T>); var nullableType = typeof(Nullable<>).MakeGenericType(type); yield return nullableType; } } public override bool TryTo(object value, out DynamoDBBool b) { return TryTo((T)value, out b); } public override bool TryTo(object value, out Primitive p) { return TryTo((T)value, out p); } public override bool TryTo(object value, out PrimitiveList pl) { return TryTo((T)value, out pl); } public override bool TryTo(object value, out DynamoDBList l) { return TryTo((T)value, out l); } public override bool TryTo(object value, out Document d) { return TryTo((T)value, out d); } protected virtual bool TryTo(T value, out DynamoDBBool b) { b = null; return false; } protected virtual bool TryTo(T value, out Primitive p) { p = null; return false; } protected virtual bool TryTo(T value, out PrimitiveList pl) { pl = null; return false; } protected virtual bool TryTo(T value, out DynamoDBList l) { l = null; return false; } protected virtual bool TryTo(T value, out Document d) { d = null; return false; } public override bool TryFrom(DynamoDBBool b, Type targetType, out object result) { T t; var output = TryFrom(b, targetType, out t); result = t; return output; } public override bool TryFrom(Primitive p, Type targetType, out object result) { T t; var output = TryFrom(p, targetType, out t); result = t; return output; } public override bool TryFrom(PrimitiveList pl, Type targetType, out object result) { T t; var output = TryFrom(pl, targetType, out t); result = t; return output; } public override bool TryFrom(DynamoDBList l, Type targetType, out object result) { T t; var output = TryFrom(l, targetType, out t); result = t; return output; } public override bool TryFrom(Document d, Type targetType, out object result) { T t; var output = TryFrom(d, targetType, out t); result = t; return output; } protected virtual bool TryFrom(DynamoDBBool b, Type targetType, out T result) { result = default(T); return false; } protected virtual bool TryFrom(Primitive p, Type targetType, out T result) { result = default(T); return false; } protected virtual bool TryFrom(PrimitiveList pl, Type targetType, out T result) { result = default(T); return false; } protected virtual bool TryFrom(DynamoDBList l, Type targetType, out T result) { result = default(T); return false; } protected virtual bool TryFrom(Document d, Type targetType, out T result) { result = default(T); return false; } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Host; using System.IO; using Microsoft.PowerShell.Commands.Internal.Format; namespace Microsoft.PowerShell.Commands { internal static class InputFileOpenModeConversion { internal static FileMode Convert(OpenMode openMode) { return SessionStateUtilities.GetFileModeFromOpenMode(openMode); } } /// <summary> /// implementation for the out-file command /// </summary> [Cmdlet("Out", "File", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113363")] public class OutFileCommand : FrontEndCommandBase { /// <summary> /// set inner command /// </summary> public OutFileCommand() { this.implementation = new OutputManagerInner(); } #region Command Line Parameters /// <summary> /// mandatory file name to write to /// </summary> [Parameter(Mandatory = true, Position = 0, ParameterSetName = "ByPath")] public string FilePath { get { return _fileName; } set { _fileName = value; } } private string _fileName; /// <summary> /// mandatory file name to write to /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")] [Alias("PSPath")] public string LiteralPath { get { return _fileName; } set { _fileName = value; _isLiteralPath = true; } } private bool _isLiteralPath = false; /// <summary> /// Encoding optional flag /// </summary> /// [Parameter(Position = 1)] [ValidateNotNullOrEmpty] [ValidateSetAttribute(new string[] { EncodingConversion.Unknown, EncodingConversion.String, EncodingConversion.Unicode, EncodingConversion.BigEndianUnicode, EncodingConversion.Utf8, EncodingConversion.Utf7, EncodingConversion.Utf32, EncodingConversion.Ascii, EncodingConversion.Default, EncodingConversion.OEM })] public string Encoding { get { return _encoding; } set { _encoding = value; } } private string _encoding; /// <summary> /// Property that sets append parameter. /// </summary> [Parameter()] public SwitchParameter Append { get { return _append; } set { _append = value; } } private bool _append; /// <summary> /// Property that sets force parameter. /// </summary> [Parameter()] public SwitchParameter Force { get { return _force; } set { _force = value; } } private bool _force; /// <summary> /// Property that prevents file overwrite. /// </summary> [Parameter()] [Alias("NoOverwrite")] public SwitchParameter NoClobber { get { return _noclobber; } set { _noclobber = value; } } private bool _noclobber; /// <summary> /// optional, number of columns to use when writing to device /// </summary> [ValidateRangeAttribute(2, int.MaxValue)] [Parameter] public int Width { get { return (_width != null) ? _width.Value : 0; } set { _width = value; } } private Nullable<int> _width = null; /// <summary> /// False to add a newline to the end of the output string, true if not. /// </summary> [Parameter] public SwitchParameter NoNewline { get { return _suppressNewline; } set { _suppressNewline = value; } } private bool _suppressNewline = false; #endregion /// <summary> /// read command line parameters /// </summary> protected override void BeginProcessing() { // set up the Scree Host interface OutputManagerInner outInner = (OutputManagerInner)this.implementation; // NOTICE: if any exception is thrown from here to the end of the method, the // cleanup code will be called in IDisposable.Dispose() outInner.LineOutput = InstantiateLineOutputInterface(); if (null == _sw) { return; } // finally call the base class for general hookup base.BeginProcessing(); } /// <summary> /// one time initialization: acquire a screen host interface /// by creating one on top of a file /// NOTICE: we assume that at this time the file name is /// available in the CRO. JonN recommends: file name has to be /// a MANDATORY parameter on the command line /// </summary> private LineOutput InstantiateLineOutputInterface() { string action = StringUtil.Format(FormatAndOut_out_xxx.OutFile_Action); if (ShouldProcess(FilePath, action)) { PathUtils.MasterStreamOpen( this, FilePath, _encoding, false, // defaultEncoding Append, Force, NoClobber, out _fs, out _sw, out _readOnlyFileInfo, _isLiteralPath ); } else return null; // compute the # of columns available int computedWidth = 120; if (_width != null) { // use the value from the command line computedWidth = _width.Value; } else { // use the value we get from the console try { // NOTE: we subtract 1 because we want to properly handle // the following scenario: // MSH>get-foo|out-file foo.txt // MSH>get-content foo.txt // in this case, if the computed width is (say) 80, get-content // would cause a wrapping of the 80 column long raw strings. // Hence we set the width to 79. computedWidth = this.Host.UI.RawUI.BufferSize.Width - 1; } catch (HostException) { // non interactive host } } // use the stream writer to create and initialize the Line Output writer TextWriterLineOutput twlo = new TextWriterLineOutput(_sw, computedWidth, _suppressNewline); // finally have the ILineOutput interface extracted return (LineOutput)twlo; } /// <summary> /// execution entry point /// </summary> protected override void ProcessRecord() { _processRecordExecuted = true; if (null == _sw) { return; } // NOTICE: if any exception is thrown, the // cleanup code will be called in IDisposable.Dispose() base.ProcessRecord(); _sw.Flush(); } /// <summary> /// execution entry point /// </summary> protected override void EndProcessing() { // When the Out-File is used in a redirection pipelineProcessor, // its ProcessRecord method may not be called when nothing is written to the // output pipe, for example: // Write-Error error > test.txt // In this case, the EndProcess method should return immediately as if it's // never been called. The cleanup work will be done in IDisposable.Dispose() if (!_processRecordExecuted) { return; } if (null == _sw) { return; } // NOTICE: if any exception is thrown, the // cleanup code will be called in IDisposable.Dispose() base.EndProcessing(); _sw.Flush(); CleanUp(); } /// <summary> /// /// </summary> protected override void InternalDispose() { base.InternalDispose(); CleanUp(); } private void CleanUp() { if (_fs != null) { _fs.Dispose(); _fs = null; } // reset the read-only attribute if (null != _readOnlyFileInfo) { _readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; _readOnlyFileInfo = null; } } /// <summary> /// handle to file stream /// </summary> private FileStream _fs; /// <summary> /// stream writer used to write to file /// </summary> private StreamWriter _sw = null; /// <summary> /// indicate whether the ProcessRecord method was executed. /// When the Out-File is used in a redirection pipelineProcessor, /// its ProcessRecord method may not be called when nothing is written to the /// output pipe, for example: /// Write-Error error > test.txt /// In this case, the EndProcess method should return immediately as if it's /// never been called. /// </summary> private bool _processRecordExecuted = false; /// <summary> /// FileInfo of file to clear read-only flag when operation is complete /// </summary> private FileInfo _readOnlyFileInfo = null; } }
// // XmlDsigXsltTransformTest.cs - Test Cases for XmlDsigXsltTransform // // Author: // Sebastien Pouliot <sebastien@ximian.com> // Atsushi Enomoto <atsushi@ximian.com> // // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com) // (C) 2004 Novell (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.Collections; using System.IO; using System.Text; using System.Xml; using Xunit; namespace System.Security.Cryptography.Xml.Tests { // Note: GetInnerXml is protected in XmlDsigXsltTransform making it // difficult to test properly. This class "open it up" :-) public class UnprotectedXmlDsigXsltTransform : XmlDsigXsltTransform { public UnprotectedXmlDsigXsltTransform() { } public UnprotectedXmlDsigXsltTransform(bool includeComments) : base(includeComments) { } public XmlNodeList UnprotectedGetInnerXml() { return base.GetInnerXml(); } } public class XmlDsigXsltTransformTest { protected UnprotectedXmlDsigXsltTransform transform; public XmlDsigXsltTransformTest() { transform = new UnprotectedXmlDsigXsltTransform(); } [Fact] // ctor () public void Constructor1() { CheckProperties(transform); } [Fact] // ctor (Boolean) public void Constructor2() { transform = new UnprotectedXmlDsigXsltTransform(true); CheckProperties(transform); transform = new UnprotectedXmlDsigXsltTransform(false); CheckProperties(transform); } void CheckProperties(XmlDsigXsltTransform transform) { Assert.Equal("http://www.w3.org/TR/1999/REC-xslt-19991116", transform.Algorithm); Type[] input = transform.InputTypes; Assert.True((input.Length == 3), "Input #"); // check presence of every supported input types bool istream = false; bool ixmldoc = false; bool ixmlnl = false; foreach (Type t in input) { if (t.ToString() == "System.IO.Stream") istream = true; if (t.ToString() == "System.Xml.XmlDocument") ixmldoc = true; if (t.ToString() == "System.Xml.XmlNodeList") ixmlnl = true; } Assert.True(istream, "Input Stream"); Assert.True(ixmldoc, "Input XmlDocument"); Assert.True(ixmlnl, "Input XmlNodeList"); Type[] output = transform.OutputTypes; Assert.True((output.Length == 1), "Output #"); // check presence of every supported output types bool ostream = false; foreach (Type t in output) { if (t.ToString() == "System.IO.Stream") ostream = true; } Assert.True(ostream, "Output Stream"); } [Fact] public void GetInnerXml() { XmlNodeList xnl = transform.UnprotectedGetInnerXml(); Assert.Null(xnl); } private string Stream2Array(Stream s) { StringBuilder sb = new StringBuilder(); int b = s.ReadByte(); while (b != -1) { sb.Append(b.ToString("X2")); b = s.ReadByte(); } return sb.ToString(); } [Fact] public void EmptyXslt() { string test = "<Test>XmlDsigXsltTransform</Test>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(test); transform.LoadInput(doc.ChildNodes); if (PlatformDetection.IsXmlDsigXsltTransformSupported) { Assert.Throws<ArgumentNullException>(() => transform.GetOutput()); } } [Fact] // Note that this is _valid_ as an "embedded stylesheet". // (see XSLT spec 2.7) public void EmbeddedStylesheet() { string test = "<Test xsl:version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>XmlDsigXsltTransform</Test>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(test); transform.LoadInnerXml(doc.ChildNodes); transform.LoadInput(doc); if (PlatformDetection.IsXmlDsigXsltTransformSupported) { Stream s = (Stream)transform.GetOutput(); } } [Fact] public void InvalidXslt() { bool result = false; try { string test = "<xsl:element name='foo' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>XmlDsigXsltTransform</xsl:element>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(test); transform.LoadInnerXml(doc.ChildNodes); Stream s = (Stream)transform.GetOutput(); } catch (Exception e) { // we must deal with an internal exception result = (e.GetType().ToString().EndsWith("XsltLoadException")); result = true; } finally { Assert.True(result, "Exception not thrown"); } } [Fact] public void OnlyInner() { string test = "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns=\"http://www.w3.org/TR/xhtml1/strict\" version=\"1.0\">"; test += "<xsl:output encoding=\"UTF-8\" indent=\"no\" method=\"xml\" />"; test += "<xsl:template match=\"/\"><html><head><title>Notaries</title>"; test += "</head><body><table><xsl:for-each select=\"Notaries/Notary\">"; test += "<tr><th><xsl:value-of select=\"@name\" /></th></tr></xsl:for-each>"; test += "</table></body></html></xsl:template></xsl:stylesheet>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(test); transform.LoadInnerXml(doc.ChildNodes); if (PlatformDetection.IsXmlDsigXsltTransformSupported) { Assert.Throws<ArgumentNullException>(() => transform.GetOutput()); } } private XmlDocument GetXslDoc() { string test = "<Transform Algorithm=\"http://www.w3.org/TR/1999/REC-xslt-19991116\" xmlns='http://www.w3.org/2000/09/xmldsig#'>"; test += "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns=\"http://www.w3.org/TR/xhtml1/strict\" version=\"1.0\">"; test += "<xsl:output encoding=\"UTF-8\" indent=\"no\" method=\"xml\" />"; test += "<xsl:template match=\"/\"><html><head><title>Notaries</title>"; test += "</head><body><table><xsl:for-each select=\"Notaries/Notary\">"; test += "<tr><th><xsl:value-of select=\"@name\" /></th></tr></xsl:for-each>"; test += "</table></body></html></xsl:template></xsl:stylesheet></Transform>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(test); return doc; } [Fact] public void LoadInputAsXmlDocument() { XmlDocument doc = GetXslDoc(); transform.LoadInnerXml(doc.DocumentElement.ChildNodes); transform.LoadInput(doc); if (PlatformDetection.IsXmlDsigXsltTransformSupported) { Stream s = (Stream)transform.GetOutput(); string output = Stream2Array(s); } } [Fact] public void LoadInputAsXmlNodeList() { XmlDocument doc = GetXslDoc(); transform.LoadInnerXml(doc.DocumentElement.ChildNodes); transform.LoadInput(doc.ChildNodes); if (PlatformDetection.IsXmlDsigXsltTransformSupported) { Stream s = (Stream)transform.GetOutput(); string output = Stream2Array(s); } } [Fact] public void LoadInputAsStream() { XmlDocument doc = GetXslDoc(); transform.LoadInnerXml(doc.DocumentElement.ChildNodes); MemoryStream ms = new MemoryStream(); doc.Save(ms); ms.Position = 0; transform.LoadInput(ms); if (PlatformDetection.IsXmlDsigXsltTransformSupported) { Stream s = (Stream)transform.GetOutput(); string output = Stream2Array(s); } } protected void AreEqual(string msg, XmlNodeList expected, XmlNodeList actual) { Assert.Equal(expected, actual); } [Fact] public void LoadInnerXml() { XmlDocument doc = GetXslDoc(); transform.LoadInnerXml(doc.DocumentElement.ChildNodes); XmlNodeList xnl = transform.UnprotectedGetInnerXml(); AssertNodeListEqual(doc.DocumentElement.ChildNodes, xnl, "LoadInnerXml"); } void AssertNodeListEqual(XmlNodeList nl1, XmlNodeList nl2, string label) { Assert.Equal(nl1.Count, nl2.Count); IEnumerator e1, e2; int i; for (i = 0, e1 = nl1.GetEnumerator(), e2 = nl2.GetEnumerator(); e1.MoveNext(); i++) { Assert.True(e2.MoveNext(), label + " : nl2.MoveNext"); Assert.Equal(e1.Current, e2.Current); } Assert.False(e2.MoveNext(), label + " : nl2 has extras"); } [Fact] public void Load2() { XmlDocument doc = GetXslDoc(); transform.LoadInnerXml(doc.DocumentElement.ChildNodes); transform.LoadInput(doc); if (PlatformDetection.IsXmlDsigXsltTransformSupported) { Stream s = (Stream)transform.GetOutput(); string output = Stream2Array(s); } } [Fact] public void UnsupportedInput() { byte[] bad = { 0xBA, 0xD }; // LAMESPEC: input MUST be one of InputType - but no exception is thrown (not documented) transform.LoadInput(bad); } [Fact] public void UnsupportedOutput() { XmlDocument doc = new XmlDocument(); AssertExtensions.Throws<ArgumentException>("type", () => transform.GetOutput(doc.GetType())); } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; /// <summary> /// An <see cref="IHttpProvider"/> implementation using standard .NET libraries. /// </summary> public class HttpProvider : IHttpProvider { private const int maxRedirects = 5; internal bool disposeHandler; internal HttpClient httpClient; internal HttpMessageHandler httpMessageHandler; /// <summary> /// Constructs a new <see cref="HttpProvider"/>. /// </summary> /// <param name="serializer">A serializer for serializing and deserializing JSON objects.</param> public HttpProvider(ISerializer serializer = null) : this((HttpMessageHandler)null, true, serializer) { } /// <summary> /// Constructs a new <see cref="HttpProvider"/>. /// </summary> /// <param name="httpClientHandler">An HTTP client handler to pass to the <see cref="HttpClient"/> for sending requests.</param> /// <param name="disposeHandler">Whether or not to dispose the client handler on Dispose().</param> /// <param name="serializer">A serializer for serializing and deserializing JSON objects.</param> /// <remarks> /// By default, HttpProvider disables automatic redirects and handles redirects to preserve authentication headers. If providing /// an <see cref="HttpClientHandler"/> to the constructor and enabling automatic redirects this could cause issues with authentication /// over the redirect. /// </remarks> public HttpProvider(HttpClientHandler httpClientHandler, bool disposeHandler, ISerializer serializer = null) : this((HttpMessageHandler)httpClientHandler, disposeHandler, serializer) { } /// <summary> /// Constructs a new <see cref="HttpProvider"/>. /// </summary> /// <param name="httpMessageHandler">An HTTP message handler to pass to the <see cref="HttpClient"/> for sending requests.</param> /// <param name="disposeHandler">Whether or not to dispose the client handler on Dispose().</param> /// <param name="serializer">A serializer for serializing and deserializing JSON objects.</param> internal HttpProvider(HttpMessageHandler httpMessageHandler, bool disposeHandler, ISerializer serializer) { this.disposeHandler = disposeHandler; this.httpMessageHandler = httpMessageHandler ?? new HttpClientHandler { AllowAutoRedirect = false }; this.httpClient = new HttpClient(this.httpMessageHandler, this.disposeHandler); this.CacheControlHeader = new CacheControlHeaderValue { NoCache = true, NoStore = true }; this.Serializer = serializer ?? new Serializer(); } /// <summary> /// Gets or sets the cache control header for requests; /// </summary> public CacheControlHeaderValue CacheControlHeader { get { return this.httpClient.DefaultRequestHeaders.CacheControl; } set { this.httpClient.DefaultRequestHeaders.CacheControl = value; } } /// <summary> /// Gets or sets the overall request timeout. /// </summary> public TimeSpan OverallTimeout { get { return this.httpClient.Timeout; } set { try { this.httpClient.Timeout = value; } catch (InvalidOperationException exception) { throw new ServiceException( new Error { Code = ErrorConstants.Codes.NotAllowed, Message = ErrorConstants.Messages.OverallTimeoutCannotBeSet, }, exception); } } } /// <summary> /// Gets a serializer for serializing and deserializing JSON objects. /// </summary> public ISerializer Serializer { get; private set; } /// <summary> /// Disposes the HttpClient and HttpClientHandler instances. /// </summary> public void Dispose() { if (this.httpClient != null) { this.httpClient.Dispose(); } } /// <summary> /// Sends the request. /// </summary> /// <param name="request">The <see cref="HttpRequestMessage"/> to send.</param> /// <returns>The <see cref="HttpResponseMessage"/>.</returns> public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request) { return this.SendAsync(request, HttpCompletionOption.ResponseContentRead, CancellationToken.None); } /// <summary> /// Sends the request. /// </summary> /// <param name="request">The <see cref="HttpRequestMessage"/> to send.</param> /// <param name="completionOption">The <see cref="HttpCompletionOption"/> to pass to the <see cref="IHttpProvider"/> on send.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="HttpResponseMessage"/>.</returns> public async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken) { var response = await this.SendRequestAsync(request, completionOption, cancellationToken); if (this.IsRedirect(response.StatusCode)) { response = await this.HandleRedirect(response, completionOption, cancellationToken); if (response == null) { throw new ServiceException( new Error { Code = ErrorConstants.Codes.GeneralException, Message = ErrorConstants.Messages.LocationHeaderNotSetOnRedirect, }); } } if (!response.IsSuccessStatusCode && !this.IsRedirect(response.StatusCode)) { using (response) { var errorResponse = await this.ConvertErrorResponseAsync(response); Error error = null; if (errorResponse == null || errorResponse.Error == null) { if (response != null && response.StatusCode == HttpStatusCode.NotFound) { error = new Error { Code = ErrorConstants.Codes.ItemNotFound }; } else { error = new Error { Code = ErrorConstants.Codes.GeneralException, Message = ErrorConstants.Messages.UnexpectedExceptionResponse, }; } } else { error = errorResponse.Error; } if (string.IsNullOrEmpty(error.ThrowSite)) { IEnumerable<string> throwsiteValues; if (response.Headers.TryGetValues(CoreConstants.Headers.ThrowSiteHeaderName, out throwsiteValues)) { error.ThrowSite = throwsiteValues.FirstOrDefault(); } } throw new ServiceException(error); } } return response; } internal async Task<HttpResponseMessage> HandleRedirect( HttpResponseMessage initialResponse, HttpCompletionOption completionOption, CancellationToken cancellationToken, int redirectCount = 0) { if (initialResponse.Headers.Location == null) { return null; } using (initialResponse) using (var redirectRequest = new HttpRequestMessage(initialResponse.RequestMessage.Method, initialResponse.Headers.Location)) { // Preserve headers for the next request foreach (var header in initialResponse.RequestMessage.Headers) { redirectRequest.Headers.Add(header.Key, header.Value); } var response = await this.SendRequestAsync(redirectRequest, completionOption, cancellationToken); if (this.IsRedirect(response.StatusCode)) { if (++redirectCount > HttpProvider.maxRedirects) { throw new ServiceException( new Error { Code = ErrorConstants.Codes.TooManyRedirects, Message = string.Format(ErrorConstants.Messages.TooManyRedirectsFormatString, HttpProvider.maxRedirects) }); } return await this.HandleRedirect(response, completionOption, cancellationToken, redirectCount); } return response; } } internal async Task<HttpResponseMessage> SendRequestAsync( HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken) { try { return await this.httpClient.SendAsync(request, completionOption, cancellationToken); } catch (TaskCanceledException exception) { throw new ServiceException( new Error { Code = ErrorConstants.Codes.Timeout, Message = ErrorConstants.Messages.RequestTimedOut, }, exception); } catch (Exception exception) { throw new ServiceException( new Error { Code = ErrorConstants.Codes.GeneralException, Message = ErrorConstants.Messages.UnexpectedExceptionOnSend, }, exception); } } /// <summary> /// Converts the <see cref="HttpRequestException"/> into an <see cref="ErrorResponse"/> object; /// </summary> /// <param name="response">The <see cref="WebResponse"/> to convert.</param> /// <returns>The <see cref="ErrorResponse"/> object.</returns> private async Task<ErrorResponse> ConvertErrorResponseAsync(HttpResponseMessage response) { try { using (var responseStream = await response.Content.ReadAsStreamAsync()) { return this.Serializer.DeserializeObject<ErrorResponse>(responseStream); } } catch (Exception) { // If there's an exception deserializing the error response return null and throw a generic // ServiceException later. return null; } } private bool IsRedirect(HttpStatusCode statusCode) { return (int)statusCode >= 300 && (int)statusCode < 400 && statusCode != HttpStatusCode.NotModified; } } }
// 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.Globalization; //for NumberFormatInfo using TestLibrary; /// <summary> /// UInt16.System.IConvertible.ToString(string) /// Converts the numeric value of this instance to its equivalent string representation /// using the specified format. /// </summary> public class UInt16ToString { public static int Main() { UInt16ToString testObj = new UInt16ToString(); TestLibrary.TestFramework.BeginTestCase("for method: UInt16.System.ToString(string)"); if(testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal &= DoPosTest("PosTest1: Value is UInt16.MinValue, format is hexadecimal \"X\".", "PostTest1", UInt16.MinValue, "X", "0"); retVal &= DoPosTest("PosTest2: Value is UInt16 integer, format is hexadecimal \"X\".", "PostTest2", 8542, "X", "215E"); retVal &= DoPosTest("PosTest3: Value is UInt16.MaxValue, format is hexadecimal \"X\".", "PostTest3", UInt16.MaxValue, "X", "FFFF"); TestLibrary.Utilities.CurrentCulture = CustomCulture; retVal &= DoPosTest("PosTest4: Value is UInt16.MinValue, format is hexadecimal \"X\".", "PosTest4", UInt16.MinValue, "X", "0"); retVal &= DoPosTest("PosTest5: Value is UInt16 integer, format is general \"G\".", "PosTest5", 5641, "G", "5641"); retVal &= DoPosTest("PosTest6: Value is UInt16.MaxValue, format is general \"G\".", "PosTest6", UInt16.MaxValue, "G", "65535"); retVal &= DoPosTest("PosTest7: Value is UInt16 integer, format is currency \"C\".", "PosTest7", 8423, "C", "84.23,000USD"); retVal &= DoPosTest("PosTest8: Value is UInt16.MaxValue, format is currency \"C\".", "PosTes8", UInt16.MaxValue, "C", "6.55.35,000USD"); retVal &= DoPosTest("PosTest9: Value is UInt16.MinValue, format is currency \"C\".", "PosTes9", UInt16.MinValue, "C", "0,000USD"); retVal &= DoPosTest("PosTest10: Value is UInt16 integer, format is decimal \"D\".", "PosTest10", 2351, "D", "2351"); retVal &= DoPosTest("PosTest11: Value is UInt16.MaxValue integer, format is decimal \"D\".", "PosTest11", UInt16.MaxValue, "D", "65535"); retVal &= DoPosTest("PosTest12: Value is UInt16.MinValue integer, format is decimal \"D\".", "PosTest12", UInt16.MinValue, "D", "0"); retVal &= DoPosTest("PosTest13: Value is UInt16 integer, format is decimal \"E\".", "PosTest13", 2351, "E", TestLibrary.Utilities.IsWindows ? "2,351000E++003" : "2,351000E3"); retVal &= DoPosTest("PosTest14: Value is UInt16.MaxValue integer, format is decimal \"E\".", "PosTest14", UInt16.MaxValue, "E", TestLibrary.Utilities.IsWindows ? "6,553500E++004" : "6,553500E4"); retVal &= DoPosTest("PosTest15: Value is UInt16.MinValue integer, format is decimal \"E\".", "PosTest15", UInt16.MinValue, "E", TestLibrary.Utilities.IsWindows ? "0,000000E++000" : "0,000000E0"); retVal &= DoPosTest("PosTest16: Value is UInt16 integer, format is decimal \"F\".", "PosTest16", 2341, "F", "2341,000"); retVal &= DoPosTest("PosTest17: Value is UInt16 integer, format is decimal \"P\".", "PosTest17", 2341, "P", "234,100,0000~"); retVal &= DoPosTest("PosTest18: Value is UInt16 integer, format is decimal \"N\".", "PosTest18", 2341, "N", "23#41,000"); retVal &= DoPosTest("PosTest19: Value is UInt16 integer, format is decimal \"N\".", "PosTest19", 2341, null, "2341"); TestLibrary.Utilities.CurrentCulture = CurrentCulture; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #endregion #region Helper method for tests public bool DoPosTest(string testDesc, string id, UInt16 uintA, string format, string expectedValue) { bool retVal = true; string errorDesc; string actualValue; TestLibrary.TestFramework.BeginScenario(testDesc); try { actualValue = uintA.ToString(format); if (actualValue != expectedValue) { errorDesc = string.Format("The string representation of {0} is not the value {1} as expected: actual({2})", uintA, expectedValue, actualValue); errorDesc += "\nThe format info is \"" + format + "\" specified."; TestLibrary.TestFramework.LogError(id + "_001", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe UInt16 integer is " + uintA + ", format info is \"" + format + "\" speicifed."; TestLibrary.TestFramework.LogError(id + "_002", errorDesc); retVal = false; } return retVal; } #endregion #region Negative tests //FormatException public bool NegTest1() { const string c_TEST_ID = "N001"; const string c_TEST_DESC = "NegTest1: The format parameter is invalid -- \"R\". "; return this.DoInvalidFormatTest(c_TEST_ID, c_TEST_DESC, "39", "40", "R"); } public bool NegTest2() { const string c_TEST_ID = "N002"; const string c_TEST_DESC = "NegTest2: The format parameter is invalid -- \"r\". "; return this.DoInvalidFormatTest(c_TEST_ID, c_TEST_DESC, "41", "42", "r"); } public bool NegTest3() { const string c_TEST_ID = "N003"; const string c_TEST_DESC = "NegTest3: The format parameter is invalid -- \"z\". "; return this.DoInvalidFormatTest(c_TEST_ID, c_TEST_DESC, "43", "44", "z"); } #endregion #region Private Methods private CultureInfo CurrentCulture = TestLibrary.Utilities.CurrentCulture; private CultureInfo customCulture = null; private CultureInfo CustomCulture { get { if (null == customCulture) { customCulture = new CultureInfo(CultureInfo.CurrentCulture.Name); NumberFormatInfo nfi = customCulture.NumberFormat; //For "G" // NegativeSign, NumberDecimalSeparator, NumberDecimalDigits, PositiveSign nfi.NegativeSign = "@"; //Default: "-" nfi.NumberDecimalSeparator = ","; //Default: "." nfi.NumberDecimalDigits = 3; //Default: 2 nfi.PositiveSign = "++"; //Default: "+" //For "E" // PositiveSign, NegativeSign, and NumberDecimalSeparator. // If precision specifier is omitted, a default of six digits after the decimal point is used. //For "R" // NegativeSign, NumberDecimalSeparator and PositiveSign //For "X", The result string isn't affected by the formatting information of the current NumberFormatInfo //For "C" // CurrencyPositivePattern, CurrencySymbol, CurrencyDecimalDigits, CurrencyDecimalSeparator, CurrencyGroupSeparator, CurrencyGroupSizes, NegativeSign and CurrencyNegativePattern nfi.CurrencyDecimalDigits = 3; //Default: 2 nfi.CurrencyDecimalSeparator = ","; //Default: "," nfi.CurrencyGroupSeparator = "."; //Default: "." nfi.CurrencyGroupSizes = new int[] { 2 }; //Default: new int[]{3} nfi.CurrencyNegativePattern = 2; //Default: 0 nfi.CurrencyPositivePattern = 1; //Default: 0 nfi.CurrencySymbol = "USD"; //Default: "$" //For "D" // NegativeSign //For "E" // PositiveSign, NumberDecimalSeparator and NegativeSign. // If precision specifier is omitted, a default of six digits after the decimal point is used. nfi.PositiveSign = "++"; //Default: "+" nfi.NumberDecimalSeparator = ","; //Default: "." //For "F" // NumberDecimalDigits, and NumberDecimalSeparator and NegativeSign. nfi.NumberDecimalDigits = 3; //Default: 2 //For "N" // NumberGroupSizes, NumberGroupSeparator, NumberDecimalSeparator, NumberDecimalDigits, NumberNegativePattern and NegativeSign. nfi.NumberGroupSizes = new int[] { 2 }; //Default: 3 nfi.NumberGroupSeparator = "#"; //Default: "," //For "P" // PercentPositivePattern, PercentNegativePattern, NegativeSign, PercentSymbol, PercentDecimalDigits, PercentDecimalSeparator, PercentGroupSeparator and PercentGroupSizes nfi.PercentPositivePattern = 1; //Default: 0 nfi.PercentNegativePattern = 2; //Default: 0 nfi.PercentSymbol = "~"; //Default: "%" nfi.PercentDecimalDigits = 4; //Default: 2 nfi.PercentDecimalSeparator = ","; //Default: "." nfi.PercentGroupSizes[0] = 2; //Default: 3 nfi.PercentGroupSeparator = ","; customCulture.NumberFormat = nfi; } return customCulture; } } #endregion #region Helper methods for negative tests public bool DoInvalidFormatTest(string testId, string testDesc, string errorNum1, string errorNum2, string format) { bool retVal = true; string errorDesc; UInt16 uintA = (UInt16)(TestLibrary.Generator.GetInt32() % (UInt16.MaxValue + 1)); TestLibrary.TestFramework.BeginScenario(testDesc); try { uintA.ToString(format); errorDesc = "FormatException is not thrown as expected."; errorDesc = string.Format("\nUInt16 value is {0}, format is {1}.", uintA, format); TestLibrary.TestFramework.LogError(errorNum1 + " TestId-" + testId, errorDesc); retVal = false; } catch (FormatException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc = string.Format("\nUInt16 value is {0}, format is {1}.", uintA, format); TestLibrary.TestFramework.LogError(errorNum2 + " TestId-" + testId, errorDesc); retVal = false; } return retVal; } #endregion }
//--------------------------------------------------------------------------- // // <copyright file="DoubleAnimationUsingKeyFrames.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.KnownBoxes; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Windows; using System.Windows.Markup; using System.Windows.Media.Animation; using System.Windows.Media.Media3D; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using MS.Internal.PresentationCore; namespace System.Windows.Media.Animation { /// <summary> /// This class is used to animate a Double property value along a set /// of key frames. /// </summary> [ContentProperty("KeyFrames")] public class DoubleAnimationUsingKeyFrames : DoubleAnimationBase, IKeyFrameAnimation, IAddChild { #region Data private DoubleKeyFrameCollection _keyFrames; private ResolvedKeyFrameEntry[] _sortedResolvedKeyFrames; private bool _areKeyTimesValid; #endregion #region Constructors /// <Summary> /// Creates a new KeyFrameDoubleAnimation. /// </Summary> public DoubleAnimationUsingKeyFrames() : base() { _areKeyTimesValid = true; } #endregion #region Freezable /// <summary> /// Creates a copy of this KeyFrameDoubleAnimation. /// </summary> /// <returns>The copy</returns> public new DoubleAnimationUsingKeyFrames Clone() { return (DoubleAnimationUsingKeyFrames)base.Clone(); } /// <summary> /// Returns a version of this class with all its base property values /// set to the current animated values and removes the animations. /// </summary> /// <returns> /// Since this class isn't animated, this method will always just return /// this instance of the class. /// </returns> public new DoubleAnimationUsingKeyFrames CloneCurrentValue() { return (DoubleAnimationUsingKeyFrames)base.CloneCurrentValue(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.FreezeCore">Freezable.FreezeCore</see>. /// </summary> protected override bool FreezeCore(bool isChecking) { bool canFreeze = base.FreezeCore(isChecking); canFreeze &= Freezable.Freeze(_keyFrames, isChecking); if (canFreeze & !_areKeyTimesValid) { ResolveKeyTimes(); } return canFreeze; } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.OnChanged">Freezable.OnChanged</see>. /// </summary> protected override void OnChanged() { _areKeyTimesValid = false; base.OnChanged(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new DoubleAnimationUsingKeyFrames(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCore(System.Windows.Freezable)">Freezable.CloneCore</see>. /// </summary> protected override void CloneCore(Freezable sourceFreezable) { DoubleAnimationUsingKeyFrames sourceAnimation = (DoubleAnimationUsingKeyFrames) sourceFreezable; base.CloneCore(sourceFreezable); CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(Freezable)">Freezable.CloneCurrentValueCore</see>. /// </summary> protected override void CloneCurrentValueCore(Freezable sourceFreezable) { DoubleAnimationUsingKeyFrames sourceAnimation = (DoubleAnimationUsingKeyFrames) sourceFreezable; base.CloneCurrentValueCore(sourceFreezable); CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(Freezable)">Freezable.GetAsFrozenCore</see>. /// </summary> protected override void GetAsFrozenCore(Freezable source) { DoubleAnimationUsingKeyFrames sourceAnimation = (DoubleAnimationUsingKeyFrames) source; base.GetAsFrozenCore(source); CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>. /// </summary> protected override void GetCurrentValueAsFrozenCore(Freezable source) { DoubleAnimationUsingKeyFrames sourceAnimation = (DoubleAnimationUsingKeyFrames) source; base.GetCurrentValueAsFrozenCore(source); CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true); } /// <summary> /// Helper used by the four Freezable clone methods to copy the resolved key times and /// key frames. The Get*AsFrozenCore methods are implemented the same as the Clone*Core /// methods; Get*AsFrozen at the top level will recursively Freeze so it's not done here. /// </summary> /// <param name="sourceAnimation"></param> /// <param name="isCurrentValueClone"></param> private void CopyCommon(DoubleAnimationUsingKeyFrames sourceAnimation, bool isCurrentValueClone) { _areKeyTimesValid = sourceAnimation._areKeyTimesValid; if ( _areKeyTimesValid && sourceAnimation._sortedResolvedKeyFrames != null) { // _sortedResolvedKeyFrames is an array of ResolvedKeyFrameEntry so the notion of CurrentValueClone doesn't apply _sortedResolvedKeyFrames = (ResolvedKeyFrameEntry[])sourceAnimation._sortedResolvedKeyFrames.Clone(); } if (sourceAnimation._keyFrames != null) { if (isCurrentValueClone) { _keyFrames = (DoubleKeyFrameCollection)sourceAnimation._keyFrames.CloneCurrentValue(); } else { _keyFrames = (DoubleKeyFrameCollection)sourceAnimation._keyFrames.Clone(); } OnFreezablePropertyChanged(null, _keyFrames); } } #endregion // Freezable #region IAddChild interface /// <summary> /// Adds a child object to this KeyFrameAnimation. /// </summary> /// <param name="child"> /// The child object to add. /// </param> /// <remarks> /// A KeyFrameAnimation only accepts a KeyFrame of the proper type as /// a child. /// </remarks> void IAddChild.AddChild(object child) { WritePreamble(); if (child == null) { throw new ArgumentNullException("child"); } AddChild(child); WritePostscript(); } /// <summary> /// Implemented to allow KeyFrames to be direct children /// of KeyFrameAnimations in markup. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void AddChild(object child) { DoubleKeyFrame keyFrame = child as DoubleKeyFrame; if (keyFrame != null) { KeyFrames.Add(keyFrame); } else { throw new ArgumentException(SR.Get(SRID.Animation_ChildMustBeKeyFrame), "child"); } } /// <summary> /// Adds a text string as a child of this KeyFrameAnimation. /// </summary> /// <param name="childText"> /// The text to add. /// </param> /// <remarks> /// A KeyFrameAnimation does not accept text as a child, so this method will /// raise an InvalididOperationException unless a derived class has /// overridden the behavior to add text. /// </remarks> /// <exception cref="ArgumentNullException">The childText parameter is /// null.</exception> void IAddChild.AddText(string childText) { if (childText == null) { throw new ArgumentNullException("childText"); } AddText(childText); } /// <summary> /// This method performs the core functionality of the AddText() /// method on the IAddChild interface. For a KeyFrameAnimation this means /// throwing and InvalidOperationException because it doesn't /// support adding text. /// </summary> /// <remarks> /// This method is the only core implementation. It does not call /// WritePreamble() or WritePostscript(). It also doesn't throw an /// ArgumentNullException if the childText parameter is null. These tasks /// are performed by the interface implementation. Therefore, it's OK /// for a derived class to override this method and call the base /// class implementation only if they determine that it's the right /// course of action. The derived class can rely on KeyFrameAnimation's /// implementation of IAddChild.AddChild or implement their own /// following the Freezable pattern since that would be a public /// method. /// </remarks> /// <param name="childText">A string representing the child text that /// should be added. If this is a KeyFrameAnimation an exception will be /// thrown.</param> /// <exception cref="InvalidOperationException">Timelines have no way /// of adding text.</exception> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void AddText(string childText) { throw new InvalidOperationException(SR.Get(SRID.Animation_NoTextChildren)); } #endregion #region DoubleAnimationBase /// <summary> /// Calculates the value this animation believes should be the current value for the property. /// </summary> /// <param name="defaultOriginValue"> /// This value is the suggested origin value provided to the animation /// to be used if the animation does not have its own concept of a /// start value. If this animation is the first in a composition chain /// this value will be the snapshot value if one is available or the /// base property value if it is not; otherise this value will be the /// value returned by the previous animation in the chain with an /// animationClock that is not Stopped. /// </param> /// <param name="defaultDestinationValue"> /// This value is the suggested destination value provided to the animation /// to be used if the animation does not have its own concept of an /// end value. This value will be the base value if the animation is /// in the first composition layer of animations on a property; /// otherwise this value will be the output value from the previous /// composition layer of animations for the property. /// </param> /// <param name="animationClock"> /// This is the animationClock which can generate the CurrentTime or /// CurrentProgress value to be used by the animation to generate its /// output value. /// </param> /// <returns> /// The value this animation believes should be the current value for the property. /// </returns> protected sealed override Double GetCurrentValueCore( Double defaultOriginValue, Double defaultDestinationValue, AnimationClock animationClock) { Debug.Assert(animationClock.CurrentState != ClockState.Stopped); if (_keyFrames == null) { return defaultDestinationValue; } // We resolved our KeyTimes when we froze, but also got notified // of the frozen state and therefore invalidated ourselves. if (!_areKeyTimesValid) { ResolveKeyTimes(); } if (_sortedResolvedKeyFrames == null) { return defaultDestinationValue; } TimeSpan currentTime = animationClock.CurrentTime.Value; Int32 keyFrameCount = _sortedResolvedKeyFrames.Length; Int32 maxKeyFrameIndex = keyFrameCount - 1; Double currentIterationValue; Debug.Assert(maxKeyFrameIndex >= 0, "maxKeyFrameIndex is less than zero which means we don't actually have any key frames."); Int32 currentResolvedKeyFrameIndex = 0; // Skip all the key frames with key times lower than the current time. // currentResolvedKeyFrameIndex will be greater than maxKeyFrameIndex // if we are past the last key frame. while ( currentResolvedKeyFrameIndex < keyFrameCount && currentTime > _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime) { currentResolvedKeyFrameIndex++; } // If there are multiple key frames at the same key time, be sure to go to the last one. while ( currentResolvedKeyFrameIndex < maxKeyFrameIndex && currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex + 1]._resolvedKeyTime) { currentResolvedKeyFrameIndex++; } if (currentResolvedKeyFrameIndex == keyFrameCount) { // Past the last key frame. currentIterationValue = GetResolvedKeyFrameValue(maxKeyFrameIndex); } else if (currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime) { // Exactly on a key frame. currentIterationValue = GetResolvedKeyFrameValue(currentResolvedKeyFrameIndex); } else { // Between two key frames. Double currentSegmentProgress = 0.0; Double fromValue; if (currentResolvedKeyFrameIndex == 0) { // The current key frame is the first key frame so we have // some special rules for determining the fromValue and an // optimized method of calculating the currentSegmentProgress. // If we're additive we want the base value to be a zero value // so that if there isn't a key frame at time 0.0, we'll use // the zero value for the time 0.0 value and then add that // later to the base value. if (IsAdditive) { fromValue = AnimatedTypeHelpers.GetZeroValueDouble(defaultOriginValue); } else { fromValue = defaultOriginValue; } // Current segment time divided by the segment duration. // Note: the reason this works is that we know that we're in // the first segment, so we can assume: // // currentTime.TotalMilliseconds = current segment time // _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds = current segment duration currentSegmentProgress = currentTime.TotalMilliseconds / _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds; } else { Int32 previousResolvedKeyFrameIndex = currentResolvedKeyFrameIndex - 1; TimeSpan previousResolvedKeyTime = _sortedResolvedKeyFrames[previousResolvedKeyFrameIndex]._resolvedKeyTime; fromValue = GetResolvedKeyFrameValue(previousResolvedKeyFrameIndex); TimeSpan segmentCurrentTime = currentTime - previousResolvedKeyTime; TimeSpan segmentDuration = _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime - previousResolvedKeyTime; currentSegmentProgress = segmentCurrentTime.TotalMilliseconds / segmentDuration.TotalMilliseconds; } currentIterationValue = GetResolvedKeyFrame(currentResolvedKeyFrameIndex).InterpolateValue(fromValue, currentSegmentProgress); } // If we're cumulative, we need to multiply the final key frame // value by the current repeat count and add this to the return // value. if (IsCumulative) { Double currentRepeat = (Double)(animationClock.CurrentIteration - 1); if (currentRepeat > 0.0) { currentIterationValue = AnimatedTypeHelpers.AddDouble( currentIterationValue, AnimatedTypeHelpers.ScaleDouble(GetResolvedKeyFrameValue(maxKeyFrameIndex), currentRepeat)); } } // If we're additive we need to add the base value to the return value. if (IsAdditive) { return AnimatedTypeHelpers.AddDouble(defaultOriginValue, currentIterationValue); } return currentIterationValue; } /// <summary> /// Provide a custom natural Duration when the Duration property is set to Automatic. /// </summary> /// <param name="clock"> /// The Clock whose natural duration is desired. /// </param> /// <returns> /// If the last KeyFrame of this animation is a KeyTime, then this will /// be used as the NaturalDuration; otherwise it will be one second. /// </returns> protected override sealed Duration GetNaturalDurationCore(Clock clock) { return new Duration(LargestTimeSpanKeyTime); } #endregion #region IKeyFrameAnimation /// <summary> /// Returns the DoubleKeyFrameCollection used by this KeyFrameDoubleAnimation. /// </summary> IList IKeyFrameAnimation.KeyFrames { get { return KeyFrames; } set { KeyFrames = (DoubleKeyFrameCollection)value; } } /// <summary> /// Returns the DoubleKeyFrameCollection used by this KeyFrameDoubleAnimation. /// </summary> public DoubleKeyFrameCollection KeyFrames { get { ReadPreamble(); // The reason we don't just set _keyFrames to the empty collection // in the first place is that null tells us that the user has not // asked for the collection yet. The first time they ask for the // collection and we're unfrozen, policy dictates that we give // them a new unfrozen collection. All subsequent times they will // get whatever collection is present, whether frozen or unfrozen. if (_keyFrames == null) { if (this.IsFrozen) { _keyFrames = DoubleKeyFrameCollection.Empty; } else { WritePreamble(); _keyFrames = new DoubleKeyFrameCollection(); OnFreezablePropertyChanged(null, _keyFrames); WritePostscript(); } } return _keyFrames; } set { if (value == null) { throw new ArgumentNullException("value"); } WritePreamble(); if (value != _keyFrames) { OnFreezablePropertyChanged(_keyFrames, value); _keyFrames = value; WritePostscript(); } } } /// <summary> /// Returns true if we should serialize the KeyFrames, property for this Animation. /// </summary> /// <returns>True if we should serialize the KeyFrames property for this Animation; otherwise false.</returns> [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeKeyFrames() { ReadPreamble(); return _keyFrames != null && _keyFrames.Count > 0; } #endregion #region Public Properties /// <summary> /// If this property is set to true, this animation will add its value /// to the base value or the value of the previous animation in the /// composition chain. Another way of saying this is that the units /// specified in the animation are relative to the base value rather /// than absolute units. /// </summary> /// <remarks> /// In the case where the first key frame's resolved key time is not /// 0.0 there is slightly different behavior between KeyFrameDoubleAnimations /// with IsAdditive set and without. Animations with the property set to false /// will behave as if there is a key frame at time 0.0 with the value of the /// base value. Animations with the property set to true will behave as if /// there is a key frame at time 0.0 with a zero value appropriate to the type /// of the animation. These behaviors provide the results most commonly expected /// and can be overridden by simply adding a key frame at time 0.0 with the preferred value. /// </remarks> public bool IsAdditive { get { return (bool)GetValue(IsAdditiveProperty); } set { SetValueInternal(IsAdditiveProperty, BooleanBoxes.Box(value)); } } /// <summary> /// If this property is set to true, the value of this animation will /// accumulate over repeat cycles. For example, if this is a point /// animation and your key frames describe something approximating and /// arc, setting this property to true will result in an animation that /// would appear to bounce the point across the screen. /// </summary> /// <remarks> /// This property works along with the IsAdditive property. Setting /// this value to true has no effect unless IsAdditive is also set /// to true. /// </remarks> public bool IsCumulative { get { return (bool)GetValue(IsCumulativeProperty); } set { SetValueInternal(IsCumulativeProperty, BooleanBoxes.Box(value)); } } #endregion #region Private Methods private struct KeyTimeBlock { public int BeginIndex; public int EndIndex; } private Double GetResolvedKeyFrameValue(Int32 resolvedKeyFrameIndex) { Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrameValue"); return GetResolvedKeyFrame(resolvedKeyFrameIndex).Value; } private DoubleKeyFrame GetResolvedKeyFrame(Int32 resolvedKeyFrameIndex) { Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrame"); return _keyFrames[_sortedResolvedKeyFrames[resolvedKeyFrameIndex]._originalKeyFrameIndex]; } /// <summary> /// Returns the largest time span specified key time from all of the key frames. /// If there are not time span key times a time span of one second is returned /// to match the default natural duration of the From/To/By animations. /// </summary> private TimeSpan LargestTimeSpanKeyTime { get { bool hasTimeSpanKeyTime = false; TimeSpan largestTimeSpanKeyTime = TimeSpan.Zero; if (_keyFrames != null) { Int32 keyFrameCount = _keyFrames.Count; for (int index = 0; index < keyFrameCount; index++) { KeyTime keyTime = _keyFrames[index].KeyTime; if (keyTime.Type == KeyTimeType.TimeSpan) { hasTimeSpanKeyTime = true; if (keyTime.TimeSpan > largestTimeSpanKeyTime) { largestTimeSpanKeyTime = keyTime.TimeSpan; } } } } if (hasTimeSpanKeyTime) { return largestTimeSpanKeyTime; } else { return TimeSpan.FromSeconds(1.0); } } } private void ResolveKeyTimes() { Debug.Assert(!_areKeyTimesValid, "KeyFrameDoubleAnimaton.ResolveKeyTimes() shouldn't be called if the key times are already valid."); int keyFrameCount = 0; if (_keyFrames != null) { keyFrameCount = _keyFrames.Count; } if (keyFrameCount == 0) { _sortedResolvedKeyFrames = null; _areKeyTimesValid = true; return; } _sortedResolvedKeyFrames = new ResolvedKeyFrameEntry[keyFrameCount]; int index = 0; // Initialize the _originalKeyFrameIndex. for ( ; index < keyFrameCount; index++) { _sortedResolvedKeyFrames[index]._originalKeyFrameIndex = index; } // calculationDuration represents the time span we will use to resolve // percent key times. This is defined as the value in the following // precedence order: // 1. The animation's duration, but only if it is a time span, not auto or forever. // 2. The largest time span specified key time of all the key frames. // 3. 1 second, to match the From/To/By animations. TimeSpan calculationDuration = TimeSpan.Zero; Duration duration = Duration; if (duration.HasTimeSpan) { calculationDuration = duration.TimeSpan; } else { calculationDuration = LargestTimeSpanKeyTime; } int maxKeyFrameIndex = keyFrameCount - 1; ArrayList unspecifiedBlocks = new ArrayList(); bool hasPacedKeyTimes = false; // // Pass 1: Resolve Percent and Time key times. // index = 0; while (index < keyFrameCount) { KeyTime keyTime = _keyFrames[index].KeyTime; switch (keyTime.Type) { case KeyTimeType.Percent: _sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.FromMilliseconds( keyTime.Percent * calculationDuration.TotalMilliseconds); index++; break; case KeyTimeType.TimeSpan: _sortedResolvedKeyFrames[index]._resolvedKeyTime = keyTime.TimeSpan; index++; break; case KeyTimeType.Paced: case KeyTimeType.Uniform: if (index == maxKeyFrameIndex) { // If the last key frame doesn't have a specific time // associated with it its resolved key time will be // set to the calculationDuration, which is the // defined in the comments above where it is set. // Reason: We only want extra time at the end of the // key frames if the user specifically states that // the last key frame ends before the animation ends. _sortedResolvedKeyFrames[index]._resolvedKeyTime = calculationDuration; index++; } else if ( index == 0 && keyTime.Type == KeyTimeType.Paced) { // Note: It's important that this block come after // the previous if block because of rule precendence. // If the first key frame in a multi-frame key frame // collection is paced, we set its resolved key time // to 0.0 for performance reasons. If we didn't, the // resolved key time list would be dependent on the // base value which can change every animation frame // in many cases. _sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.Zero; index++; } else { if (keyTime.Type == KeyTimeType.Paced) { hasPacedKeyTimes = true; } KeyTimeBlock block = new KeyTimeBlock(); block.BeginIndex = index; // NOTE: We don't want to go all the way up to the // last frame because if it is Uniform or Paced its // resolved key time will be set to the calculation // duration using the logic above. // // This is why the logic is: // ((++index) < maxKeyFrameIndex) // instead of: // ((++index) < keyFrameCount) while ((++index) < maxKeyFrameIndex) { KeyTimeType type = _keyFrames[index].KeyTime.Type; if ( type == KeyTimeType.Percent || type == KeyTimeType.TimeSpan) { break; } else if (type == KeyTimeType.Paced) { hasPacedKeyTimes = true; } } Debug.Assert(index < keyFrameCount, "The end index for a block of unspecified key frames is out of bounds."); block.EndIndex = index; unspecifiedBlocks.Add(block); } break; } } // // Pass 2: Resolve Uniform key times. // for (int j = 0; j < unspecifiedBlocks.Count; j++) { KeyTimeBlock block = (KeyTimeBlock)unspecifiedBlocks[j]; TimeSpan blockBeginTime = TimeSpan.Zero; if (block.BeginIndex > 0) { blockBeginTime = _sortedResolvedKeyFrames[block.BeginIndex - 1]._resolvedKeyTime; } // The number of segments is equal to the number of key // frames we're working on plus 1. Think about the case // where we're working on a single key frame. There's a // segment before it and a segment after it. // // Time known Uniform Time known // ^ ^ ^ // | | | // | (segment 1) | (segment 2) | Int64 segmentCount = (block.EndIndex - block.BeginIndex) + 1; TimeSpan uniformTimeStep = TimeSpan.FromTicks((_sortedResolvedKeyFrames[block.EndIndex]._resolvedKeyTime - blockBeginTime).Ticks / segmentCount); index = block.BeginIndex; TimeSpan resolvedTime = blockBeginTime + uniformTimeStep; while (index < block.EndIndex) { _sortedResolvedKeyFrames[index]._resolvedKeyTime = resolvedTime; resolvedTime += uniformTimeStep; index++; } } // // Pass 3: Resolve Paced key times. // if (hasPacedKeyTimes) { ResolvePacedKeyTimes(); } // // Sort resolved key frame entries. // Array.Sort(_sortedResolvedKeyFrames); _areKeyTimesValid = true; return; } /// <summary> /// This should only be called from ResolveKeyTimes and only at the /// appropriate time. /// </summary> private void ResolvePacedKeyTimes() { Debug.Assert(_keyFrames != null && _keyFrames.Count > 2, "Caller must guard against calling this method when there are insufficient keyframes."); // If the first key frame is paced its key time has already // been resolved, so we start at index 1. int index = 1; int maxKeyFrameIndex = _sortedResolvedKeyFrames.Length - 1; do { if (_keyFrames[index].KeyTime.Type == KeyTimeType.Paced) { // // We've found a paced key frame so this is the // beginning of a paced block. // // The first paced key frame in this block. int firstPacedBlockKeyFrameIndex = index; // List of segment lengths for this paced block. List<Double> segmentLengths = new List<Double>(); // The resolved key time for the key frame before this // block which we'll use as our starting point. TimeSpan prePacedBlockKeyTime = _sortedResolvedKeyFrames[index - 1]._resolvedKeyTime; // The total of the segment lengths of the paced key // frames in this block. Double totalLength = 0.0; // The key value of the previous key frame which will be // used to determine the segment length of this key frame. Double prevKeyValue = _keyFrames[index - 1].Value; do { Double currentKeyValue = _keyFrames[index].Value; // Determine the segment length for this key frame and // add to the total length. totalLength += AnimatedTypeHelpers.GetSegmentLengthDouble(prevKeyValue, currentKeyValue); // Temporarily store the distance into the total length // that this key frame represents in the resolved // key times array to be converted to a resolved key // time outside of this loop. segmentLengths.Add(totalLength); // Prepare for the next iteration. prevKeyValue = currentKeyValue; index++; } while ( index < maxKeyFrameIndex && _keyFrames[index].KeyTime.Type == KeyTimeType.Paced); // index is currently set to the index of the key frame // after the last paced key frame. This will always // be a valid index because we limit ourselves with // maxKeyFrameIndex. // We need to add the distance between the last paced key // frame and the next key frame to get the total distance // inside the key frame block. totalLength += AnimatedTypeHelpers.GetSegmentLengthDouble(prevKeyValue, _keyFrames[index].Value); // Calculate the time available in the resolved key time space. TimeSpan pacedBlockDuration = _sortedResolvedKeyFrames[index]._resolvedKeyTime - prePacedBlockKeyTime; // Convert lengths in segmentLengths list to resolved // key times for the paced key frames in this block. for (int i = 0, currentKeyFrameIndex = firstPacedBlockKeyFrameIndex; i < segmentLengths.Count; i++, currentKeyFrameIndex++) { // The resolved key time for each key frame is: // // The key time of the key frame before this paced block // + ((the percentage of the way through the total length) // * the resolved key time space available for the block) _sortedResolvedKeyFrames[currentKeyFrameIndex]._resolvedKeyTime = prePacedBlockKeyTime + TimeSpan.FromMilliseconds( (segmentLengths[i] / totalLength) * pacedBlockDuration.TotalMilliseconds); } } else { index++; } } while (index < maxKeyFrameIndex); } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using IServiceProvider = System.IServiceProvider; using ShellConstants = Microsoft.VisualStudio.Shell.Interop.Constants; namespace Microsoft.VisualStudioTools.Project { /// <summary> /// This abstract class handles opening, saving of items in the hierarchy. /// </summary> internal abstract class DocumentManager { #region fields private readonly HierarchyNode node = null; #endregion #region properties protected HierarchyNode Node => this.node; #endregion #region ctors protected DocumentManager(HierarchyNode node) { Utilities.ArgumentNotNull("node", node); this.node = node; } #endregion #region virtual methods /// <summary> /// Open a document using the standard editor. This method has no implementation since a document is abstract in this context /// </summary> /// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param> /// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param> /// <param name="windowFrame">A reference to the window frame that is mapped to the document</param> /// <param name="windowFrameAction">Determine the UI action on the document window</param> /// <returns>NotImplementedException</returns> /// <remarks>See FileDocumentManager class for an implementation of this method</remarks> public virtual int Open(ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame windowFrame, WindowFrameShowAction windowFrameAction) { throw new NotImplementedException(); } /// <summary> /// Open a document using a specific editor. This method has no implementation. /// </summary> /// <param name="editorFlags">Specifies actions to take when opening a specific editor. Possible editor flags are defined in the enumeration Microsoft.VisualStudio.Shell.Interop.__VSOSPEFLAGS</param> /// <param name="editorType">Unique identifier of the editor type</param> /// <param name="physicalView">Name of the physical view. If null, the environment calls MapLogicalView on the editor factory to determine the physical view that corresponds to the logical view. In this case, null does not specify the primary view, but rather indicates that you do not know which view corresponds to the logical view</param> /// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param> /// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param> /// <param name="frame">A reference to the window frame that is mapped to the document</param> /// <param name="windowFrameAction">Determine the UI action on the document window</param> /// <returns>NotImplementedException</returns> /// <remarks>See FileDocumentManager for an implementation of this method</remarks> public virtual int OpenWithSpecific(uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame frame, WindowFrameShowAction windowFrameAction) { throw new NotImplementedException(); } /// <summary> /// Open a document using a specific editor. This method has no implementation. /// </summary> /// <param name="editorFlags">Specifies actions to take when opening a specific editor. Possible editor flags are defined in the enumeration Microsoft.VisualStudio.Shell.Interop.__VSOSPEFLAGS</param> /// <param name="editorType">Unique identifier of the editor type</param> /// <param name="physicalView">Name of the physical view. If null, the environment calls MapLogicalView on the editor factory to determine the physical view that corresponds to the logical view. In this case, null does not specify the primary view, but rather indicates that you do not know which view corresponds to the logical view</param> /// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param> /// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param> /// <param name="frame">A reference to the window frame that is mapped to the document</param> /// <param name="windowFrameAction">Determine the UI action on the document window</param> /// <returns>NotImplementedException</returns> /// <remarks>See FileDocumentManager for an implementation of this method</remarks> public virtual int ReOpenWithSpecific(uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame frame, WindowFrameShowAction windowFrameAction) { return OpenWithSpecific(editorFlags, ref editorType, physicalView, ref logicalView, docDataExisting, out frame, windowFrameAction); } /// <summary> /// Close an open document window /// </summary> /// <param name="closeFlag">Decides how to close the document</param> /// <returns>S_OK if successful, otherwise an error is returned</returns> public virtual int Close(__FRAMECLOSE closeFlag) { if (this.node == null || this.node.ProjectMgr == null || this.node.ProjectMgr.IsClosed || this.node.ProjectMgr.IsClosing) { return VSConstants.E_FAIL; } if (this.IsOpenedByUs) { var shell = this.Node.ProjectMgr.Site.GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; var logicalView = Guid.Empty; uint grfIDO = 0; IVsUIHierarchy pHierOpen; var itemIdOpen = new uint[1]; IVsWindowFrame windowFrame; int fOpen; ErrorHandler.ThrowOnFailure(shell.IsDocumentOpen(this.Node.ProjectMgr, this.Node.ID, this.Node.Url, ref logicalView, grfIDO, out pHierOpen, itemIdOpen, out windowFrame, out fOpen)); if (windowFrame != null) { return windowFrame.CloseFrame((uint)closeFlag); } } return VSConstants.S_OK; } /// <summary> /// Silently saves an open document /// </summary> /// <param name="saveIfDirty">Save the open document only if it is dirty</param> /// <remarks>The call to SaveDocData may return Microsoft.VisualStudio.Shell.Interop.PFF_RESULTS.STG_S_DATALOSS to indicate some characters could not be represented in the current codepage</remarks> public virtual void Save(bool saveIfDirty) { if (saveIfDirty && this.IsDirty) { var persistDocData = this.DocData; if (persistDocData != null) { string name; int cancelled; ErrorHandler.ThrowOnFailure(persistDocData.SaveDocData(VSSAVEFLAGS.VSSAVE_SilentSave, out name, out cancelled)); } } } #endregion /// <summary> /// Queries the RDT to see if the document is currently edited and not saved. /// </summary> public bool IsDirty { get { var docTable = (IVsRunningDocumentTable4)this.node.ProjectMgr.GetService(typeof(SVsRunningDocumentTable)); if (!docTable.IsMonikerValid(this.node.GetMkDocument())) { return false; } return docTable.IsDocumentDirty(docTable.GetDocumentCookie(this.node.GetMkDocument())); } } /// <summary> /// Queries the RDT to see if the document was opened by our project. /// </summary> public bool IsOpenedByUs { get { var docTable = (IVsRunningDocumentTable4)this.node.ProjectMgr.GetService(typeof(SVsRunningDocumentTable)); if (!docTable.IsMonikerValid(this.node.GetMkDocument())) { return false; } IVsHierarchy hierarchy; uint itemId; docTable.GetDocumentHierarchyItem( docTable.GetDocumentCookie(this.node.GetMkDocument()), out hierarchy, out itemId ); return Utilities.IsSameComObject(this.node.ProjectMgr, hierarchy); } } /// <summary> /// Returns the doc cookie in the RDT for the associated file. /// </summary> public uint DocCookie { get { var docTable = (IVsRunningDocumentTable4)this.node.ProjectMgr.GetService(typeof(SVsRunningDocumentTable)); if (!docTable.IsMonikerValid(this.node.GetMkDocument())) { return (uint)ShellConstants.VSDOCCOOKIE_NIL; } return docTable.GetDocumentCookie(this.node.GetMkDocument()); } } /// <summary> /// Returns the IVsPersistDocData associated with the document, or null if there isn't one. /// </summary> public IVsPersistDocData DocData { get { var docTable = (IVsRunningDocumentTable4)this.node.ProjectMgr.GetService(typeof(SVsRunningDocumentTable)); if (!docTable.IsMonikerValid(this.node.GetMkDocument())) { return null; } return docTable.GetDocumentData(docTable.GetDocumentCookie(this.node.GetMkDocument())) as IVsPersistDocData; } } #region helper methods #if !DEV12_OR_LATER /// <summary> /// Get document properties from RDT /// </summary> private void GetDocInfo( out bool isOpen, // true if the doc is opened out bool isDirty, // true if the doc is dirty out bool isOpenedByUs, // true if opened by our project out uint docCookie, // VSDOCCOOKIE if open out IVsPersistDocData persistDocData) { isOpen = isDirty = isOpenedByUs = false; docCookie = (uint)ShellConstants.VSDOCCOOKIE_NIL; persistDocData = null; if (this.node == null || this.node.ProjectMgr == null || this.node.ProjectMgr.IsClosed) { return; } IVsHierarchy hierarchy; uint vsitemid = VSConstants.VSITEMID_NIL; VsShellUtilities.GetRDTDocumentInfo(this.node.ProjectMgr.Site, this.node.Url, out hierarchy, out vsitemid, out persistDocData, out docCookie); if (hierarchy == null || docCookie == (uint)ShellConstants.VSDOCCOOKIE_NIL) { return; } isOpen = true; // check if the doc is opened by another project if (Utilities.IsSameComObject(this.node.ProjectMgr, hierarchy)) { isOpenedByUs = true; } if (persistDocData != null) { int isDocDataDirty; ErrorHandler.ThrowOnFailure(persistDocData.IsDocDataDirty(out isDocDataDirty)); isDirty = (isDocDataDirty != 0); } } #endif protected string GetOwnerCaption() { Debug.Assert(this.node != null, "No node has been initialized for the document manager"); object pvar; ErrorHandler.ThrowOnFailure(this.node.ProjectMgr.GetProperty(this.node.ID, (int)__VSHPROPID.VSHPROPID_Caption, out pvar)); return (pvar as string); } protected static void CloseWindowFrame(ref IVsWindowFrame windowFrame) { if (windowFrame != null) { try { ErrorHandler.ThrowOnFailure(windowFrame.CloseFrame(0)); } finally { windowFrame = null; } } } protected string GetFullPathForDocument() { var fullPath = string.Empty; // Get the URL representing the item fullPath = this.node.GetMkDocument(); Debug.Assert(!string.IsNullOrEmpty(fullPath), "Could not retrive the fullpath for the node" + this.Node.ID.ToString(CultureInfo.CurrentCulture)); return fullPath; } #endregion #region static methods /// <summary> /// Updates the caption for all windows associated to the document. /// </summary> /// <param name="site">The service provider.</param> /// <param name="caption">The new caption.</param> /// <param name="docData">The IUnknown interface to a document data object associated with a registered document.</param> public static void UpdateCaption(IServiceProvider site, string caption, IntPtr docData) { Utilities.ArgumentNotNull("site", site); if (string.IsNullOrEmpty(caption)) { throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty), "caption"); } var uiShell = site.GetService(typeof(SVsUIShell)) as IVsUIShell; // We need to tell the windows to update their captions. IEnumWindowFrames windowFramesEnum; ErrorHandler.ThrowOnFailure(uiShell.GetDocumentWindowEnum(out windowFramesEnum)); var windowFrames = new IVsWindowFrame[1]; uint fetched; while (windowFramesEnum.Next(1, windowFrames, out fetched) == VSConstants.S_OK && fetched == 1) { var windowFrame = windowFrames[0]; object data; ErrorHandler.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out data)); var ptr = Marshal.GetIUnknownForObject(data); try { if (ptr == docData) { ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID.VSFPROPID_OwnerCaption, caption)); } } finally { if (ptr != IntPtr.Zero) { Marshal.Release(ptr); } } } } /// <summary> /// Rename document in the running document table from oldName to newName. /// </summary> /// <param name="provider">The service provider.</param> /// <param name="oldName">Full path to the old name of the document.</param> /// <param name="newName">Full path to the new name of the document.</param> /// <param name="newItemId">The new item id of the document</param> public static void RenameDocument(IServiceProvider site, string oldName, string newName, uint newItemId) { Utilities.ArgumentNotNull("site", site); if (string.IsNullOrEmpty(oldName)) { throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty), "oldName"); } if (string.IsNullOrEmpty(newName)) { throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty), "newName"); } if (newItemId == VSConstants.VSITEMID_NIL) { throw new ArgumentNullException("newItemId"); } var pRDT = site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (pRDT == null) return; IVsHierarchy pIVsHierarchy; uint itemId; IntPtr docData; uint uiVsDocCookie; ErrorHandler.ThrowOnFailure(pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, oldName, out pIVsHierarchy, out itemId, out docData, out uiVsDocCookie)); if (docData != IntPtr.Zero && pIVsHierarchy != null) { try { var pUnk = Marshal.GetIUnknownForObject(pIVsHierarchy); var iid = typeof(IVsHierarchy).GUID; IntPtr pHier; Marshal.QueryInterface(pUnk, ref iid, out pHier); try { ErrorHandler.ThrowOnFailure(pRDT.RenameDocument(oldName, newName, pHier, newItemId)); } finally { if (pHier != IntPtr.Zero) Marshal.Release(pHier); if (pUnk != IntPtr.Zero) Marshal.Release(pUnk); } } finally { Marshal.Release(docData); } } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using System.Reflection.Internal; namespace System.Reflection.Metadata.Ecma335 { internal struct StringStreamReader { private static string[] s_virtualValues; internal readonly MemoryBlock Block; internal StringStreamReader(MemoryBlock block, MetadataKind metadataKind) { if (s_virtualValues == null && metadataKind != MetadataKind.Ecma335) { // Note: // Virtual values shall not contain surrogates, otherwise StartsWith might be inconsistent // when comparing to a text that ends with a high surrogate. var values = new string[(int)StringHandle.VirtualIndex.Count]; values[(int)StringHandle.VirtualIndex.System_Runtime_WindowsRuntime] = "System.Runtime.WindowsRuntime"; values[(int)StringHandle.VirtualIndex.System_Runtime] = "System.Runtime"; values[(int)StringHandle.VirtualIndex.System_ObjectModel] = "System.ObjectModel"; values[(int)StringHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml] = "System.Runtime.WindowsRuntime.UI.Xaml"; values[(int)StringHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime] = "System.Runtime.InteropServices.WindowsRuntime"; values[(int)StringHandle.VirtualIndex.System_Numerics_Vectors] = "System.Numerics.Vectors"; values[(int)StringHandle.VirtualIndex.Dispose] = "Dispose"; values[(int)StringHandle.VirtualIndex.AttributeTargets] = "AttributeTargets"; values[(int)StringHandle.VirtualIndex.AttributeUsageAttribute] = "AttributeUsageAttribute"; values[(int)StringHandle.VirtualIndex.Color] = "Color"; values[(int)StringHandle.VirtualIndex.CornerRadius] = "CornerRadius"; values[(int)StringHandle.VirtualIndex.DateTimeOffset] = "DateTimeOffset"; values[(int)StringHandle.VirtualIndex.Duration] = "Duration"; values[(int)StringHandle.VirtualIndex.DurationType] = "DurationType"; values[(int)StringHandle.VirtualIndex.EventHandler1] = "EventHandler`1"; values[(int)StringHandle.VirtualIndex.EventRegistrationToken] = "EventRegistrationToken"; values[(int)StringHandle.VirtualIndex.Exception] = "Exception"; values[(int)StringHandle.VirtualIndex.GeneratorPosition] = "GeneratorPosition"; values[(int)StringHandle.VirtualIndex.GridLength] = "GridLength"; values[(int)StringHandle.VirtualIndex.GridUnitType] = "GridUnitType"; values[(int)StringHandle.VirtualIndex.ICommand] = "ICommand"; values[(int)StringHandle.VirtualIndex.IDictionary2] = "IDictionary`2"; values[(int)StringHandle.VirtualIndex.IDisposable] = "IDisposable"; values[(int)StringHandle.VirtualIndex.IEnumerable] = "IEnumerable"; values[(int)StringHandle.VirtualIndex.IEnumerable1] = "IEnumerable`1"; values[(int)StringHandle.VirtualIndex.IList] = "IList"; values[(int)StringHandle.VirtualIndex.IList1] = "IList`1"; values[(int)StringHandle.VirtualIndex.INotifyCollectionChanged] = "INotifyCollectionChanged"; values[(int)StringHandle.VirtualIndex.INotifyPropertyChanged] = "INotifyPropertyChanged"; values[(int)StringHandle.VirtualIndex.IReadOnlyDictionary2] = "IReadOnlyDictionary`2"; values[(int)StringHandle.VirtualIndex.IReadOnlyList1] = "IReadOnlyList`1"; values[(int)StringHandle.VirtualIndex.KeyTime] = "KeyTime"; values[(int)StringHandle.VirtualIndex.KeyValuePair2] = "KeyValuePair`2"; values[(int)StringHandle.VirtualIndex.Matrix] = "Matrix"; values[(int)StringHandle.VirtualIndex.Matrix3D] = "Matrix3D"; values[(int)StringHandle.VirtualIndex.Matrix3x2] = "Matrix3x2"; values[(int)StringHandle.VirtualIndex.Matrix4x4] = "Matrix4x4"; values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedAction] = "NotifyCollectionChangedAction"; values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedEventArgs] = "NotifyCollectionChangedEventArgs"; values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedEventHandler] = "NotifyCollectionChangedEventHandler"; values[(int)StringHandle.VirtualIndex.Nullable1] = "Nullable`1"; values[(int)StringHandle.VirtualIndex.Plane] = "Plane"; values[(int)StringHandle.VirtualIndex.Point] = "Point"; values[(int)StringHandle.VirtualIndex.PropertyChangedEventArgs] = "PropertyChangedEventArgs"; values[(int)StringHandle.VirtualIndex.PropertyChangedEventHandler] = "PropertyChangedEventHandler"; values[(int)StringHandle.VirtualIndex.Quaternion] = "Quaternion"; values[(int)StringHandle.VirtualIndex.Rect] = "Rect"; values[(int)StringHandle.VirtualIndex.RepeatBehavior] = "RepeatBehavior"; values[(int)StringHandle.VirtualIndex.RepeatBehaviorType] = "RepeatBehaviorType"; values[(int)StringHandle.VirtualIndex.Size] = "Size"; values[(int)StringHandle.VirtualIndex.System] = "System"; values[(int)StringHandle.VirtualIndex.System_Collections] = "System.Collections"; values[(int)StringHandle.VirtualIndex.System_Collections_Generic] = "System.Collections.Generic"; values[(int)StringHandle.VirtualIndex.System_Collections_Specialized] = "System.Collections.Specialized"; values[(int)StringHandle.VirtualIndex.System_ComponentModel] = "System.ComponentModel"; values[(int)StringHandle.VirtualIndex.System_Numerics] = "System.Numerics"; values[(int)StringHandle.VirtualIndex.System_Windows_Input] = "System.Windows.Input"; values[(int)StringHandle.VirtualIndex.Thickness] = "Thickness"; values[(int)StringHandle.VirtualIndex.TimeSpan] = "TimeSpan"; values[(int)StringHandle.VirtualIndex.Type] = "Type"; values[(int)StringHandle.VirtualIndex.Uri] = "Uri"; values[(int)StringHandle.VirtualIndex.Vector2] = "Vector2"; values[(int)StringHandle.VirtualIndex.Vector3] = "Vector3"; values[(int)StringHandle.VirtualIndex.Vector4] = "Vector4"; values[(int)StringHandle.VirtualIndex.Windows_Foundation] = "Windows.Foundation"; values[(int)StringHandle.VirtualIndex.Windows_UI] = "Windows.UI"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml] = "Windows.UI.Xaml"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Controls_Primitives] = "Windows.UI.Xaml.Controls.Primitives"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media] = "Windows.UI.Xaml.Media"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation] = "Windows.UI.Xaml.Media.Animation"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Media3D] = "Windows.UI.Xaml.Media.Media3D"; s_virtualValues = values; AssertFilled(); } this.Block = TrimEnd(block); } [Conditional("DEBUG")] private static void AssertFilled() { for (int i = 0; i < s_virtualValues.Length; i++) { Debug.Assert(s_virtualValues[i] != null, "Missing virtual value for StringHandle.VirtualIndex." + (StringHandle.VirtualIndex)i); } } // Trims the alignment padding of the heap. // See StgStringPool::InitOnMem in ndp\clr\src\Utilcode\StgPool.cpp. // This is especially important for EnC. private static MemoryBlock TrimEnd(MemoryBlock block) { if (block.Length == 0) { return block; } int i = block.Length - 1; while (i >= 0 && block.PeekByte(i) == 0) { i--; } // this shouldn't happen in valid metadata: if (i == block.Length - 1) { return block; } // +1 for terminating \0 return block.GetMemoryBlockAt(0, i + 2); } internal string GetVirtualValue(StringHandle.VirtualIndex index) { return s_virtualValues[(int)index]; } internal string GetString(StringHandle handle, MetadataStringDecoder utf8Decoder) { byte[] prefix; if (handle.IsVirtual) { switch (handle.StringKind) { case StringKind.Virtual: return s_virtualValues[(int)handle.GetVirtualIndex()]; case StringKind.WinRTPrefixed: prefix = MetadataReader.WinRTPrefix; break; default: Debug.Assert(false, "We should not get here"); return null; } } else { prefix = null; } int bytesRead; char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0'; return this.Block.PeekUtf8NullTerminated(handle.GetHeapOffset(), prefix, utf8Decoder, out bytesRead, otherTerminator); } internal StringHandle GetNextHandle(StringHandle handle) { if (handle.IsVirtual) { return default(StringHandle); } int terminator = this.Block.IndexOf(0, handle.GetHeapOffset()); if (terminator == -1 || terminator == Block.Length - 1) { return default(StringHandle); } return StringHandle.FromOffset(terminator + 1); } internal bool Equals(StringHandle handle, string value, MetadataStringDecoder utf8Decoder, bool ignoreCase) { Debug.Assert(value != null); if (handle.IsVirtual) { // TODO: This can allocate unnecessarily for <WinRT> prefixed handles. return string.Equals(GetString(handle, utf8Decoder), value, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } if (handle.IsNil) { return value.Length == 0; } char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0'; return this.Block.Utf8NullTerminatedEquals(handle.GetHeapOffset(), value, utf8Decoder, otherTerminator, ignoreCase); } internal bool StartsWith(StringHandle handle, string value, MetadataStringDecoder utf8Decoder, bool ignoreCase) { Debug.Assert(value != null); if (handle.IsVirtual) { // TODO: This can allocate unnecessarily for <WinRT> prefixed handles. return GetString(handle, utf8Decoder).StartsWith(value, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } if (handle.IsNil) { return value.Length == 0; } char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0'; return this.Block.Utf8NullTerminatedStartsWith(handle.GetHeapOffset(), value, utf8Decoder, otherTerminator, ignoreCase); } /// <summary> /// Returns true if the given raw (non-virtual) handle represents the same string as given ASCII string. /// </summary> internal bool EqualsRaw(StringHandle rawHandle, string asciiString) { Debug.Assert(!rawHandle.IsVirtual); Debug.Assert(rawHandle.StringKind != StringKind.DotTerminated, "Not supported"); return this.Block.CompareUtf8NullTerminatedStringWithAsciiString(rawHandle.GetHeapOffset(), asciiString) == 0; } /// <summary> /// Returns the heap index of the given ASCII character or -1 if not found prior null terminator or end of heap. /// </summary> internal int IndexOfRaw(int startIndex, char asciiChar) { Debug.Assert(asciiChar != 0 && asciiChar <= 0x7f); return this.Block.Utf8NullTerminatedOffsetOfAsciiChar(startIndex, asciiChar); } /// <summary> /// Returns true if the given raw (non-virtual) handle represents a string that starts with given ASCII prefix. /// </summary> internal bool StartsWithRaw(StringHandle rawHandle, string asciiPrefix) { Debug.Assert(!rawHandle.IsVirtual); Debug.Assert(rawHandle.StringKind != StringKind.DotTerminated, "Not supported"); return this.Block.Utf8NullTerminatedStringStartsWithAsciiPrefix(rawHandle.GetHeapOffset(), asciiPrefix); } /// <summary> /// Equivalent to Array.BinarySearch, searches for given raw (non-virtual) handle in given array of ASCII strings. /// </summary> internal int BinarySearchRaw(string[] asciiKeys, StringHandle rawHandle) { Debug.Assert(!rawHandle.IsVirtual); Debug.Assert(rawHandle.StringKind != StringKind.DotTerminated, "Not supported"); return this.Block.BinarySearch(asciiKeys, rawHandle.GetHeapOffset()); } } internal unsafe struct BlobStreamReader { private struct VirtualHeapBlob { public readonly GCHandle Pinned; public readonly byte[] Array; public VirtualHeapBlob(byte[] array) { Pinned = GCHandle.Alloc(array, GCHandleType.Pinned); Array = array; } } // Container for virtual heap blobs that unpins handles on finalization. // This is not handled via dispose because the only resource is managed memory. private sealed class VirtualHeapBlobTable { public readonly Dictionary<BlobHandle, VirtualHeapBlob> Table; public VirtualHeapBlobTable() { Table = new Dictionary<BlobHandle, VirtualHeapBlob>(); } ~VirtualHeapBlobTable() { if (Table != null) { foreach (var blob in Table.Values) { blob.Pinned.Free(); } } } } // Since the number of virtual blobs we need is small (the number of attribute classes in .winmd files) // we can create a pinned handle for each of them. // If we needed many more blobs we could create and pin a single byte[] and allocate blobs there. private VirtualHeapBlobTable _lazyVirtualHeapBlobs; private static byte[][] s_virtualHeapBlobs; internal readonly MemoryBlock Block; internal BlobStreamReader(MemoryBlock block, MetadataKind metadataKind) { _lazyVirtualHeapBlobs = null; this.Block = block; if (s_virtualHeapBlobs == null && metadataKind != MetadataKind.Ecma335) { var blobs = new byte[(int)BlobHandle.VirtualIndex.Count][]; blobs[(int)BlobHandle.VirtualIndex.ContractPublicKeyToken] = new byte[] { 0xB0, 0x3F, 0x5F, 0x7F, 0x11, 0xD5, 0x0A, 0x3A }; blobs[(int)BlobHandle.VirtualIndex.ContractPublicKey] = new byte[] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x07, 0xD1, 0xFA, 0x57, 0xC4, 0xAE, 0xD9, 0xF0, 0xA3, 0x2E, 0x84, 0xAA, 0x0F, 0xAE, 0xFD, 0x0D, 0xE9, 0xE8, 0xFD, 0x6A, 0xEC, 0x8F, 0x87, 0xFB, 0x03, 0x76, 0x6C, 0x83, 0x4C, 0x99, 0x92, 0x1E, 0xB2, 0x3B, 0xE7, 0x9A, 0xD9, 0xD5, 0xDC, 0xC1, 0xDD, 0x9A, 0xD2, 0x36, 0x13, 0x21, 0x02, 0x90, 0x0B, 0x72, 0x3C, 0xF9, 0x80, 0x95, 0x7F, 0xC4, 0xE1, 0x77, 0x10, 0x8F, 0xC6, 0x07, 0x77, 0x4F, 0x29, 0xE8, 0x32, 0x0E, 0x92, 0xEA, 0x05, 0xEC, 0xE4, 0xE8, 0x21, 0xC0, 0xA5, 0xEF, 0xE8, 0xF1, 0x64, 0x5C, 0x4C, 0x0C, 0x93, 0xC1, 0xAB, 0x99, 0x28, 0x5D, 0x62, 0x2C, 0xAA, 0x65, 0x2C, 0x1D, 0xFA, 0xD6, 0x3D, 0x74, 0x5D, 0x6F, 0x2D, 0xE5, 0xF1, 0x7E, 0x5E, 0xAF, 0x0F, 0xC4, 0x96, 0x3D, 0x26, 0x1C, 0x8A, 0x12, 0x43, 0x65, 0x18, 0x20, 0x6D, 0xC0, 0x93, 0x34, 0x4D, 0x5A, 0xD2, 0x93 }; blobs[(int)BlobHandle.VirtualIndex.AttributeUsage_AllowSingle] = new byte[] { // preamble: 0x01, 0x00, // target (template parameter): 0x00, 0x00, 0x00, 0x00, // named arg count: 0x01, 0x00, // SERIALIZATION_TYPE_PROPERTY 0x54, // ELEMENT_TYPE_BOOLEAN 0x02, // "AllowMultiple".Length 0x0D, // "AllowMultiple" 0x41, 0x6C, 0x6C, 0x6F, 0x77, 0x4D, 0x75, 0x6C, 0x74, 0x69, 0x70, 0x6C, 0x65, // false 0x00 }; blobs[(int)BlobHandle.VirtualIndex.AttributeUsage_AllowMultiple] = new byte[] { // preamble: 0x01, 0x00, // target (template parameter): 0x00, 0x00, 0x00, 0x00, // named arg count: 0x01, 0x00, // SERIALIZATION_TYPE_PROPERTY 0x54, // ELEMENT_TYPE_BOOLEAN 0x02, // "AllowMultiple".Length 0x0D, // "AllowMultiple" 0x41, 0x6C, 0x6C, 0x6F, 0x77, 0x4D, 0x75, 0x6C, 0x74, 0x69, 0x70, 0x6C, 0x65, // true 0x01 }; s_virtualHeapBlobs = blobs; } } internal byte[] GetBytes(BlobHandle handle) { if (handle.IsVirtual) { // consider: if we returned an ImmutableArray we wouldn't need to copy return GetVirtualBlobArray(handle, unique: true); } int offset = handle.GetHeapOffset(); int bytesRead; int numberOfBytes = this.Block.PeekCompressedInteger(offset, out bytesRead); if (numberOfBytes == BlobReader.InvalidCompressedInteger) { return EmptyArray<byte>.Instance; } return this.Block.PeekBytes(offset + bytesRead, numberOfBytes); } internal MemoryBlock GetMemoryBlock(BlobHandle handle) { if (handle.IsVirtual) { if (_lazyVirtualHeapBlobs == null) { Interlocked.CompareExchange(ref _lazyVirtualHeapBlobs, new VirtualHeapBlobTable(), null); } int index = (int)handle.GetVirtualIndex(); int length = s_virtualHeapBlobs[index].Length; VirtualHeapBlob virtualBlob; lock (_lazyVirtualHeapBlobs) { if (!_lazyVirtualHeapBlobs.Table.TryGetValue(handle, out virtualBlob)) { virtualBlob = new VirtualHeapBlob(GetVirtualBlobArray(handle, unique: false)); _lazyVirtualHeapBlobs.Table.Add(handle, virtualBlob); } } return new MemoryBlock((byte*)virtualBlob.Pinned.AddrOfPinnedObject(), length); } int offset, size; Block.PeekHeapValueOffsetAndSize(handle.GetHeapOffset(), out offset, out size); return this.Block.GetMemoryBlockAt(offset, size); } internal BlobReader GetBlobReader(BlobHandle handle) { return new BlobReader(GetMemoryBlock(handle)); } internal BlobHandle GetNextHandle(BlobHandle handle) { if (handle.IsVirtual) { return default(BlobHandle); } int offset, size; if (!Block.PeekHeapValueOffsetAndSize(handle.GetHeapOffset(), out offset, out size)) { return default(BlobHandle); } int nextIndex = offset + size; if (nextIndex >= Block.Length) { return default(BlobHandle); } return BlobHandle.FromOffset(nextIndex); } internal byte[] GetVirtualBlobArray(BlobHandle handle, bool unique) { BlobHandle.VirtualIndex index = handle.GetVirtualIndex(); byte[] result = s_virtualHeapBlobs[(int)index]; switch (index) { case BlobHandle.VirtualIndex.AttributeUsage_AllowMultiple: case BlobHandle.VirtualIndex.AttributeUsage_AllowSingle: result = (byte[])result.Clone(); handle.SubstituteTemplateParameters(result); break; default: if (unique) { result = (byte[])result.Clone(); } break; } return result; } public string GetDocumentName(DocumentNameBlobHandle handle) { var blobReader = GetBlobReader(handle); // Spec: separator is an ASCII encoded character in range [0x01, 0x7F], or byte 0 to represent an empty separator. int separator = blobReader.ReadByte(); if (separator > 0x7f) { throw new BadImageFormatException(string.Format(SR.InvalidDocumentName, separator)); } var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; bool isFirstPart = true; while (blobReader.RemainingBytes > 0) { if (separator != 0 && !isFirstPart) { builder.Append((char)separator); } var partReader = GetBlobReader(blobReader.ReadBlobHandle()); // TODO: avoid allocating temp string (https://github.com/dotnet/corefx/issues/2102) builder.Append(partReader.ReadUTF8(partReader.Length)); isFirstPart = false; } return pooledBuilder.ToStringAndFree(); } internal bool DocumentNameEquals(DocumentNameBlobHandle handle, string other, bool ignoreCase) { var blobReader = GetBlobReader(handle); // Spec: separator is an ASCII encoded character in range [0x01, 0x7F], or byte 0 to represent an empty separator. int separator = blobReader.ReadByte(); if (separator > 0x7f) { return false; } int ignoreCaseMask = StringUtils.IgnoreCaseMask(ignoreCase); int otherIndex = 0; bool isFirstPart = true; while (blobReader.RemainingBytes > 0) { if (separator != 0 && !isFirstPart) { if (otherIndex == other.Length || !StringUtils.IsEqualAscii(other[otherIndex], separator, ignoreCaseMask)) { return false; } otherIndex++; } var partBlock = GetMemoryBlock(blobReader.ReadBlobHandle()); int firstDifferenceIndex; var result = partBlock.Utf8NullTerminatedFastCompare(0, other, otherIndex, out firstDifferenceIndex, terminator: '\0', ignoreCase: ignoreCase); if (result == MemoryBlock.FastComparisonResult.Inconclusive) { return GetDocumentName(handle).Equals(other, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } if (result == MemoryBlock.FastComparisonResult.Unequal || firstDifferenceIndex - otherIndex != partBlock.Length) { return false; } otherIndex = firstDifferenceIndex; isFirstPart = false; } return otherIndex == other.Length; } } internal struct GuidStreamReader { internal readonly MemoryBlock Block; public GuidStreamReader(MemoryBlock block) { this.Block = block; } internal Guid GetGuid(GuidHandle handle) { if (handle.IsNil) { return default(Guid); } // Metadata Spec: The Guid heap is an array of GUIDs, each 16 bytes wide. // Its first element is numbered 1, its second 2, and so on. return this.Block.PeekGuid((handle.Index - 1) * BlobUtilities.SizeOfGuid); } } internal struct UserStringStreamReader { internal readonly MemoryBlock Block; public UserStringStreamReader(MemoryBlock block) { this.Block = block; } internal string GetString(UserStringHandle handle) { int offset, size; if (!Block.PeekHeapValueOffsetAndSize(handle.GetHeapOffset(), out offset, out size)) { return string.Empty; } // Spec: Furthermore, there is an additional terminal byte (so all byte counts are odd, not even). // The size in the blob header is the length of the string in bytes + 1. return this.Block.PeekUtf16(offset, size & ~1); } internal UserStringHandle GetNextHandle(UserStringHandle handle) { int offset, size; if (!Block.PeekHeapValueOffsetAndSize(handle.GetHeapOffset(), out offset, out size)) { return default(UserStringHandle); } int nextIndex = offset + size; if (nextIndex >= Block.Length) { return default(UserStringHandle); } return UserStringHandle.FromOffset(nextIndex); } } }
using System; using Android.Util; using Android.Views.Animations; using Android.Widget; using Android.Views; using Android.Graphics; using Android.Content; using Java.Lang.Ref; namespace ManneDoForms.Droid.Common.PhotoViewDroid { public class PhotoViewDroidAttacher:Java.Lang.Object,IPhotoViewDroid,Android.Views.View.IOnTouchListener,IOnGestureListener,Android.Views.ViewTreeObserver.IOnGlobalLayoutListener { public static readonly String LOG_TAG = "PhotoViewAttacher"; // let debug flag be dynamic, but still Proguard can be used to remove from // release builds private readonly bool DEBUG = Log.IsLoggable(LOG_TAG,LogPriority.Debug); static readonly Android.Views.Animations.IInterpolator sInterpolator = new AccelerateDecelerateInterpolator(); int ZOOM_DURATION = IPhotoViewDroidConstants.DEFAULT_ZOOM_DURATION; static readonly int EDGE_NONE = -1; static readonly int EDGE_LEFT = 0; static readonly int EDGE_RIGHT = 1; static readonly int EDGE_BOTH = 2; private float mMinScale = IPhotoViewDroidConstants.DEFAULT_MIN_SCALE; private float mMidScale = IPhotoViewDroidConstants.DEFAULT_MID_SCALE; private float mMaxScale = IPhotoViewDroidConstants.DEFAULT_MAX_SCALE; private bool mAllowParentInterceptOnEdge = true; private static void CheckZoomLevels(float minZoom, float midZoom, float maxZoom) { if (minZoom >= midZoom) { throw new Java.Lang.IllegalArgumentException( "MinZoom has to be less than MidZoom"); } else if (midZoom >= maxZoom) { throw new Java.Lang.IllegalArgumentException( "MidZoom has to be less than MaxZoom"); } } private static bool HasDrawable(ImageView imageView) { return null != imageView && null != imageView.Drawable; } private static bool IsSupportedScaleType( Android.Widget.ImageView.ScaleType scaleType) { if (null == scaleType) { return false; } if (scaleType.Name().Equals(Android.Widget.ImageView.ScaleType.Matrix.Name())) { throw new Java.Lang.IllegalArgumentException(scaleType.Name() + " is not supported in PhotoView"); } else { return true; } } private static void SetImageViewScaleTypeMatrix(ImageView imageView) { if (null != imageView && !(imageView is IPhotoViewDroid)) { if (!Android.Widget.ImageView.ScaleType.Matrix.Name().Equals(imageView.GetScaleType().Name())) { imageView.SetScaleType(Android.Widget.ImageView.ScaleType.Matrix); } } } private Java.Lang.Ref.WeakReference mImageView; // Gesture Detectors private GestureDetector mGestureDetector; private IGestureDetector mScaleDragDetector; // These are set so we don't keep allocating them on the heap private readonly Matrix mBaseMatrix = new Matrix(); private readonly Matrix mDrawMatrix = new Matrix(); private readonly Matrix mSuppMatrix = new Matrix(); private readonly RectF mDisplayRect = new RectF(); private readonly float[] mMatrixValues = new float[9]; // Listeners private IOnMatrixChangedListener mMatrixChangeListener; private IOnPhotoTapListener mPhotoTapListener; private IOnViewTapListener mViewTapListener; private Android.Views.View.IOnLongClickListener mLongClickListener; private int mIvTop, mIvRight, mIvBottom, mIvLeft; private FlingRunnable mCurrentFlingRunnable; private int mScrollEdge = EDGE_BOTH; private bool mZoomEnabled; private Android.Widget.ImageView.ScaleType mScaleType = Android.Widget.ImageView.ScaleType.FitCenter; public PhotoViewDroidAttacher(ImageView imageView) { mImageView = new Java.Lang.Ref.WeakReference(imageView); imageView.DrawingCacheEnabled = true; imageView.SetOnTouchListener (this); ViewTreeObserver observer = imageView.ViewTreeObserver; if (null != observer) observer.AddOnGlobalLayoutListener(this); // Make sure we using MATRIX Scale Type SetImageViewScaleTypeMatrix (imageView); if (imageView.IsInEditMode) { return; } // Create Gesture Detectors... mScaleDragDetector = VersionedGestureDetector.NewInstance( imageView.Context, this); mGestureDetector = new GestureDetector (imageView.Context, new MSimpleOnGestureListener (this)); mGestureDetector.SetOnDoubleTapListener (new DefaultOnDoubleTapListener (this)); SetZoomable (true); } public void Cleanup() { if (null == mImageView) { return; // cleanup already done } ImageView imageView = (ImageView)(((Reference)mImageView).Get()); if (null != imageView) { // Remove this as a global layout listener ViewTreeObserver observer = imageView.ViewTreeObserver; if (null != observer && observer.IsAlive) { observer.RemoveGlobalOnLayoutListener(this); } // Remove the ImageView's reference to this imageView.SetOnTouchListener(null); // make sure a pending fling runnable won't be run CancelFling(); } if (null != mGestureDetector) { mGestureDetector.SetOnDoubleTapListener(null); } // Clear listeners too mMatrixChangeListener = null; mPhotoTapListener = null; mViewTapListener = null; // Finally, clear ImageView mImageView = null; } #region LATER WORK public ImageView GetImageView () { ImageView imageView = null; if (null != mImageView) { imageView = (ImageView)mImageView.Get(); } // If we don't have an ImageView, call cleanup() if (null == imageView) { Cleanup(); Log.Info(LOG_TAG, "ImageView no longer exists. You should not use this PhotoViewAttacher any more."); } return imageView; } public void SetImageViewMatrix(Matrix matrix) { ImageView imageView = GetImageView(); if (null != imageView) { CheckImageViewScaleType(); imageView.ImageMatrix=(matrix); // Call MatrixChangedListener if needed if (null != mMatrixChangeListener) { RectF displayRect = GetDisplayRect(matrix); if (null != displayRect) { mMatrixChangeListener.OnMatrixChanged(displayRect); } } } } public Matrix GetDrawMatrix() { mDrawMatrix.Set(mBaseMatrix); mDrawMatrix.PostConcat(mSuppMatrix); return mDrawMatrix; } private void CancelFling() { if (null != mCurrentFlingRunnable) { mCurrentFlingRunnable.CancelFling(); mCurrentFlingRunnable = null; } } private bool CheckMatrixBounds() { ImageView imageView = GetImageView(); if (null == imageView) { return false; } RectF rect = GetDisplayRect(GetDrawMatrix()); if (null == rect) { return false; } float height = rect.Height(), width = rect.Width(); float deltaX = 0, deltaY = 0; int viewHeight = GetImageViewHeight(imageView); if (height <= viewHeight) { if (mScaleType.Name ().Equals (ImageView.ScaleType.FitStart.Name ())) { deltaY = -rect.Top; } else if (ImageView.ScaleType.FitEnd.Equals (mScaleType.Name ())) { deltaY = viewHeight - height - rect.Top; } else{ deltaY = (viewHeight - height) / 2 - rect.Top; } } else if (rect.Top > 0) { deltaY = -rect.Top; } else if (rect.Bottom < viewHeight) { deltaY = viewHeight - rect.Bottom; } int viewWidth = GetImageViewWidth(imageView); if (width <= viewWidth) { if (mScaleType.Name().Equals(ImageView.ScaleType.FitStart.Name())) { deltaX = -rect.Left; } else if (mScaleType.Name().Equals(ImageView.ScaleType.FitEnd.Name())) { deltaX = viewWidth - width - rect.Left; } else { deltaX = (viewWidth - width) / 2 - rect.Left; } mScrollEdge = EDGE_BOTH; } else if (rect.Left > 0) { mScrollEdge = EDGE_LEFT; deltaX = -rect.Left; } else if (rect.Right < viewWidth) { deltaX = viewWidth - rect.Right; mScrollEdge = EDGE_RIGHT; } else { mScrollEdge = EDGE_NONE; } // Finally actually translate the matrix mSuppMatrix.PostTranslate(deltaX, deltaY); return true; } private RectF GetDisplayRect(Matrix matrix) { ImageView imageView = GetImageView(); if (null != imageView) { Android.Graphics.Drawables.Drawable d = imageView.Drawable; if (null != d) { mDisplayRect.Set(0, 0, d.IntrinsicWidth, d.IntrinsicHeight); matrix.MapRect(mDisplayRect); return mDisplayRect; } } return null; } private void CheckAndDisplayMatrix() { if (CheckMatrixBounds()) { SetImageViewMatrix(GetDrawMatrix()); } } private float GetValue(Matrix matrix, int whichValue) { matrix.GetValues(mMatrixValues); return mMatrixValues[whichValue]; } private int GetImageViewWidth(ImageView imageView) { if (null == imageView) return 0; return imageView.Width - imageView.PaddingLeft - imageView.PaddingRight; } private int GetImageViewHeight(ImageView imageView) { if (null == imageView) return 0; return imageView.Height - imageView.PaddingTop - imageView.PaddingBottom; } private void UpdateBaseMatrix(Android.Graphics.Drawables.Drawable d) { ImageView imageView = GetImageView (); if (null == imageView || null == d) { return; } float viewWidth = GetImageViewWidth (imageView); float viewHeight = GetImageViewHeight (imageView); int drawableWidth = d.IntrinsicWidth; int drawableHeight = d.IntrinsicHeight; mBaseMatrix.Reset (); float widthScale = viewWidth / drawableWidth; float heightScale = viewHeight / drawableHeight; if (mScaleType == Android.Widget.ImageView.ScaleType.Center) { mBaseMatrix.PostTranslate ((viewWidth - drawableWidth) / 2F, (viewHeight - drawableHeight) / 2F); } else if (mScaleType == Android.Widget.ImageView.ScaleType.CenterCrop) { float scale = Math.Max (widthScale, heightScale); mBaseMatrix.PostScale (scale, scale); mBaseMatrix.PostTranslate ((viewWidth - drawableWidth * scale) / 2F, (viewHeight - drawableHeight * scale) / 2F); } else if (mScaleType == Android.Widget.ImageView.ScaleType.CenterInside) { float scale = Math.Min (1.0f, Math.Min (widthScale, heightScale)); mBaseMatrix.PostScale (scale, scale); mBaseMatrix.PostTranslate ((viewWidth - drawableWidth * scale) / 2F, (viewHeight - drawableHeight * scale) / 2F); } else { RectF mTempSrc = new RectF (0, 0, drawableWidth, drawableHeight); RectF mTempDst = new RectF (0, 0, viewWidth, viewHeight); if (mScaleType.Name ().Equals (ImageView.ScaleType.FitCenter.Name ())) { mBaseMatrix.SetRectToRect (mTempSrc, mTempDst, Matrix.ScaleToFit.Center); } else if (mScaleType.Name ().Equals (ImageView.ScaleType.FitStart.Name ())) { mBaseMatrix.SetRectToRect (mTempSrc, mTempDst, Matrix.ScaleToFit.Start); } else if (mScaleType.Name().Equals (ImageView.ScaleType.FitEnd.Name())) mBaseMatrix.SetRectToRect (mTempSrc, mTempDst, Matrix.ScaleToFit.End); else if (mScaleType.Name ().Equals (ImageView.ScaleType.FitXy.Name ())) mBaseMatrix.SetRectToRect (mTempSrc, mTempDst, Matrix.ScaleToFit.Fill); } ResetMatrix (); } private void ResetMatrix() { mSuppMatrix.Reset(); SetImageViewMatrix(GetDrawMatrix()); CheckMatrixBounds(); } public void Update() { ImageView imageView = GetImageView(); if (null != imageView) { if (mZoomEnabled) { // Make sure we using MATRIX Scale Type SetImageViewScaleTypeMatrix(imageView); // Update the base matrix using the current drawable UpdateBaseMatrix(imageView.Drawable); } else { // Reset the Matrix... ResetMatrix(); } } } private void CheckImageViewScaleType() { ImageView imageView = GetImageView(); /** * PhotoView's getScaleType() will just divert to this.getScaleType() so * only call if we're not attached to a PhotoView. */ if (null != imageView && !(imageView is IPhotoViewDroid)) { if (!Android.Widget.ImageView.ScaleType.Matrix.Name().Equals(imageView.GetScaleType().Name())) { throw new Java.Lang.IllegalStateException( "The ImageView's ScaleType has been changed since attaching a PhotoViewAttacher"); } } } #endregion #region IPhotoView implementation public bool CanZoom () { return mZoomEnabled; } public RectF GetDisplayRect () { CheckMatrixBounds(); return GetDisplayRect(GetDrawMatrix()); } public bool SetDisplayMatrix (Matrix finalMatrix) { if (finalMatrix == null) throw new Java.Lang.IllegalArgumentException("Matrix cannot be null"); ImageView imageView = GetImageView(); if (null == imageView) return false; if (null == imageView.Drawable) return false; mSuppMatrix.Set(finalMatrix); SetImageViewMatrix(GetDrawMatrix()); CheckMatrixBounds(); return true; } public Matrix GetDisplayMatrix () { return new Matrix(GetDrawMatrix()); } public float GetMinScale () { return GetMinimumScale(); } public float GetMinimumScale () { return mMinScale; } public float GetMidScale () { return GetMediumScale(); } public float GetMediumScale () { return mMidScale; } public float GetMaxScale () { return GetMaximumScale(); } public float GetMaximumScale () { return mMaxScale; } public float GetScale () { return FloatMath.Sqrt((float) Math.Pow(GetValue(mSuppMatrix, Matrix.MscaleX), 2) + (float) Math.Pow(GetValue(mSuppMatrix, Matrix.MskewY), 2)); } public ImageView.ScaleType GetScaleType () { return mScaleType; } public void SetAllowParentInterceptOnEdge (bool allow) { mAllowParentInterceptOnEdge = allow; } public void SetMinScale (float minScale) { SetMinimumScale(minScale); } public void SetMinimumScale (float minimumScale) { CheckZoomLevels(minimumScale, mMidScale, mMaxScale); mMinScale = minimumScale; } public void SetMidScale (float midScale) { SetMediumScale(midScale); } public void SetMediumScale (float mediumScale) { CheckZoomLevels(mMinScale, mediumScale, mMaxScale); mMidScale = mediumScale; } public void SetMaxScale (float maxScale) { SetMaximumScale(maxScale); } public void SetMaximumScale (float maximumScale) { CheckZoomLevels(mMinScale, mMidScale, maximumScale); mMaxScale = maximumScale; } public void SetOnLongClickListener (View.IOnLongClickListener listener) { mLongClickListener = listener; } public void SetRotationTo (float degrees) { mSuppMatrix.SetRotate(degrees % 360); CheckAndDisplayMatrix(); } public void SetRotationBy (float degrees) { mSuppMatrix.PostRotate(degrees % 360); CheckAndDisplayMatrix(); } public void SetScale (float scale) { SetScale(scale, false); } public void SetScale (float scale, bool animate) { ImageView imageView = GetImageView(); if (null != imageView) { SetScale(scale, (imageView.Right) / 2, (imageView.Bottom) / 2, animate); } } public void SetScale (float scale, float focalX, float focalY, bool animate) { ImageView imageView = GetImageView(); if (null != imageView) { // Check to see if the scale is within bounds if (scale < mMinScale || scale > mMaxScale) { LogManager .GetLogger() .i(LOG_TAG, "Scale must be within the range of minScale and maxScale"); return; } if (animate) { imageView.Post(new AnimatedZoomRunnable(this,GetScale(), scale, focalX, focalY)); } else { mSuppMatrix.SetScale(scale, scale, focalX, focalY); CheckAndDisplayMatrix(); } } } public void SetScaleType (ImageView.ScaleType scaleType) { if (IsSupportedScaleType(scaleType) && scaleType != mScaleType) { mScaleType = scaleType; // Finally update Update(); } } public void SetZoomable (bool zoomable) { mZoomEnabled = zoomable; Update(); } public void SetPhotoViewRotation (float degrees) { mSuppMatrix.SetRotate(degrees % 360); CheckAndDisplayMatrix(); } public Bitmap GetVisibleRectangleBitmap () { ImageView imageView = GetImageView(); return imageView == null ? null : imageView.DrawingCache; } public void SetZoomTransitionDuration (int milliseconds) { if (milliseconds < 0) milliseconds = IPhotoViewDroidConstants.DEFAULT_ZOOM_DURATION; this.ZOOM_DURATION = milliseconds; } public IPhotoViewDroid GetIPhotoViewImplementation () { return this; } public void SetOnMatrixChangeListener (IOnMatrixChangedListener listener) { mMatrixChangeListener = listener; } public void SetOnPhotoTapListener (IOnPhotoTapListener listener) { mPhotoTapListener = listener; } public IOnPhotoTapListener GetOnPhotoTapListener () { return mPhotoTapListener; } public void SetOnViewTapListener (IOnViewTapListener listener) { mViewTapListener = listener; } public IOnViewTapListener GetOnViewTapListener () { return mViewTapListener; } public void SetOnDoubleTapListener (GestureDetector.IOnDoubleTapListener newOnDoubleTapListener) { if (newOnDoubleTapListener != null) this.mGestureDetector.SetOnDoubleTapListener(newOnDoubleTapListener); else this.mGestureDetector.SetOnDoubleTapListener(new DefaultOnDoubleTapListener(this)); } #endregion public bool OnTouch (View v, MotionEvent ev) { bool handled = false; if (mZoomEnabled && HasDrawable((ImageView) v)) { IViewParent parent = v.Parent; switch (ev.Action) { case MotionEventActions.Down: // First, disable the Parent from intercepting the touch // event if (null != parent) parent.RequestDisallowInterceptTouchEvent(true); else Log.Info(LOG_TAG, "onTouch getParent() returned null"); // If we're flinging, and the user presses down, cancel // fling CancelFling(); break; case MotionEventActions.Cancel: case MotionEventActions.Up: // If the user has zoomed less than min scale, zoom back // to min scale if (GetScale() < mMinScale) { RectF rect = GetDisplayRect(); if (null != rect) { v.Post(new AnimatedZoomRunnable(this,GetScale(), mMinScale, rect.CenterX(), rect.CenterY())); handled = true; } } break; } // Try the Scale/Drag detector if (null != mScaleDragDetector && mScaleDragDetector.OnTouchEvent(ev)) { handled = true; } // Check to see if the user double tapped if (null != mGestureDetector && mGestureDetector.OnTouchEvent(ev)) { handled = true; } } return handled; } #region IOnGestureListener implementation public void OnDrag (float dx, float dy) { if (mScaleDragDetector.IsScaling()) { return; // Do not drag if we are already scaling } if (DEBUG) { LogManager.GetLogger().d(LOG_TAG, Java.Lang.String.Format("onDrag: dx: %.2f. dy: %.2f", dx, dy)); } ImageView imageView = GetImageView(); mSuppMatrix.PostTranslate(dx, dy); CheckAndDisplayMatrix(); IViewParent parent = imageView.Parent; if (mAllowParentInterceptOnEdge && !mScaleDragDetector.IsScaling()) { if (mScrollEdge == EDGE_BOTH || (mScrollEdge == EDGE_LEFT && dx >= 1f) || (mScrollEdge == EDGE_RIGHT && dx <= -1f)) { if (null != parent) parent.RequestDisallowInterceptTouchEvent(false); } } else { if (null != parent) { parent.RequestDisallowInterceptTouchEvent(true); } } } public void OnFling (float startX, float startY, float velocityX, float velocityY) { if (DEBUG) { LogManager.GetLogger().d( LOG_TAG, "onFling. sX: " + startX + " sY: " + startY + " Vx: " + velocityX + " Vy: " + velocityY); } ImageView imageView = GetImageView(); mCurrentFlingRunnable = new FlingRunnable(this,imageView.Context); mCurrentFlingRunnable.Fling(GetImageViewWidth(imageView), GetImageViewHeight(imageView), (int) velocityX, (int) velocityY); imageView.Post(mCurrentFlingRunnable); } public void OnScale (float scaleFactor, float focusX, float focusY) { if (DEBUG) { LogManager.GetLogger().d( LOG_TAG, Java.Lang.String.Format("onScale: scale: %.2f. fX: %.2f. fY: %.2f", scaleFactor, focusX, focusY)); } if (GetScale() < mMaxScale || scaleFactor < 1f) { mSuppMatrix.PostScale(scaleFactor, scaleFactor, focusX, focusY); CheckAndDisplayMatrix(); } } #endregion #region IOnGlobalLayoutListener implementation public void OnGlobalLayout () { ImageView imageView = GetImageView(); if (null != imageView) { if (mZoomEnabled) { int top = imageView.Top; int right = imageView.Right; int bottom = imageView.Bottom; int left = imageView.Left; /** * We need to check whether the ImageView's bounds have changed. * This would be easier if we targeted API 11+ as we could just use * View.OnLayoutChangeListener. Instead we have to replicate the * work, keeping track of the ImageView's bounds and then checking * if the values change. */ if (top != mIvTop || bottom != mIvBottom || left != mIvLeft || right != mIvRight) { // Update our base matrix, as the bounds have changed UpdateBaseMatrix(imageView.Drawable); // Update values as something has changed mIvTop = top; mIvRight = right; mIvBottom = bottom; mIvLeft = left; } } else { UpdateBaseMatrix(imageView.Drawable); } } } #endregion private class FlingRunnable:Java.Lang.Object,Java.Lang.IRunnable { private readonly ScrollerProxy mScroller; private int mCurrentX, mCurrentY; PhotoViewDroidAttacher photoViewAttacher; public FlingRunnable(PhotoViewDroidAttacher photoViewAttacher,Context context) { mScroller = ScrollerProxy.GetScroller(context); this.photoViewAttacher=photoViewAttacher; } public void CancelFling() { if (photoViewAttacher.DEBUG) { LogManager.GetLogger().d("PhotoViewAttacher", "Cancel Fling"); } mScroller.ForceFinished(true); } public void Fling(int viewWidth, int viewHeight, int velocityX, int velocityY) { RectF rect = photoViewAttacher.GetDisplayRect(); if (null == rect) { return; } int startX =(int) Math.Round(-rect.Left); int minX, maxX, minY, maxY; if (viewWidth < rect.Width()) { minX = 0; maxX =(int) Math.Round(rect.Width() - viewWidth); } else { minX = maxX = startX; } int startY =(int) Math.Round(-rect.Top); if (viewHeight < rect.Height()) { minY = 0; maxY =(int) Math.Round(rect.Height() - viewHeight); } else { minY = maxY = startY; } mCurrentX = startX; mCurrentY = startY; if (photoViewAttacher.DEBUG) { LogManager.GetLogger().d( "PhotoViewAttacher", "fling. StartX:" + startX + " StartY:" + startY + " MaxX:" + maxX + " MaxY:" + maxY); } // If we actually can move, fling the scroller if (startX != maxX || startY != maxY) { mScroller.Fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY, 0, 0); } } public void Run () { if (mScroller.IsFinished()) { return; // remaining post that should not be handled } ImageView imageView =photoViewAttacher.GetImageView(); if (null != imageView && mScroller.ComputeScrollOffset ()) { int newX = mScroller.GetCurrX(); int newY = mScroller.GetCurrY(); if (photoViewAttacher.DEBUG) { LogManager.GetLogger().d( LOG_TAG, "fling run(). CurrentX:" + mCurrentX + " CurrentY:" + mCurrentY + " NewX:" + newX + " NewY:" + newY); } photoViewAttacher.mSuppMatrix.PostTranslate(mCurrentX - newX, mCurrentY - newY); photoViewAttacher.SetImageViewMatrix (photoViewAttacher.GetDrawMatrix ()); mCurrentX = newX; mCurrentY = newY; Compat.PostOnAnimation (imageView, this); } } } private class MSimpleOnGestureListener:GestureDetector.SimpleOnGestureListener { PhotoViewDroidAttacher photoViewAttacher; public MSimpleOnGestureListener(PhotoViewDroidAttacher photoViewAttacher) { this.photoViewAttacher=photoViewAttacher; } public override void OnLongPress(MotionEvent e) { if (null != photoViewAttacher.mLongClickListener) { photoViewAttacher.mLongClickListener.OnLongClick(photoViewAttacher.GetImageView()); } } } private class AnimatedZoomRunnable :Java.Lang.Object, Java.Lang.IRunnable { private readonly float mFocalX, mFocalY; private readonly long mStartTime; private readonly float mZoomStart, mZoomEnd; PhotoViewDroidAttacher photoViewAttacher; public AnimatedZoomRunnable(PhotoViewDroidAttacher photoViewAttacher, float currentZoom, float targetZoom, float focalX, float focalY) { this.photoViewAttacher=photoViewAttacher; mFocalX = focalX; mFocalY = focalY; mStartTime =Java.Lang.JavaSystem.CurrentTimeMillis(); mZoomStart = currentZoom; mZoomEnd = targetZoom; } #region IRunnable implementation public void Run () { ImageView imageView =photoViewAttacher.GetImageView(); if (imageView == null) { return; } float t = Interpolate(); float scale = mZoomStart + t * (mZoomEnd - mZoomStart); float deltaScale = scale /photoViewAttacher.GetScale(); photoViewAttacher.mSuppMatrix.PostScale(deltaScale, deltaScale, mFocalX, mFocalY); photoViewAttacher.CheckAndDisplayMatrix(); // We haven't hit our target scale yet, so post ourselves again if (t < 1f) { Compat.PostOnAnimation(imageView, this); } } #endregion private float Interpolate() { float t = 1f * (Java.Lang.JavaSystem.CurrentTimeMillis() - mStartTime) / photoViewAttacher.ZOOM_DURATION; t = Math.Min(1f, t); t = sInterpolator.GetInterpolation(t); return t; } } public interface IOnMatrixChangedListener { /** * Callback for when the Matrix displaying the Drawable has changed. This could be because * the View's bounds have changed, or the user has zoomed. * * @param rect - Rectangle displaying the Drawable's new bounds. */ void OnMatrixChanged(RectF rect); } public interface IOnPhotoTapListener { /** * A callback to receive where the user taps on a photo. You will only receive a callback if * the user taps on the actual photo, tapping on 'whitespace' will be ignored. * * @param view - View the user tapped. * @param x - where the user tapped from the of the Drawable, as percentage of the * Drawable width. * @param y - where the user tapped from the top of the Drawable, as percentage of the * Drawable height. */ void OnPhotoTap(View view, float x, float y); } public interface IOnViewTapListener { /** * A callback to receive where the user taps on a ImageView. You will receive a callback if * the user taps anywhere on the view, tapping on 'whitespace' will not be ignored. * * @param view - View the user tapped. * @param x - where the user tapped from the left of the View. * @param y - where the user tapped from the top of the View. */ void OnViewTap(View view, float x, float y); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Cci; using Microsoft.Tools.Transformer.CodeModel; using ModelFileToCCI2; using System; using System.Collections.Generic; using System.Text; using System.Xml; namespace TrimBin { public class IncludeSet : ModelElement { public IncludeSet() { //_types = new Dictionary<string, TrimType>(); _assemblies = new Dictionary<string, AssemblyElement>(); } public override IDictionary<string, AssemblyElement> Assemblies { get { return _assemblies; } } public void LoadFrom(ModelElement otherModel) { foreach (AssemblyElement assembly in otherModel.Assemblies.Values) { TrimAssembly newAssembly = new TrimAssembly(assembly.Key, assembly.IncludeStatus); _assemblies.Add(newAssembly.Name, newAssembly); foreach (KeyValuePair<String, TypeForwarderElement> typeForwarder in assembly.TypeForwarders) { TrimTypeForwarder newTypeForwarder = new TrimTypeForwarder(typeForwarder.Value.AssemblyName, typeForwarder.Value.TypeName, typeForwarder.Value.IncludeStatus); newAssembly.TypeForwarders.Add(newTypeForwarder.Key, newTypeForwarder); } foreach (KeyValuePair<String, TypeElement> type in assembly.Types) { TrimType newType = new TrimType(type.Value.Key, type.Value.IncludeStatus, type.Value.VisibilityOverride, type.Value.SecurityTransparencyStatus); newAssembly.Types.Add(newType.Key, newType); foreach (KeyValuePair<String, MemberElement> member in type.Value.Members) { TrimMember newMember = new TrimMember(newType, member.Value.Name, member.Value.ReturnType, member.Value.MemberType, member.Value.IncludeStatus, member.Value.VisibilityOverride, member.Value.SecurityTransparencyStatus); newType.Members.Add(newMember.Key, newMember); } } } } public void ReadIncludeFile(String includeFile) { XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreComments = true; settings.IgnoreProcessingInstructions = true; settings.IgnoreWhitespace = true; XmlReader reader = XmlReader.Create(includeFile, settings); ModelReader modelReader = new TrimReader(/*_types*/); modelReader.RecursivelyReadBlock(reader, this, true); } public void AddAssembly(TrimAssembly assembly) { _assemblies.Add(assembly.Key, assembly); } public TrimAssembly GetAssemblyElement(String assemblyName) { AssemblyElement result = null; _assemblies.TryGetValue(assemblyName, out result); return result as TrimAssembly; } public ICollection<AssemblyElement> GetAllAssemblies() { return _assemblies.Values; } private static void MangleTypeNameError(string fqtn) { throw new Exception("error parsing type name: " + fqtn); } private Dictionary<string, AssemblyElement> _assemblies; //private Dictionary<string, TrimType> _types; private const string FIELD_PREFIX = "Field: "; private const string PROPERTY_PREFIX = "Property: "; private const string EVENT_PREFIX = "Event: "; } public class TrimAssembly : AssemblyElement { public TrimAssembly(string assemblyName, IncludeStatus status) { _name = assemblyName; _includeStatus = status; _types = new Dictionary<string, TypeElement>(); _typeForwarders = new Dictionary<string, TypeForwarderElement>(); } public override IncludeStatus IncludeStatus { get { return _includeStatus; } } public override string Key { get { return _name; } } public string Name { get { return _name; } } public override IDictionary<string, TypeForwarderElement> TypeForwarders { get { return _typeForwarders; } } private string _name; private IncludeStatus _includeStatus; private Dictionary<string, TypeElement> _types; private Dictionary<string, TypeForwarderElement> _typeForwarders; public override IDictionary<string, TypeElement> Types { get { return _types; } } } public class TrimType : TypeElement { public TrimType(String typeName, IncludeStatus includeStatus, VisibilityOverride visibilityOverride, SecurityTransparencyStatus securityTransparencyStatus) { _typeName = typeName; _typeMembers = new Dictionary<string, MemberElement>(); _includeStatus = includeStatus; _visibilityOverride = visibilityOverride; _securityTransparencyStatus = securityTransparencyStatus; } public override IncludeStatus IncludeStatus { get { return _includeStatus; } } public override VisibilityOverride VisibilityOverride { get { return _visibilityOverride; } } public override SecurityTransparencyStatus SecurityTransparencyStatus { get { return _securityTransparencyStatus; } } public override string Key { get { return _typeName; } } public virtual TrimMember GetMemberElementFromMember(ITypeMemberReference member) { if (member == null || member.GetType().ToString().Contains("Dummy")) { throw new ArgumentNullException("member"); } MemberElement memberElement = null; _typeMembers.TryGetValue(Util.MemberKeyFromMember(member), out memberElement); return memberElement as TrimMember; } public String TypeName { get { return _typeName; } } public void AddMember(TrimMember member) { _typeMembers.Add(member.Key, member); } public override IDictionary<string, MemberElement> Members { get { return _typeMembers; } } private String _typeName; private Dictionary<string, MemberElement> _typeMembers; private IncludeStatus _includeStatus; private VisibilityOverride _visibilityOverride; private SecurityTransparencyStatus _securityTransparencyStatus; } public class TrimTypeForwarder : TypeForwarderElement { private String _assemblyName; private String _typeName; private IncludeStatus _includeStatus; public TrimTypeForwarder(String assemblyName, String typeName, IncludeStatus includeStatus) { _assemblyName = assemblyName; _typeName = typeName; _includeStatus = includeStatus; } public override IncludeStatus IncludeStatus { get { return _includeStatus; } } public override VisibilityOverride VisibilityOverride { get { throw new NotSupportedException(); } } public override SecurityTransparencyStatus SecurityTransparencyStatus { get { throw new NotSupportedException(); } } public override string AssemblyName { get { return _assemblyName; } } public override string TypeName { get { return _typeName; } } } // Represents a special type that's not included in model.xml. public class SpecialTrimType : TrimType { public SpecialTrimType(string typeName) : base(typeName, IncludeStatus.ImplRoot, VisibilityOverride.None, SecurityTransparencyStatus.Transparent) { } public override TrimMember GetMemberElementFromMember(ITypeMemberReference member) { return new SpecialTrimMember(this, member.Name.Value, null, Util.GetMemberTypeFromMember(member)); } } public class TrimMember : MemberElement { public TrimMember(TrimType declaringType, string memberName, string returnType, /*string paramListString, */MemberTypes memberType, IncludeStatus includeStatus, VisibilityOverride visibilityOverride, SecurityTransparencyStatus securityTransparencyStatus) { _declaringType = declaringType; _memberName = memberName; _returnType = returnType; _memberType = memberType; _includeStatus = includeStatus; _securityTransparencyStatus = securityTransparencyStatus; //_paramListString = paramListString; //if (null == paramListString) // _paramQualifiedTypeNames = new List<string>(); //else // _paramQualifiedTypeNames = SplitParameterList(paramListString); _visibilityOverride = visibilityOverride; } public override string Name { get { return _memberName; } } public override string ReturnType { get { return _returnType; } } public override VisibilityOverride VisibilityOverride { get { return _visibilityOverride; } } public override SecurityTransparencyStatus SecurityTransparencyStatus { get { return _securityTransparencyStatus; } } public override IncludeStatus IncludeStatus { get { return _includeStatus; } } private TrimType _declaringType; private string _memberName; private string _returnType; private string _key; private MemberTypes _memberType; private IncludeStatus _includeStatus; //IList<string> _paramQualifiedTypeNames; //string _paramListString; private VisibilityOverride _visibilityOverride; private SecurityTransparencyStatus _securityTransparencyStatus; public TrimType DeclaringType { get { return _declaringType; } } public override MemberTypes MemberType { get { return _memberType; } } public string MemberName { get { return _memberName; } } //public IList<string> ParamQualifiedTypeNames { get { return _paramQualifiedTypeNames; } } //public string ParamListString { get { return _paramListString; } } public bool IsVisibleExternally { get { return (_includeStatus == IncludeStatus.ApiClosure || _includeStatus == IncludeStatus.ApiRoot || _includeStatus == IncludeStatus.ApiFxInternal); } } public override string Key { get { if (_key == null) { StringBuilder sbKey = new StringBuilder(); sbKey.Append(MemberType.ToString()); sbKey.Append(" : "); sbKey.Append(_memberName); if (_returnType != null) { sbKey.Append(" : "); sbKey.Append(_returnType); } _key = sbKey.ToString(); } return _key; } } } public class SpecialTrimMember : TrimMember { public SpecialTrimMember(TrimType trimType, string memberName, string returnType, MemberTypes memberType) : base(trimType, memberName, returnType, memberType, IncludeStatus.ImplRoot, VisibilityOverride.None, SecurityTransparencyStatus.Transparent) { } } internal class TrimReader : ModelReader { //Dictionary<string, TrimType> _types; //bool _changeVisibility; public TrimReader(/*Dictionary<string, TrimType> types*/) { //_types = types; } public override AssemblyElement CreateAssemblyElement(ModelElement model, string assemblyName, IncludeStatus includeStatus) { IncludeSet includeSet = (IncludeSet)model; TrimAssembly trimAssembly = new TrimAssembly(assemblyName, includeStatus); ; includeSet.AddAssembly(trimAssembly); return trimAssembly; } public override TypeElement CreateTypeElement(AssemblyElement assembly, string typeName, IncludeStatus includeStatus, VisibilityOverride visibilityOverride, SecurityTransparencyStatus securityTransparencyStatus) { TrimAssembly trimAssembly = (TrimAssembly)assembly; TrimType typeIncludeInfo = new TrimType(typeName, includeStatus, visibilityOverride, securityTransparencyStatus); trimAssembly.Types.Add(typeIncludeInfo.Key, typeIncludeInfo); return typeIncludeInfo; } public override TypeForwarderElement CreateTypeForwarderElement(AssemblyElement parent, string assemblyName, string typeName, IncludeStatus includeStatus) { TrimAssembly trimAssembly = (TrimAssembly)parent; TrimTypeForwarder typeForwarder = new TrimTypeForwarder(assemblyName, typeName, includeStatus); trimAssembly.TypeForwarders.Add(typeForwarder.Key, typeForwarder); return typeForwarder; } public override MemberElement CreateMemberElement(TypeElement type, string memberName, string returnType, MemberTypes memberType, IncludeStatus includeStatus, VisibilityOverride visibilityOverride, SecurityTransparencyStatus securityTransparencyStatus) { TrimType typeInfo = (TrimType)type; TrimMember id = new TrimMember(typeInfo, memberName, returnType, /*paramListString, */memberType, includeStatus, visibilityOverride, securityTransparencyStatus); typeInfo.Members.Add(id.Key, id); return id; } public override bool IncludeBuild(string platform, string architecture, string flavor, string condition) { // TODO: Trimmer currently doesn't support filtering. All our filtering for createMscorlibSmall is done in Thinner. return true; } } }
#region Using using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text.RegularExpressions; using DelegateList = System.Collections.Generic.List<System.Reflection.FieldInfo>; #endregion // ReSharper disable once CheckNamespace namespace Khronos { /// <summary> /// Base class for loading external routines. /// </summary> /// <remarks> /// <para> /// This class is used for basic operations of automatic generated classes Gl, Wgl, Glx and Egl. The main /// functions of this class allows: /// - To parse OpenGL extensions string /// - To query import functions using reflection /// - To query delegate functions using reflection /// - To link imported functions into delegates functions. /// </para> /// <para> /// Argument of the methods with 'internal' modifier are not checked. /// </para> /// </remarks> public class KhronosApi { #region Function Linkage /// <summary> /// The function OpenGL calls will be loaded by. /// </summary> public static Func<string, IntPtr> ProcLoadFunction; /// <summary> /// Delegate used for getting a procedure address. /// </summary> /// <param name="path"> /// A <see cref="string" /> that specifies the path of the library to load the procedure from. /// </param> /// <param name="function"> /// A <see cref="string" /> that specifies the name of the procedure to be loaded. /// </param> /// <returns> /// It returns a <see cref="IntPtr" /> that specifies the function pointer. If not defined, it /// returns <see cref="IntPtr.Zero" />. /// </returns> internal delegate IntPtr GetAddressDelegate(string path, string function); /// <summary> /// Link delegates field using import declaration, using platform specific method for determining procedures address. /// </summary> internal static void BindAPIFunction<T>(string functionName, KhronosVersion version, ExtensionsCollection extensions) { FunctionContext functionContext = GetFunctionContext(typeof(T)); Debug.Assert(functionContext != null); BindAPIFunction(functionContext.GetFunction(functionName), version, extensions); } /// <summary> /// Link delegates fields using import declarations. /// </summary> /// <param name="function"> /// A <see cref="FieldInfo" /> that specifies the underlying function field to be updated. /// </param> /// <param name="version"></param> /// <param name="extensions"></param> private static void BindAPIFunction(FieldInfo function, KhronosVersion version, ExtensionsCollection extensions) { Debug.Assert(function != null); RequiredByFeatureAttribute requiredByFeature = null; var requiredByExtensions = new List<RequiredByFeatureAttribute>(); string defaultName = function.Name.Substring(1); // Delegate name always prefixes with 'p' if (version != null || extensions != null) { var removed = false; #region Check Requirement #if NETSTANDARD1_1 || NETSTANDARD1_4 || NETCORE IEnumerable<Attribute> attrRequired = new List<Attribute>(function.GetCustomAttributes(typeof(RequiredByFeatureAttribute))); #else IEnumerable<Attribute> attrRequired = Attribute.GetCustomAttributes(function, typeof(RequiredByFeatureAttribute)); #endif // ReSharper disable once PossibleInvalidCastExceptionInForeachLoop foreach (RequiredByFeatureAttribute attr in attrRequired) { // Check for API support if (attr.IsSupported(version, extensions) == false) continue; // Keep track of the features requiring this command if (attr.FeatureVersion != null) { // Version feature: keep track only of the maximum version if (requiredByFeature == null || requiredByFeature.FeatureVersion < attr.FeatureVersion) requiredByFeature = attr; } else { // Extension feature: collect every supporting extension requiredByExtensions.Add(attr); } } #endregion #region Check Deprecation/Removal if (requiredByFeature != null) { // Note: indeed the feature could be supported; check whether it is removed; this is checked only if // a non-extension feature is detected: extensions cannot remove commands Attribute[] attrRemoved = Attribute.GetCustomAttributes(function, typeof(RemovedByFeatureAttribute)); KhronosVersion maxRemovedVersion = null; // ReSharper disable once PossibleInvalidCastExceptionInForeachLoop foreach (RemovedByFeatureAttribute attr in attrRemoved) { // Check for API support if (attr.IsRemoved(version, extensions) == false) continue; // Removed! removed = true; // Keep track of the maximum API version removing this command if (maxRemovedVersion == null || maxRemovedVersion < attr.FeatureVersion) maxRemovedVersion = attr.FeatureVersion; } // Check for resurrection if (removed) { Debug.Assert(requiredByFeature != null); Debug.Assert(maxRemovedVersion != null); if (requiredByFeature.FeatureVersion > maxRemovedVersion) removed = false; } } #endregion // Do not check feature requirements in case of removal. Note: extensions are checked all the same if (removed) requiredByFeature = null; } // Load function pointer IntPtr importAddress; if (requiredByFeature != null || version == null) { // Load command address (version feature) string functionName = defaultName; if (requiredByFeature?.EntryPoint != null) functionName = requiredByFeature.EntryPoint; if ((importAddress = ProcLoadFunction(functionName)) != IntPtr.Zero) { BindAPIFunction(function, importAddress); return; } } // Load command address (extension features) foreach (RequiredByFeatureAttribute extensionFeature in requiredByExtensions) { string functionName = extensionFeature.EntryPoint ?? defaultName; if ((importAddress = ProcLoadFunction(functionName)) != IntPtr.Zero) { BindAPIFunction(function, importAddress); return; } } // Function not implemented: reset function.SetValue(null, null); } /// <summary> /// Set fields using import declarations. /// </summary> /// <param name="function"> /// A <see cref="FieldInfo" /> that specifies the underlying function field to be updated. /// </param> /// <param name="importAddress"> /// A <see cref="IntPtr" /> that specifies the function pointer. /// </param> private static void BindAPIFunction(FieldInfo function, IntPtr importAddress) { Debug.Assert(function != null); Debug.Assert(importAddress != IntPtr.Zero); Delegate delegatePtr = Marshal.GetDelegateForFunctionPointer(importAddress, function.FieldType); Debug.Assert(delegatePtr != null); function.SetValue(null, delegatePtr); } /// <summary> /// Link delegates fields using import declarations. /// </summary> /// <param name="version"></param> /// <param name="extensions"></param> /// <exception cref="ArgumentNullException"> /// Exception thrown if <paramref name="path" /> or <paramref name="getAddress" /> is null. /// </exception> internal static void BindAPI<T>(KhronosVersion version, ExtensionsCollection extensions) { FunctionContext functionContext = GetFunctionContext(typeof(T)); Debug.Assert(functionContext != null); foreach (FieldInfo fi in functionContext.Delegates) { BindAPIFunction(fi, version, extensions); } } /// <summary> /// Determine whether an API command is compatible with the specific API version and extensions registry. /// </summary> /// <param name="function"> /// A <see cref="FieldInfo" /> that specifies the command delegate to set. This argument make avail attributes useful /// to determine the actual support for this command. /// </param> /// <param name="version"> /// The <see cref="KhronosVersion" /> that specifies the API version. /// </param> /// <param name="extensions"> /// The <see cref="ExtensionsCollection" /> that specifies the API extensions registry. /// </param> /// <returns> /// It returns a <see cref="Boolean" /> that specifies whether <paramref name="function" /> is supported by the /// API having the version <paramref name="version" /> and the extensions registry <paramref name="extensions" />. /// </returns> internal static bool IsCompatibleField(FieldInfo function, KhronosVersion version, ExtensionsCollection extensions) { Debug.Assert(function != null); Debug.Assert(version != null); IEnumerable<Attribute> attrRequired = Attribute.GetCustomAttributes(function, typeof(RequiredByFeatureAttribute)); KhronosVersion maxRequiredVersion = null; bool required = false, removed = false; // ReSharper disable once PossibleInvalidCastExceptionInForeachLoop foreach (RequiredByFeatureAttribute attr in attrRequired) { // Check for API support if (attr.IsSupported(version, extensions) == false) continue; // Supported! required = true; // Keep track of the maximum API version supporting this command // Note: useful for resurrected commands after deprecation if (maxRequiredVersion == null || maxRequiredVersion < attr.FeatureVersion) maxRequiredVersion = attr.FeatureVersion; } if (required) { // Note: indeed the feature could be supported; check whether it is removed IEnumerable<Attribute> attrRemoved = Attribute.GetCustomAttributes(function, typeof(RemovedByFeatureAttribute)); KhronosVersion maxRemovedVersion = null; // ReSharper disable once PossibleInvalidCastExceptionInForeachLoop foreach (RemovedByFeatureAttribute attr in attrRemoved) { if (attr.IsRemoved(version, extensions) == false) continue; // Removed! removed = true; // Keep track of the maximum API version removing this command if (maxRemovedVersion == null || maxRemovedVersion < attr.FeatureVersion) maxRemovedVersion = attr.FeatureVersion; } // Check for resurrection if (removed) { Debug.Assert(maxRequiredVersion != null); Debug.Assert(maxRemovedVersion != null); if (maxRequiredVersion > maxRemovedVersion) removed = false; } return removed == false; } return false; } /// <summary> /// Get the delegates methods for the specified type. /// </summary> /// <param name="type"> /// A <see cref="Type" /> that specifies the type used for detecting delegates declarations. /// </param> /// <returns> /// It returns the <see cref="DelegateList" /> for <paramref name="type" />. /// </returns> private static DelegateList GetDelegateList(Type type) { Type delegatesClass = type.GetNestedType("Delegates", BindingFlags.Static | BindingFlags.NonPublic); Debug.Assert(delegatesClass != null); return new DelegateList(delegatesClass.GetFields(BindingFlags.Static | BindingFlags.NonPublic)); } /// <summary> /// Get the <see cref="Khronos.KhronosApi.FunctionContext" /> corresponding to a specific type. /// </summary> /// <param name="type"> /// A <see cref="Type" /> that specifies the type used for loading function pointers. /// </param> /// <returns></returns> private static FunctionContext GetFunctionContext(Type type) { if (FunctionContexts.TryGetValue(type, out FunctionContext functionContext)) return functionContext; functionContext = new FunctionContext(type); FunctionContexts.Add(type, functionContext); return functionContext; } /// <summary> /// Information required for loading function pointers. /// </summary> private class FunctionContext { /// <summary> /// Construct a FunctionContext on a specific <see cref="Type" />. /// </summary> /// <param name="type"> /// The <see cref="Type" /> deriving from <see cref="KhronosApi" />. /// </param> public FunctionContext(Type type) { Type delegatesClass = type.GetNestedType("Delegates", BindingFlags.Static | BindingFlags.NonPublic); Debug.Assert(delegatesClass != null); _delegateType = delegatesClass; Delegates = GetDelegateList(type); } /// <summary> /// Get the field representing the delegate for an API function. /// </summary> /// <param name="functionName"> /// A <see cref="string" /> that specifies the native function name. /// </param> /// <returns> /// It returns the <see cref="FieldInfo" /> for the function. /// </returns> public FieldInfo GetFunction(string functionName) { if (functionName == null) throw new ArgumentNullException(nameof(functionName)); FieldInfo functionField = _delegateType.GetField("p" + functionName, BindingFlags.Static | BindingFlags.NonPublic); Debug.Assert(functionField != null); return functionField; } /// <summary> /// Type containing all delegates. /// </summary> private readonly Type _delegateType; /// <summary> /// The delegate fields list for the underlying type. /// </summary> public readonly DelegateList Delegates; } /// <summary> /// Mapping between <see cref="Khronos.KhronosApi.FunctionContext" /> and the underlying <see cref="Type" />. /// </summary> private static readonly Dictionary<Type, FunctionContext> FunctionContexts = new Dictionary<Type, FunctionContext>(); #endregion #region Extension Support /// <summary> /// Attribute asserting the extension requiring the underlying member. /// </summary> [AttributeUsage(AttributeTargets.Field, AllowMultiple = true)] public sealed class ExtensionAttribute : Attribute { /// <summary> /// Construct a ExtensionAttribute, specifying the extension name. /// </summary> /// <param name="extensionName"> /// A <see cref="string" /> that specifies the name of the extension that requires the element. /// </param> /// <exception cref="ArgumentException"> /// Exception thrown if <paramref name="extensionName" /> is null or empty. /// </exception> public ExtensionAttribute(string extensionName) { ExtensionName = extensionName; } /// <summary> /// The name of the extension. /// </summary> public readonly string ExtensionName; /// <summary> /// </summary> public string Api; } /// <summary> /// Attribute asserting the extension requiring the underlying member. /// </summary> [AttributeUsage(AttributeTargets.Field, AllowMultiple = true)] public sealed class CoreExtensionAttribute : Attribute { #region Constructors /// <summary> /// Construct a CoreExtensionAttribute specifying the version numbers. /// </summary> /// <param name="major"> /// A <see cref="Int32" /> that specifies that major version number. /// </param> /// <param name="minor"> /// A <see cref="Int32" /> that specifies that minor version number. /// </param> /// <param name="api"> /// A <see cref="string" /> that specifies the API name. /// </param> /// <exception cref="ArgumentException"> /// Exception thrown if <paramref name="major" /> is less or equals to 0, or if <paramref name="minor" /> is less than 0. /// </exception> /// <exception cref="ArgumentNullException"> /// Exception thrown if <paramref name="api" /> is null. /// </exception> public CoreExtensionAttribute(int major, int minor, string api) { Version = new KhronosVersion(major, minor, 0, api); } /// <summary> /// Construct a CoreExtensionAttribute specifying the version numbers. /// </summary> /// <param name="major"> /// A <see cref="Int32" /> that specifies that major version number. /// </param> /// <param name="minor"> /// A <see cref="Int32" /> that specifies that minor version number. /// </param> /// <exception cref="ArgumentException"> /// Exception thrown if <paramref name="major" /> is less or equals to 0, or if <paramref name="minor" /> is less than 0. /// </exception> public CoreExtensionAttribute(int major, int minor) : this(major, minor, KhronosVersion.API_GL) { } #endregion #region Required API Version /// <summary> /// The required major OpenGL version for supporting the extension. /// </summary> public readonly KhronosVersion Version; #endregion } /// <summary> /// Base class for managing OpenGL extensions. /// </summary> public abstract class ExtensionsCollection { /// <summary> /// Check whether the specified extension is supported by current platform. /// </summary> /// <param name="extensionName"> /// A <see cref="string" /> that specifies the extension name. /// </param> /// <returns> /// It returns a boolean value indicating whether the extension identified with <paramref name="extensionName" /> /// is supported or not by the current platform. /// </returns> public bool HasExtensions(string extensionName) { if (extensionName == null) throw new ArgumentNullException(nameof(extensionName)); return _extensionsRegistry.ContainsKey(extensionName); } /// <summary> /// Force extension support. /// </summary> /// <param name="extensionName"> /// A <see cref="string" /> that specifies the extension name. /// </param> internal void EnableExtension(string extensionName) { if (extensionName == null) throw new ArgumentNullException(nameof(extensionName)); _extensionsRegistry[extensionName] = true; } /// <summary> /// Query the supported extensions. /// </summary> /// <param name="version"> /// The <see cref="KhronosVersion" /> that specifies the version of the API context. /// </param> /// <param name="extensionsString"> /// A string that specifies the supported extensions, those names are separated by spaces. /// </param> /// <exception cref="ArgumentNullException"> /// Exception thrown if <paramref name="extensionsString" /> is null. /// </exception> protected void Query(KhronosVersion version, string extensionsString) { if (extensionsString == null) throw new ArgumentNullException(nameof(extensionsString)); Query(version, extensionsString.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries)); } /// <summary> /// Query the supported extensions. /// </summary> /// <param name="version"> /// The <see cref="KhronosVersion" /> that specifies the version of the API context. /// </param> /// <param name="extensions"> /// An array of strings that specifies the supported extensions. /// </param> /// <exception cref="ArgumentNullException"> /// Exception thrown if <paramref name="extensions" /> is null. /// </exception> protected void Query(KhronosVersion version, string[] extensions) { if (extensions == null) throw new ArgumentNullException(nameof(extensions)); // Cache extension names in registry _extensionsRegistry.Clear(); foreach (string extension in extensions) { if (!_extensionsRegistry.ContainsKey(extension)) _extensionsRegistry.Add(extension, true); } // Sync fields SyncMembers(version); } /// <summary> /// Set all fields of this ExtensionsCollection, depending on current extensions. /// </summary> /// <param name="version"> /// The <see cref="KhronosVersion" /> that specifies the context version/API. It can be null. /// </param> protected internal void SyncMembers(KhronosVersion version) { Type thisType = GetType(); #if NETSTANDARD1_1 || NETSTANDARD1_4 || NETCORE IEnumerable<FieldInfo> thisTypeFields = thisType.GetTypeInfo().DeclaredFields; #else IEnumerable<FieldInfo> thisTypeFields = thisType.GetFields(BindingFlags.Instance | BindingFlags.Public); #endif foreach (FieldInfo fieldInfo in thisTypeFields) { // Check boolean field (defensive) // Debug.Assert(fieldInfo.FieldType == typeof(bool)); if (fieldInfo.FieldType != typeof(bool)) continue; var support = false; // Support by extension #if NETSTANDARD1_1 || NETSTANDARD1_4 || NETCORE IEnumerable<Attribute> extensionAttributes = fieldInfo.GetCustomAttributes(typeof(ExtensionAttribute)); #else IEnumerable<Attribute> extensionAttributes = Attribute.GetCustomAttributes(fieldInfo, typeof(ExtensionAttribute)); #endif // ReSharper disable once PossibleInvalidCastExceptionInForeachLoop foreach (ExtensionAttribute extensionAttribute in extensionAttributes) { if (!_extensionsRegistry.ContainsKey(extensionAttribute.ExtensionName)) continue; if (version != null && version.Api != null && extensionAttribute.Api != null && !Regex.IsMatch(version.Api, "^" + extensionAttribute.Api + "$")) continue; support = true; break; } // Support by version if (version != null && support == false) { #if NETSTANDARD1_1 || NETSTANDARD1_4 || NETCORE IEnumerable<Attribute> coreAttributes = fieldInfo.GetCustomAttributes(typeof(CoreExtensionAttribute)); #else IEnumerable<Attribute> coreAttributes = Attribute.GetCustomAttributes(fieldInfo, typeof(CoreExtensionAttribute)); #endif // ReSharper disable once PossibleInvalidCastExceptionInForeachLoop foreach (CoreExtensionAttribute coreAttribute in coreAttributes) { if (version.Api != coreAttribute.Version.Api || version < coreAttribute.Version) continue; support = true; break; } } fieldInfo.SetValue(this, support); } } /// <summary> /// Registry of supported extensions. /// </summary> private readonly Dictionary<string, bool> _extensionsRegistry = new Dictionary<string, bool>(); } #endregion #region Command Checking /// <summary> /// Check whether commands implemented by the current driver have a corresponding extension declaring the /// support of them. /// </summary> /// <typeparam name="T"> /// The type of the KhronosApi to inspect for commands. /// </typeparam> /// <param name="version"> /// The <see cref="KhronosVersion" /> currently implemented by the current context on this thread. /// </param> /// <param name="extensions"> /// The <see cref="ExtensionsCollection" /> that specifies the extensions supported by the driver. /// </param> /// <param name="enableExtensions"></param> protected static void CheckExtensionCommands<T>(KhronosVersion version, ExtensionsCollection extensions, bool enableExtensions) where T : KhronosApi { if (version == null) throw new ArgumentNullException(nameof(version)); if (extensions == null) throw new ArgumentNullException(nameof(extensions)); FunctionContext functionContext = GetFunctionContext(typeof(T)); Debug.Assert(functionContext != null); var hiddenVersions = new Dictionary<string, List<Type>>(); var hiddenExtensions = new Dictionary<string, bool>(); foreach (FieldInfo fi in functionContext.Delegates) { var fiDelegateType = (Delegate) fi.GetValue(null); bool commandDefined = fiDelegateType != null; var supportedByFeature = false; // Get the delegate type Type delegateType = fi.DeclaringType?.GetNestedType(fi.Name.Substring(1), BindingFlags.Public | BindingFlags.NonPublic); if (delegateType == null) continue; // Support fields names not in sync with delegate types // TODO Why not use 'fi' directly for getting attributes? They should be in sync IEnumerable<object> requiredByFeatureAttributes = delegateType.GetCustomAttributes(typeof(RequiredByFeatureAttribute), false); foreach (RequiredByFeatureAttribute requiredByFeatureAttribute in requiredByFeatureAttributes) { supportedByFeature |= requiredByFeatureAttribute.IsSupported(version, extensions); } // Find the underlying extension RequiredByFeatureAttribute hiddenVersionAttrib = null; RequiredByFeatureAttribute hiddenExtensionAttrib = null; foreach (RequiredByFeatureAttribute requiredByFeatureAttribute in requiredByFeatureAttributes) { if (requiredByFeatureAttribute.IsSupportedApi(version.Api) == false) { // Version attribute if (hiddenVersionAttrib == null) hiddenVersionAttrib = requiredByFeatureAttribute; } else { // Extension attribute if (hiddenExtensionAttrib == null) hiddenExtensionAttrib = requiredByFeatureAttribute; } } if (commandDefined != supportedByFeature) if (commandDefined) { if (hiddenVersionAttrib != null && hiddenExtensionAttrib == null) { if (hiddenVersions.TryGetValue(hiddenVersionAttrib.FeatureName, out List<Type> versionDelegates) == false) hiddenVersions.Add(hiddenVersionAttrib.FeatureName, versionDelegates = new List<Type>()); versionDelegates.Add(delegateType); } if (hiddenExtensionAttrib != null) // Eventually leave to false for incomplete extensions if (hiddenExtensions.ContainsKey(hiddenExtensionAttrib.FeatureName) == false) hiddenExtensions.Add(hiddenExtensionAttrib.FeatureName, true); } // Partial extensions are not supported if (hiddenExtensionAttrib != null && commandDefined == false && hiddenExtensions.ContainsKey(hiddenExtensionAttrib.FeatureName)) hiddenExtensions[hiddenExtensionAttrib.FeatureName] = false; } if (!enableExtensions) return; var sync = false; foreach (KeyValuePair<string, bool> hiddenExtension in hiddenExtensions.Where(hiddenExtension => hiddenExtension.Value)) { extensions.EnableExtension(hiddenExtension.Key); sync = true; } if (sync) extensions.SyncMembers(version); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Reflection; using Xunit; namespace System.Globalization.Tests { public class TextInfoMiscTests { public static IEnumerable<object[]> TextInfo_TestData() { yield return new object[] { "", 0x7f, 0x4e4, 0x25, 0x2710, 0x1b5, false }; yield return new object[] { "en-US", 0x409, 0x4e4, 0x25, 0x2710, 0x1b5, false }; yield return new object[] { "ja-JP", 0x411, 0x3a4, 0x4f42, 0x2711, 0x3a4, false }; yield return new object[] { "zh-CN", 0x804, 0x3a8, 0x1f4, 0x2718, 0x3a8, false }; yield return new object[] { "ar-SA", 0x401, 0x4e8, 0x4fc4, 0x2714, 0x2d0, true }; yield return new object[] { "ko-KR", 0x412, 0x3b5, 0x5161, 0x2713, 0x3b5, false }; yield return new object[] { "he-IL", 0x40d, 0x4e7, 0x1f4, 0x2715, 0x35e, true }; } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] // OS changes [MemberData(nameof(TextInfo_TestData))] public void MiscTest(string cultureName, int lcid, int ansiCodePage, int ebcdiCCodePage, int macCodePage, int oemCodePage, bool isRightToLeft) { TextInfo ti = CultureInfo.GetCultureInfo(cultureName).TextInfo; Assert.Equal(lcid, ti.LCID); Assert.Equal(ansiCodePage, ti.ANSICodePage); Assert.Equal(ebcdiCCodePage, ti.EBCDICCodePage); Assert.Equal(macCodePage, ti.MacCodePage); Assert.Equal(oemCodePage, ti.OEMCodePage); Assert.Equal(isRightToLeft, ti.IsRightToLeft); } [Fact] public void ReadOnlyTest() { TextInfo ti = CultureInfo.GetCultureInfo("en-US").TextInfo; Assert.True(ti.IsReadOnly, "IsReadOnly should be true with cached TextInfo object"); ti = (TextInfo) ti.Clone(); Assert.False(ti.IsReadOnly, "IsReadOnly should be false with cloned TextInfo object"); ti = TextInfo.ReadOnly(ti); Assert.True(ti.IsReadOnly, "IsReadOnly should be true with created read-nly TextInfo object"); } [Fact] public void ToTitleCaseTest() { TextInfo ti = CultureInfo.GetCultureInfo("en-US").TextInfo; Assert.Equal("A Tale Of Two Cities", ti.ToTitleCase("a tale of two cities")); Assert.Equal("Growl To The Rescue", ti.ToTitleCase("gROWL to the rescue")); Assert.Equal("Inside The US Government", ti.ToTitleCase("inside the US government")); Assert.Equal("Sports And MLB Baseball", ti.ToTitleCase("sports and MLB baseball")); Assert.Equal("The Return Of Sherlock Holmes", ti.ToTitleCase("The Return of Sherlock Holmes")); Assert.Equal("UNICEF And Children", ti.ToTitleCase("UNICEF and children")); AssertExtensions.Throws<ArgumentNullException>("str", () => ti.ToTitleCase(null)); } public static IEnumerable<object[]> DutchTitleCaseInfo_TestData() { yield return new object[] { "nl-NL", "IJ IJ IJ IJ", "ij iJ Ij IJ" }; yield return new object[] { "nl-be", "IJzeren Eigenschappen", "ijzeren eigenschappen" }; yield return new object[] { "NL-NL", "Lake IJssel", "lake iJssel" }; yield return new object[] { "NL-BE", "Boba N' IJango Fett PEW PEW", "Boba n' Ijango fett PEW PEW" }; yield return new object[] { "en-us", "Ijill And Ijack", "ijill and ijack" }; yield return new object[] { "de-DE", "Ij Ij IJ Ij", "ij ij IJ ij" }; yield return new object[] { "he-il", "Ijon't Know What Will Happen.", "Ijon't know what Will happen." }; } [Theory] [MemberData(nameof(DutchTitleCaseInfo_TestData))] public void ToTitleCaseDutchTest(string cultureName, string expected, string actual) { TextInfo ti = CultureInfo.GetCultureInfo(cultureName).TextInfo; Assert.Equal(expected, ti.ToTitleCase(actual)); } public static IEnumerable<object[]> CultureName_TestData() { yield return new object[] { CultureInfo.InvariantCulture.TextInfo, "" }; yield return new object[] { new CultureInfo("").TextInfo, "" }; yield return new object[] { new CultureInfo("en-US").TextInfo, "en-US" }; yield return new object[] { new CultureInfo("fr-FR").TextInfo, "fr-FR" }; yield return new object[] { new CultureInfo("EN-us").TextInfo, "en-US" }; yield return new object[] { new CultureInfo("FR-fr").TextInfo, "fr-FR" }; } [Theory] [MemberData(nameof(CultureName_TestData))] public void CultureName(TextInfo textInfo, string expected) { Assert.Equal(expected, textInfo.CultureName); } public static IEnumerable<object[]> IsReadOnly_TestData() { yield return new object[] { CultureInfo.ReadOnly(new CultureInfo("en-US")).TextInfo, true }; yield return new object[] { CultureInfo.InvariantCulture.TextInfo, true }; yield return new object[] { new CultureInfo("").TextInfo, false }; yield return new object[] { new CultureInfo("en-US").TextInfo, false }; yield return new object[] { new CultureInfo("fr-FR").TextInfo, false }; } [Theory] [MemberData(nameof(IsReadOnly_TestData))] public void IsReadOnly(TextInfo textInfo, bool expected) { Assert.Equal(expected, textInfo.IsReadOnly); } [Theory] [InlineData("en-US", false)] [InlineData("ar", true)] public void IsRightToLeft(string name, bool expected) { Assert.Equal(expected, new CultureInfo(name).TextInfo.IsRightToLeft); } [Fact] public void ListSeparator_EnUS() { Assert.NotEqual(string.Empty, new CultureInfo("en-US").TextInfo.ListSeparator); } [Theory] [InlineData("")] [InlineData(" ")] [InlineData("abcdef")] public void ListSeparator_Set(string newListSeparator) { TextInfo textInfo = new CultureInfo("en-US").TextInfo; textInfo.ListSeparator = newListSeparator; Assert.Equal(newListSeparator, textInfo.ListSeparator); } [Fact] public void ListSeparator_Set_Invalid() { Assert.Throws<InvalidOperationException>(() => CultureInfo.InvariantCulture.TextInfo.ListSeparator = ""); AssertExtensions.Throws<ArgumentNullException>("value", () => new CultureInfo("en-US").TextInfo.ListSeparator = null); } public static IEnumerable<object[]> Equals_TestData() { yield return new object[] { CultureInfo.InvariantCulture.TextInfo, CultureInfo.InvariantCulture.TextInfo, true }; yield return new object[] { CultureInfo.InvariantCulture.TextInfo, new CultureInfo("").TextInfo, true }; yield return new object[] { CultureInfo.InvariantCulture.TextInfo, new CultureInfo("en-US"), false }; yield return new object[] { new CultureInfo("en-US").TextInfo, new CultureInfo("en-US").TextInfo, true }; yield return new object[] { new CultureInfo("en-US").TextInfo, new CultureInfo("fr-FR").TextInfo, false }; yield return new object[] { new CultureInfo("en-US").TextInfo, null, false }; yield return new object[] { new CultureInfo("en-US").TextInfo, new object(), false }; yield return new object[] { new CultureInfo("en-US").TextInfo, 123, false }; yield return new object[] { new CultureInfo("en-US").TextInfo, "en-US", false }; } [Theory] [MemberData(nameof(Equals_TestData))] public void Equals(TextInfo textInfo, object obj, bool expected) { Assert.Equal(expected, textInfo.Equals(obj)); if (obj is TextInfo) { Assert.Equal(expected, textInfo.GetHashCode().Equals(obj.GetHashCode())); } } private static readonly string [] s_cultureNames = new string[] { "", "en-US", "fr", "fr-FR" }; // ToLower_TestData_netcore has the data which is specific to netcore framework public static IEnumerable<object[]> ToLower_TestData_netcore() { foreach (string cultureName in s_cultureNames) { // DESERT CAPITAL LETTER LONG I has a lower case variant (but not on Windows 7). yield return new object[] { cultureName, "\U00010400", PlatformDetection.IsWindows7 ? "\U00010400" : "\U00010428" }; } } public static IEnumerable<object[]> ToLower_TestData() { foreach (string cultureName in s_cultureNames) { yield return new object[] { cultureName, "", "" }; yield return new object[] { cultureName, "A", "a" }; yield return new object[] { cultureName, "a", "a" }; yield return new object[] { cultureName, "ABC", "abc" }; yield return new object[] { cultureName, "abc", "abc" }; yield return new object[] { cultureName, "1", "1" }; yield return new object[] { cultureName, "123", "123" }; yield return new object[] { cultureName, "!", "!" }; yield return new object[] { cultureName, "HELLOWOR!LD123", "hellowor!ld123" }; yield return new object[] { cultureName, "HelloWor!ld123", "hellowor!ld123" }; yield return new object[] { cultureName, "Hello\n\0World\u0009!", "hello\n\0world\t!" }; yield return new object[] { cultureName, "THIS IS A LONGER TEST CASE", "this is a longer test case" }; yield return new object[] { cultureName, "this Is A LONGER mIXEd casE test case", "this is a longer mixed case test case" }; yield return new object[] { cultureName, "THIS \t hAs \t SOMe \t tabs", "this \t has \t some \t tabs" }; yield return new object[] { cultureName, "EMBEDDED\0NuLL\0Byte\0", "embedded\0null\0byte\0" }; // LATIN CAPITAL LETTER O WITH ACUTE, which has a lower case variant. yield return new object[] { cultureName, "\u00D3", "\u00F3" }; // SNOWMAN, which does not have a lower case variant. yield return new object[] { cultureName, "\u2603", "\u2603" }; // RAINBOW (outside the BMP and does not case) yield return new object[] { cultureName, "\U0001F308", "\U0001F308" }; // Unicode defines some codepoints which expand into multiple codepoints // when cased (see SpecialCasing.txt from UNIDATA for some examples). We have never done // these sorts of expansions, since it would cause string lengths to change when cased, // which is non-intuitive. In addition, there are some context sensitive mappings which // we also don't preform. // Greek Capital Letter Sigma (does not to case to U+03C2 with "final sigma" rule). yield return new object[] { cultureName, "\u03A3", "\u03C3" }; } foreach (string cultureName in new string[] { "tr", "tr-TR", "az", "az-Latn-AZ" }) { yield return new object[] { cultureName, "\u0130", "i" }; yield return new object[] { cultureName, "i", "i" }; yield return new object[] { cultureName, "I", "\u0131" }; yield return new object[] { cultureName, "HI!", "h\u0131!" }; yield return new object[] { cultureName, "HI\n\0H\u0130\t!", "h\u0131\n\0hi\u0009!" }; } // ICU has special tailoring for the en-US-POSIX locale which treats "i" and "I" as different letters // instead of two letters with a case difference during collation. Make sure this doesn't confuse our // casing implementation, which uses collation to understand if we need to do Turkish casing or not. if (!PlatformDetection.IsWindows) { yield return new object[] { "en-US-POSIX", "I", "i" }; } } private static void TestToLower(string name, string str, string expected) { Assert.Equal(expected, new CultureInfo(name).TextInfo.ToLower(str)); if (str.Length == 1) { Assert.Equal(expected[0], new CultureInfo(name).TextInfo.ToLower(str[0])); } } [Theory] [MemberData(nameof(ToLower_TestData))] public void ToLower(string name, string str, string expected) { TestToLower(name, str, expected); } [Theory] [MemberData(nameof(ToLower_TestData_netcore))] public void ToLower_Netcore(string name, string str, string expected) { TestToLower(name, str, expected); } [Fact] public void ToLower_InvalidSurrogates() { // Invalid UTF-16 in a string (mismatched surrogate pairs) should be unchanged. foreach (string cultureName in new string[] { "", "en-US", "fr" }) { ToLower(cultureName, "BE CAREFUL, \uD83C\uD83C, THIS ONE IS TRICKY", "be careful, \uD83C\uD83C, this one is tricky"); ToLower(cultureName, "BE CAREFUL, \uDF08\uD83C, THIS ONE IS TRICKY", "be careful, \uDF08\uD83C, this one is tricky"); ToLower(cultureName, "BE CAREFUL, \uDF08\uDF08, THIS ONE IS TRICKY", "be careful, \uDF08\uDF08, this one is tricky"); } } [Theory] [InlineData("")] [InlineData("en-US")] [InlineData("fr")] public void ToLower_Null_ThrowsArgumentNullException(string cultureName) { AssertExtensions.Throws<ArgumentNullException>("str", () => new CultureInfo(cultureName).TextInfo.ToLower(null)); } // ToUpper_TestData_netcore has the data which is specific to netcore framework public static IEnumerable<object[]> ToUpper_TestData_netcore() { foreach (string cultureName in s_cultureNames) { // DESERT SMALL LETTER LONG I has an upper case variant (but not on Windows 7). yield return new object[] { cultureName, "\U00010428", PlatformDetection.IsWindows7 ? "\U00010428" : "\U00010400" }; } } public static IEnumerable<object[]> ToUpper_TestData() { foreach (string cultureName in s_cultureNames) { yield return new object[] { cultureName, "", "" }; yield return new object[] { cultureName, "a", "A" }; yield return new object[] { cultureName, "abc", "ABC" }; yield return new object[] { cultureName, "A", "A" }; yield return new object[] { cultureName, "ABC", "ABC" }; yield return new object[] { cultureName, "1", "1" }; yield return new object[] { cultureName, "123", "123" }; yield return new object[] { cultureName, "!", "!" }; yield return new object[] { cultureName, "HelloWor!ld123", "HELLOWOR!LD123" }; yield return new object[] { cultureName, "HELLOWOR!LD123", "HELLOWOR!LD123" }; yield return new object[] { cultureName, "Hello\n\0World\u0009!", "HELLO\n\0WORLD\t!" }; yield return new object[] { cultureName, "this is a longer test case", "THIS IS A LONGER TEST CASE" }; yield return new object[] { cultureName, "this Is A LONGER mIXEd casE test case", "THIS IS A LONGER MIXED CASE TEST CASE" }; yield return new object[] { cultureName, "this \t HaS \t somE \t TABS", "THIS \t HAS \t SOME \t TABS" }; yield return new object[] { cultureName, "embedded\0NuLL\0Byte\0", "EMBEDDED\0NULL\0BYTE\0" }; // LATIN SMALL LETTER O WITH ACUTE, which has an upper case variant. yield return new object[] { cultureName, "\u00F3", "\u00D3" }; // SNOWMAN, which does not have an upper case variant. yield return new object[] { cultureName, "\u2603", "\u2603" }; // RAINBOW (outside the BMP and does not case) yield return new object[] { cultureName, "\U0001F308", "\U0001F308" }; // Unicode defines some codepoints which expand into multiple codepoints // when cased (see SpecialCasing.txt from UNIDATA for some examples). We have never done // these sorts of expansions, since it would cause string lengths to change when cased, // which is non-intuitive. In addition, there are some context sensitive mappings which // we also don't preform. // es-zed does not case to SS when uppercased. yield return new object[] { cultureName, "\u00DF", "\u00DF" }; // Ligatures do not expand when cased. yield return new object[] { cultureName, "\uFB00", "\uFB00" }; // Precomposed character with no uppercase variant, we don't want to "decompose" this // as part of casing. yield return new object[] { cultureName, "\u0149", "\u0149" }; } // Turkish i foreach (string cultureName in new string[] { "tr", "tr-TR", "az", "az-Latn-AZ" }) { yield return new object[] { cultureName, "i", "\u0130" }; yield return new object[] { cultureName, "\u0130", "\u0130" }; yield return new object[] { cultureName, "\u0131", "I" }; yield return new object[] { cultureName, "I", "I" }; yield return new object[] { cultureName, "H\u0131\n\0Hi\u0009!", "HI\n\0H\u0130\t!" }; } // ICU has special tailoring for the en-US-POSIX locale which treats "i" and "I" as different letters // instead of two letters with a case difference during collation. Make sure this doesn't confuse our // casing implementation, which uses collation to understand if we need to do Turkish casing or not. if (!PlatformDetection.IsWindows) { yield return new object[] { "en-US-POSIX", "i", "I" }; } } private static void TestToUpper(string name, string str, string expected) { Assert.Equal(expected, new CultureInfo(name).TextInfo.ToUpper(str)); if (str.Length == 1) { Assert.Equal(expected[0], new CultureInfo(name).TextInfo.ToUpper(str[0])); } } [Theory] [MemberData(nameof(ToUpper_TestData))] public void ToUpper(string name, string str, string expected) { TestToUpper(name, str, expected); } [Theory] [MemberData(nameof(ToUpper_TestData_netcore))] public void ToUpper_netcore(string name, string str, string expected) { TestToUpper(name, str, expected); } [Fact] public void ToUpper_InvalidSurrogates() { // Invalid UTF-16 in a string (mismatched surrogate pairs) should be unchanged. foreach (string cultureName in new string[] { "", "en-US", "fr"}) { ToUpper(cultureName, "be careful, \uD83C\uD83C, this one is tricky", "BE CAREFUL, \uD83C\uD83C, THIS ONE IS TRICKY"); ToUpper(cultureName, "be careful, \uDF08\uD83C, this one is tricky", "BE CAREFUL, \uDF08\uD83C, THIS ONE IS TRICKY"); ToUpper(cultureName, "be careful, \uDF08\uDF08, this one is tricky", "BE CAREFUL, \uDF08\uDF08, THIS ONE IS TRICKY"); } } [Theory] [InlineData("")] [InlineData("en-US")] [InlineData("fr")] public void ToUpper_Null_ThrowsArgumentNullException(string cultureName) { AssertExtensions.Throws<ArgumentNullException>("str", () => new CultureInfo(cultureName).TextInfo.ToUpper(null)); } [Theory] [InlineData("en-US", "TextInfo - en-US")] [InlineData("fr-FR", "TextInfo - fr-FR")] [InlineData("", "TextInfo - ")] public void ToString(string name, string expected) { Assert.Equal(expected, new CultureInfo(name).TextInfo.ToString()); } } }
// *********************************************************************** // Copyright (c) 2012 Charlie Poole // // 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 PARALLEL using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; #if NET_2_0 || NET_3_5 using ManualResetEventSlim = System.Threading.ManualResetEvent; #endif namespace NUnit.Framework.Internal.Execution { /// <summary> /// WorkItemQueueState indicates the current state of a WorkItemQueue /// </summary> public enum WorkItemQueueState { /// <summary> /// The queue is paused /// </summary> Paused, /// <summary> /// The queue is running /// </summary> Running, /// <summary> /// The queue is stopped /// </summary> Stopped } /// <summary> /// A WorkItemQueue holds work items that are ready to /// be run, either initially or after some dependency /// has been satisfied. /// </summary> public class WorkItemQueue { private const int spinCount = 5; private Logger log = InternalTrace.GetLogger("WorkItemQueue"); private ConcurrentQueue<WorkItem> _innerQueue = new ConcurrentQueue<WorkItem>(); private Stack<ConcurrentQueue<WorkItem>> _savedQueues = new Stack<ConcurrentQueue<WorkItem>>(); /* This event is used solely for the purpose of having an optimized sleep cycle when * we have to wait on an external event (Add or Remove for instance) */ private readonly ManualResetEventSlim _mreAdd = new ManualResetEventSlim(false); /* The whole idea is to use these two values in a transactional * way to track and manage the actual data inside the underlying lock-free collection * instead of directly working with it or using external locking. * * They are manipulated with CAS and are guaranteed to increase over time and use * of the instance thus preventing ABA problems. */ private int _addId = int.MinValue; private int _removeId = int.MinValue; /// <summary> /// Initializes a new instance of the <see cref="WorkItemQueue"/> class. /// </summary> /// <param name="name">The name of the queue.</param> /// <param name="isParallel">Flag indicating whether this is a parallel queue</param> /// "<param name="apartment">ApartmentState to use for items on this queue</param> public WorkItemQueue(string name, bool isParallel, ApartmentState apartment) { Name = name; IsParallelQueue = isParallel; TargetApartment = apartment; State = WorkItemQueueState.Paused; MaxCount = 0; ItemsProcessed = 0; } #region Properties /// <summary> /// Gets the name of the work item queue. /// </summary> public string Name { get; private set; } /// <summary> /// Gets a flag indicating whether this queue is used for parallel execution /// </summary> public bool IsParallelQueue { get; private set; } /// <summary> /// Gets the target ApartmentState for work items on this queue /// </summary> public ApartmentState TargetApartment { get; private set; } private int _itemsProcessed; /// <summary> /// Gets the total number of items processed so far /// </summary> public int ItemsProcessed { get { return _itemsProcessed; } private set { _itemsProcessed = value; } } private int _maxCount; /// <summary> /// Gets the maximum number of work items. /// </summary> public int MaxCount { get { return _maxCount; } private set { _maxCount = value; } } private int _state; /// <summary> /// Gets the current state of the queue /// </summary> public WorkItemQueueState State { get { return (WorkItemQueueState)_state; } private set { _state = (int)value; } } /// <summary> /// Get a bool indicating whether the queue is empty. /// </summary> public bool IsEmpty { get { return _innerQueue.IsEmpty; } } #endregion #region Public Methods /// <summary> /// Enqueue a WorkItem to be processed /// </summary> /// <param name="work">The WorkItem to process</param> public void Enqueue(WorkItem work) { do { int cachedAddId = _addId; // Validate that we have are the current enqueuer if (Interlocked.CompareExchange(ref _addId, cachedAddId + 1, cachedAddId) != cachedAddId) continue; // Add to the collection _innerQueue.Enqueue(work); // Set MaxCount using CAS int i, j = _maxCount; do { i = j; j = Interlocked.CompareExchange(ref _maxCount, Math.Max(i, _innerQueue.Count), i); } while (i != j); // Wake up threads that may have been sleeping _mreAdd.Set(); return; } while (true); } /// <summary> /// Dequeue a WorkItem for processing /// </summary> /// <returns>A WorkItem or null if the queue has stopped</returns> public WorkItem Dequeue() { SpinWait sw = new SpinWait(); do { WorkItemQueueState cachedState = State; if (cachedState == WorkItemQueueState.Stopped) return null; // Tell worker to terminate int cachedRemoveId = _removeId; int cachedAddId = _addId; // Empty case (or paused) if (cachedRemoveId == cachedAddId || cachedState == WorkItemQueueState.Paused) { // Spin a few times to see if something changes if (sw.Count <= spinCount) { sw.SpinOnce(); } else { // Reset to wait for an enqueue _mreAdd.Reset(); // Recheck for an enqueue to avoid a Wait if ((cachedRemoveId != _removeId || cachedAddId != _addId) && cachedState != WorkItemQueueState.Paused) { // Queue is not empty, set the event _mreAdd.Set(); continue; } // Wait for something to happen _mreAdd.Wait(500); } continue; } // Validate that we are the current dequeuer if (Interlocked.CompareExchange(ref _removeId, cachedRemoveId + 1, cachedRemoveId) != cachedRemoveId) continue; // Dequeue our work item WorkItem work; while (!_innerQueue.TryDequeue(out work)) { }; // Add to items processed using CAS Interlocked.Increment(ref _itemsProcessed); return work; } while (true); } /// <summary> /// Start or restart processing of items from the queue /// </summary> public void Start() { log.Info("{0}.{1} starting", Name, _savedQueues.Count); if (Interlocked.CompareExchange(ref _state, (int)WorkItemQueueState.Running, (int)WorkItemQueueState.Paused) == (int)WorkItemQueueState.Paused) _mreAdd.Set(); } /// <summary> /// Signal the queue to stop /// </summary> public void Stop() { log.Info("{0}.{1} stopping - {2} WorkItems processed, max size {3}", Name, _savedQueues.Count, ItemsProcessed, MaxCount); if (Interlocked.Exchange(ref _state, (int)WorkItemQueueState.Stopped) != (int)WorkItemQueueState.Stopped) _mreAdd.Set(); } /// <summary> /// Pause the queue for restarting later /// </summary> public void Pause() { log.Debug("{0}.{1} pausing", Name, _savedQueues.Count); Interlocked.CompareExchange(ref _state, (int)WorkItemQueueState.Paused, (int)WorkItemQueueState.Running); } /// <summary> /// Save the current inner queue and create new ones for use by /// a non-parallel fixture with parallel children. /// </summary> internal void Save() { Pause(); _savedQueues.Push(_innerQueue); _innerQueue = new ConcurrentQueue<WorkItem>(); Start(); } /// <summary> /// Restore the inner queue that was previously saved /// </summary> internal void Restore() { Pause(); _innerQueue = _savedQueues.Pop(); Start(); } #endregion } #if NET_2_0 || NET_3_5 internal static class ManualResetEventExtensions { public static bool Wait (this ManualResetEvent mre, int millisecondsTimeout) { return mre.WaitOne(millisecondsTimeout, false); } } #endif } #endif
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace Microsoft.Tools.ServiceModel.ComSvcConfig { using System; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.Collections; using System.Collections.Specialized; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Globalization; using System.Text; using System.Threading; using System.Reflection; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Security.Principal; using System.ServiceModel; using Microsoft.Tools.ServiceModel; using Microsoft.Tools.ServiceModel.SvcUtil; using System.Configuration; [ComImport] [Guid("33CAF1A1-FCB8-472b-B45E-967448DED6D8")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IServiceSysTxnConfig { } [ComImport] [Guid("ecabb0c8-7f19-11d2-978e-0000f8757e2a")] class CServiceConfig { } public static class Tool { static Options options; internal static Options Options { get { return options; } } // const string DefaultBindingName = "HttpDuplexWindowsSecurityBinding"; internal static Exception CreateArgumentException(string command, string arg, string message, Exception innerException) { return new ArgumentException(SR.GetString(SR.InvalidArg, command, arg, message), innerException); } internal static Exception CreateException(string message, Exception innerException) { return new ApplicationException(message, innerException); } // returns whether help was displayed static void DisplayHelp(Mode mode) { if (options.Mode == Mode.NotSpecified) { DisplayUsage(); } else if (options.Mode == Mode.Install) { ToolConsole.WriteLine(SR.GetString(SR.HelpUsage4, Cmd.Install, Abbr.Install)); ToolConsole.WriteLine(SR.GetString(SR.HelpUsageExamples)); ToolConsole.WriteLine(" ComSvcConfig.exe /install /application:TestApp /contract:* /hosting:complus"); ToolConsole.WriteLine(" ComSvcConfig.exe /install /application:TestApp /contract:TestComponent,ITest /hosting:was /webDirectory:testdir /mex"); ToolConsole.WriteLine(" ComSvcConfig.exe /install /application:TestApp /contract:TestComponent,ITest.{Method1} /hosting:was /webDirectory:testdir /mex"); ToolConsole.WriteLine(" ComSvcConfig.exe /install /application:TestApp /contract:TestComponent,ITest.{Method2,Method3} /hosting:was /webDirectory:testdir /mex"); } else if (options.Mode == Mode.Uninstall) { ToolConsole.WriteLine(SR.GetString(SR.HelpUsage5, Cmd.Uninstall, Abbr.Uninstall)); ToolConsole.WriteLine(SR.GetString(SR.HelpUsageExamples)); ToolConsole.WriteLine(" ComSvcConfig.exe /uninstall /application:OnlineStore /contract:* /hosting:complus"); ToolConsole.WriteLine(" ComSvcConfig.exe /uninstall /application:OnlineStore /contract:* /hosting:was /mex"); ToolConsole.WriteLine(" ComSvcConfig.exe /uninstall /application:OnlineStore /contract:TestComponent,ITest.{Method1} /hosting:was /mex"); ToolConsole.WriteLine(" ComSvcConfig.exe /uninstall /application:OnlineStore /contract:TestComponent,ITest.{Method2,Method3} /hosting:was /mex"); } else if (options.Mode == Mode.List) { ToolConsole.WriteLine(SR.GetString(SR.HelpUsage6, Cmd.List, Abbr.List)); ToolConsole.WriteLine(SR.GetString(SR.HelpUsageExamples)); ToolConsole.WriteLine(" ComSvcConfig.exe /list"); ToolConsole.WriteLine(" ComSvcConfig.exe /list /hosting:complus"); ToolConsole.WriteLine(" ComSvcConfig.exe /list /hosting:was"); } } static void DisplayLogo() { // Using CommonResStrings.WcfTrademarkForCmdLine for the trademark: the proper resource for command line tools. Console.WriteLine(SR.GetString(SR.Logo, CommonResStrings.WcfTrademarkForCmdLine, ThisAssembly.InformationalVersion, CommonResStrings.CopyrightForCmdLine)); } static void DisplayUsage() { ToolConsole.WriteLine(SR.GetString(SR.HelpUsage1)); ToolConsole.WriteLine(SR.GetString(SR.HelpUsage2, ThisAssembly.Title)); ToolConsole.WriteLine(SR.GetString(SR.HelpUsage3)); ToolConsole.WriteLine(SR.GetString(SR.HelpUsage4, Cmd.Install, Abbr.Install)); ToolConsole.WriteLine(SR.GetString(SR.HelpUsage5, Cmd.Uninstall, Abbr.Uninstall)); ToolConsole.WriteLine(SR.GetString(SR.HelpUsage6, Cmd.List, Abbr.List)); ToolConsole.WriteLine(SR.GetString(SR.HelpUsage7)); ToolConsole.WriteLine(SR.GetString(SR.HelpUsageApplication, Cmd.Application, Abbr.Application)); ToolConsole.WriteLine(SR.GetString(SR.HelpUsageInterface, Cmd.Contract, Abbr.Contract, "{", "}")); ToolConsole.WriteLine(SR.GetString(SR.HelpUsageReferences, Cmd.AllowReferences, Abbr.AllowReferences)); ToolConsole.WriteLine(SR.GetString(SR.HelpUsageHosting, Cmd.Hosting, Abbr.Hosting)); ToolConsole.WriteLine(SR.GetString(SR.HelpUsageWebServer, Cmd.WebServer, Abbr.WebServer)); ToolConsole.WriteLine(SR.GetString(SR.HelpUsageWebDirectory, Cmd.WebDirectory, Abbr.WebDirectory)); ToolConsole.WriteLine(SR.GetString(SR.HelpUsageMexOption, Cmd.MetaData, Abbr.MetaData)); ToolConsole.WriteLine(SR.GetString(SR.HelpUsageGuidOption, Cmd.ID, Abbr.ID)); ToolConsole.WriteLine(SR.GetString(SR.HelpUsageNoLogo, Cmd.NoLogo, Abbr.NoLogo)); ToolConsole.WriteLine(SR.GetString(SR.HelpUsageVerbose, Cmd.Verbose, Abbr.Verbose)); ToolConsole.WriteLine(SR.GetString(SR.HelpUsage8, "help")); ToolConsole.WriteLine(SR.GetString(SR.HelpUsageExamples)); ToolConsole.WriteLine(" ComSvcConfig.exe /install /application:TestApp /contract:* /hosting:complus"); ToolConsole.WriteLine(" ComSvcConfig.exe /install /application:TestApp /contract:TestComponent,ITest /hosting:was /webDirectory:testdir /mex"); ToolConsole.WriteLine(" ComSvcConfig.exe /list"); ToolConsole.WriteLine(" ComSvcConfig.exe /list /hosting:complus"); ToolConsole.WriteLine(" ComSvcConfig.exe /list /hosting:was"); ToolConsole.WriteLine(" ComSvcConfig.exe /uninstall /application:OnlineStore /contract:* /hosting:complus"); ToolConsole.WriteLine(" ComSvcConfig.exe /uninstall /application:OnlineStore /contract:* /hosting:was"); ToolConsole.WriteLine(""); } static void DoInstall() { ValidateAddParams(); ComAdminAppInfo appInfo = ComAdminWrapper.GetAppInfo(options.Application); if (appInfo == null) { throw CreateArgumentException(Cmd.Application, options.Application, SR.GetString(SR.ApplicationNotFound, options.Application), null); } ValidateApplication(appInfo, options.Hosting); Guid sourceAppId = appInfo.ID; EndpointConfigContainer container = null; if (options.Hosting == Hosting.Complus) { container = ComplusEndpointConfigContainer.Get(options.Application, true); if (container == null) { throw CreateArgumentException(Cmd.Application, options.Application, SR.GetString(SR.ApplicationNotFound, options.Application), null); } } else if (options.Hosting == Hosting.Was) { string webServer = null; if (options.WebServer != null) { webServer = options.WebServer; } else { webServer = WasEndpointConfigContainer.DefaultWebServer; } container = WasEndpointConfigContainer.Get(webServer, options.WebDirectory, options.Application); if (container == null) { throw CreateArgumentException(Cmd.WebDirectory, options.WebDirectory, SR.GetString(SR.WebDirectoryNotFound, options.WebDirectory), null); } } IList<ComponentDefinition<Guid>> guidComponents = null; if (options.AllComponents) { GetAllComponentsForAdd(appInfo, options.Mex, out guidComponents); } else { GetComponentsFromInputForAdd(appInfo, options.Components, options.Mex, container.HasEndpointsForApplication(sourceAppId), out guidComponents); } if (guidComponents.Count == 0) { if (String.Empty != options.MexOnlyComponent) throw Tool.CreateException(SR.GetString(SR.MexOnlyComponentHasNoExposedInterface, options.MexOnlyComponent), null); else throw Tool.CreateException(SR.GetString(SR.NoneOfTheComponentsSatisfiedTheAddCriteria), null); } List<EndpointConfig> endpointConfigs = new List<EndpointConfig>(); foreach (ComponentDefinition<Guid> component in guidComponents) { ComAdminClassInfo componentInfo = appInfo.FindClass(component.Component.ToString("B")); Debug.Assert(componentInfo != null, "No component Found"); string bindingType = null; string bindingName = null; if (!componentInfo.SupportsTransactionFlow) { bindingType = container.DefaultBindingType; bindingName = container.DefaultBindingName; } else { bindingType = container.DefaultTransactionalBindingType; bindingName = container.DefaultTransactionalBindingName; } foreach (InterfaceDefination<Guid> iInterface in component.Interfaces) { Guid iid = iInterface.Interface; EndpointConfig ec = null; if (iid != typeof(IMetadataExchange).GUID) { string address = container.DefaultEndpointAddress(sourceAppId, component.Component, iid); ec = new EndpointConfig(sourceAppId, component.Component, iid, bindingType, bindingName, new Uri(address, UriKind.RelativeOrAbsolute), false, (List<string>)iInterface.Methods); } else { ec = new EndpointConfig(sourceAppId, component.Component, typeof(IMetadataExchange).GUID, container.DefaultMexBindingType, container.DefaultMexBindingName, new Uri(container.DefaultMexAddress(sourceAppId, component.Component), UriKind.RelativeOrAbsolute), true, null); } endpointConfigs.Add(ec); } } try { container.Add(endpointConfigs); container.PrepareChanges(); // containers can throw from this } catch (Exception e) { if (e is NullReferenceException || e is SEHException) { throw; } container.AbortChanges(); throw CreateException(SR.GetString(SR.ErrorDuringAdd, options.Application), e); } container.CommitChanges(); } // Assumption is that application, if present, is in curly Guids form static List<EndpointConfigContainer> GetContainersForQueryOrRemove(Hosting hosting, string application, string webServer, string webDirectory) { List<EndpointConfigContainer> containers = new List<EndpointConfigContainer>(); // first, get any complus-hosted endpointConfigs if (hosting == Hosting.Complus || hosting == Hosting.NotSpecified) { if (!string.IsNullOrEmpty(application)) { EndpointConfigContainer container = ComplusEndpointConfigContainer.Get(application); if (container == null) { throw CreateArgumentException(Cmd.Application, options.Application, SR.GetString(SR.ApplicationNotFound, options.Application), null); } containers.Add(container); } else { // query for all complus-hosted apps List<ComplusEndpointConfigContainer> comContainers = ComplusEndpointConfigContainer.Get(); if (comContainers != null) { foreach (ComplusEndpointConfigContainer comContainer in comContainers) { containers.Add(comContainer); } } } } // then, get any was-hosted endpointConfigs if (hosting == Hosting.Was || hosting == Hosting.NotSpecified) { // specific webDirectory if (!string.IsNullOrEmpty(webDirectory)) { if (string.IsNullOrEmpty(webServer)) { webServer = WasEndpointConfigContainer.DefaultWebServer; } EndpointConfigContainer container = WasEndpointConfigContainer.Get(webServer, webDirectory, application); if (container == null) { throw CreateArgumentException(Cmd.WebDirectory, options.WebDirectory, SR.GetString(SR.WebDirectoryNotFound, options.WebDirectory), null); } if (string.IsNullOrEmpty(application)) { containers.Add(container); } else { if (container.HasEndpointsForApplication(new Guid(application))) { containers.Add(container); } } } else { // no webDirectory specified. // we will therefore look in all webDirs, in all webServers (unless one is specified) List<WasEndpointConfigContainer> wasContainers = null; if (!string.IsNullOrEmpty(webServer)) { wasContainers = WasEndpointConfigContainer.Get(webServer, application); // all webDirs in a specific server } else { wasContainers = WasEndpointConfigContainer.Get(application); // all webDirs in all servers } if (wasContainers != null) { foreach (WasEndpointConfigContainer container in wasContainers) { if (string.IsNullOrEmpty(application)) { containers.Add(container); } else { if (container.HasEndpointsForApplication(new Guid(application))) { containers.Add(container); } } } } } } return containers; } static void DisplayEndpointConfig(EndpointConfig config) { List<string> baseAddresses = null; if (config.Container != null) { baseAddresses = config.Container.GetBaseAddresses(config); } if (null == baseAddresses || 0 == baseAddresses.Count) { if (config.IsMexEndpoint) ToolConsole.WriteQueryLine(" " + SR.GetString(SR.MexEndpointExposed, config.Address)); else { ToolConsole.WriteQueryLine(" " + SR.GetString(SR.BindingType, config.BindingType)); ToolConsole.WriteQueryLine(" " + SR.GetString(SR.BindingConfigurationName, config.BindingName)); ToolConsole.WriteQueryLine(" " + SR.GetString(SR.Address, config.Address)); } } else { foreach (string s in baseAddresses) { string addr = s + @"/" + config.Address; if (config.IsMexEndpoint) ToolConsole.WriteQueryLine(" " + SR.GetString(SR.MexEndpointExposed, addr)); else { ToolConsole.WriteQueryLine(" " + SR.GetString(SR.BindingType, config.BindingType)); ToolConsole.WriteQueryLine(" " + SR.GetString(SR.BindingConfigurationName, config.BindingName)); ToolConsole.WriteQueryLine(" " + SR.GetString(SR.Address, addr)); } } } } static void DoList() { ValidateQueryParams(); string application = null; Guid appid; if (options.Application != null) { // Make sure that the application exists, and get its Guid if (!ComAdminWrapper.ResolveApplicationId(options.Application, out appid)) { throw CreateArgumentException(Cmd.Application, options.Application, SR.GetString(SR.ApplicationNotFound, options.Application), null); } application = appid.ToString("B"); } List<EndpointConfig> endpointConfigs = new List<EndpointConfig>(); List<EndpointConfigContainer> containers = GetContainersForQueryOrRemove(options.Hosting, application, options.WebServer, options.WebDirectory); if (containers != null) { foreach (EndpointConfigContainer container in containers) { try { List<EndpointConfig> configs = null; if (!string.IsNullOrEmpty(application)) { configs = container.GetEndpointConfigs(new Guid(application)); } else { configs = container.GetEndpointConfigs(); } endpointConfigs.AddRange(configs); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception) { if (container is WasEndpointConfigContainer) ToolConsole.WriteWarning(SR.GetString(SR.InvalidConfigFile, ((WasEndpointConfigContainer)container).ConfigFile.OriginalFileName)); if (container is ComplusEndpointConfigContainer) ToolConsole.WriteWarning(SR.GetString(SR.InvalidConfigFile, ((ComplusEndpointConfigContainer)container).ConfigFile.OriginalFileName)); } } } Dictionary<Guid, Dictionary<Guid, Dictionary<Guid, List<EndpointConfig>>>> applicationToComponents = new Dictionary<Guid, Dictionary<Guid, Dictionary<Guid, List<EndpointConfig>>>>(); foreach (EndpointConfig config in endpointConfigs) { Dictionary<Guid, Dictionary<Guid, List<EndpointConfig>>> componentToInterfaces = null; Dictionary<Guid, List<EndpointConfig>> interfacesForComponents = null; List<EndpointConfig> endpointsForInterface = null; if (!applicationToComponents.TryGetValue(config.Appid, out componentToInterfaces)) { componentToInterfaces = new Dictionary<Guid, Dictionary<Guid, List<EndpointConfig>>>(); applicationToComponents[config.Appid] = componentToInterfaces; } if (!componentToInterfaces.TryGetValue(config.Clsid, out interfacesForComponents)) { interfacesForComponents = new Dictionary<Guid, List<EndpointConfig>>(); componentToInterfaces[config.Clsid] = interfacesForComponents; } if (!interfacesForComponents.TryGetValue(config.Iid, out endpointsForInterface)) { endpointsForInterface = new List<EndpointConfig>(); interfacesForComponents[config.Iid] = endpointsForInterface; } endpointsForInterface.Add(config); } IEnumerator<KeyValuePair<Guid, Dictionary<Guid, Dictionary<Guid, List<EndpointConfig>>>>> enumerateApps = applicationToComponents.GetEnumerator(); while (enumerateApps.MoveNext()) { IEnumerator<KeyValuePair<Guid, Dictionary<Guid, List<EndpointConfig>>>> enumerateComponents = enumerateApps.Current.Value.GetEnumerator(); ComAdminAppInfo appInfo = ComAdminWrapper.GetAppInfo(enumerateApps.Current.Key.ToString("B")); if (appInfo == null) continue; ToolConsole.WriteQueryLine(SR.GetString(SR.EnumeratingComponentsForApplication, options.ShowGuids ? appInfo.ID.ToString("B") : appInfo.Name)); foreach (EndpointConfigContainer container in containers) { if (container.HasEndpointsForApplication(enumerateApps.Current.Key)) { if (container is WasEndpointConfigContainer) { ToolConsole.WriteQueryLine(" " + SR.GetString(SR.WasHosting)); ToolConsole.WriteQueryLine(" " + SR.GetString(SR.ConfigFileName, ((WasEndpointConfigContainer)container).ConfigFile.OriginalFileName)); } else { ToolConsole.WriteQueryLine(" " + SR.GetString(SR.ComplusHosting)); ToolConsole.WriteQueryLine(" " + SR.GetString(SR.ConfigFileName, ((ComplusEndpointConfigContainer)container).ConfigFile.OriginalFileName)); } } } while (enumerateComponents.MoveNext()) { IEnumerator<KeyValuePair<Guid, List<EndpointConfig>>> enumerateInterfaces = enumerateComponents.Current.Value.GetEnumerator(); ComAdminClassInfo classInfo = appInfo.FindClass(enumerateComponents.Current.Key.ToString("B")); if (classInfo == null) continue; ToolConsole.WriteQueryLine(" " + SR.GetString(SR.EnumeratingInterfacesForComponent, options.ShowGuids ? classInfo.Clsid.ToString("B") : classInfo.Name)); while (enumerateInterfaces.MoveNext()) { ComAdminInterfaceInfo interfaceInfo = classInfo.FindInterface(enumerateInterfaces.Current.Key.ToString("B")); if (interfaceInfo == null) { foreach (EndpointConfig config in enumerateInterfaces.Current.Value) { if (config.IsMexEndpoint) { DisplayEndpointConfig(config); continue; } } } else { ToolConsole.WriteQueryLine(" " + SR.GetString(SR.EnumeratingEndpointsForInterfaces, options.ShowGuids ? interfaceInfo.Iid.ToString("B") : interfaceInfo.Name)); foreach (EndpointConfig config in enumerateInterfaces.Current.Value) DisplayEndpointConfig(config); } } } } } static void DoUninstall() { ValidateRemoveParams(); ComAdminAppInfo appInfo = ComAdminWrapper.GetAppInfo(options.Application); if (appInfo == null) { throw CreateArgumentException(Cmd.Application, options.Application, SR.GetString(SR.ApplicationNotFound, options.Application), null); } //ValidateApplication(appInfo, options.Hosting); Guid sourceAppId = appInfo.ID; string application = sourceAppId.ToString("B"); IList<ComponentDefinition<Guid>> guidComponents = null; if (options.AllComponents) { GetAllComponentsForRemove(appInfo, out guidComponents); } else { GetComponentsFromInputForRemove(appInfo, options.Components, out guidComponents); } List<EndpointConfigContainer> containers = GetContainersForQueryOrRemove(options.Hosting, application, options.WebServer, options.WebDirectory); if (guidComponents.Count == 0) ToolConsole.WriteWarning(SR.GetString(SR.NoneOfTheComponentsSatisfiedTheRemoveCriteria)); try { bool update = false; foreach (EndpointConfigContainer container in containers) { List<EndpointConfig> endpointsToDelete = new List<EndpointConfig>(); List<EndpointConfig> endpointConfigs = container.GetEndpointConfigs(sourceAppId); foreach (EndpointConfig endpointConfig in endpointConfigs) { if (ShouldDelete(endpointConfig, guidComponents)) { endpointsToDelete.Add(endpointConfig); } } if (endpointsToDelete.Count != 0) { container.Remove(endpointsToDelete); update = true; } } if (!update) ToolConsole.WriteWarning(SR.GetString(SR.NoneOfConfigsFoundMatchTheCriteriaSpecifiedNothingWillBeRemoved)); foreach (EndpointConfigContainer container in containers) { container.PrepareChanges(); // containers are allowed to throw from Prepare } } catch (Exception e) { if (e is NullReferenceException || e is SEHException) { throw; } foreach (EndpointConfigContainer container in containers) { container.AbortChanges(); // containers shouldn't throw from here } throw CreateException(SR.GetString(SR.ErrorDuringRemove), e); } // Commit time! foreach (EndpointConfigContainer container in containers) { container.CommitChanges(); // containers shouldn't throw from here } } static bool ShouldDelete(EndpointConfig endpointConfig, IList<ComponentDefinition<Guid>> guidComponents) { foreach (ComponentDefinition<Guid> component in guidComponents) { if (component.Component == endpointConfig.Clsid) { foreach (InterfaceDefination<Guid> interfaceDef in component.Interfaces) { if (interfaceDef.Interface == endpointConfig.Iid) { endpointConfig.Methods = interfaceDef.Methods; return true; } } } } return false; } static void EnsureUserIsAdministrator() { WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); if (!principal.IsInRole(WindowsBuiltInRole.Administrator)) { throw CreateException(SR.GetString(SR.MustBeAnAdministrator), null); } } // returns strongly typed, verified components/interfaces in an application static void GetAllComponentsForAdd(ComAdminAppInfo appInfo, bool mex, out IList<ComponentDefinition<Guid>> outComps) { outComps = new List<ComponentDefinition<Guid>>(); foreach (ComAdminClassInfo classInfo in appInfo.Classes) { ComponentDefinition<Guid> outComp; if (!ValidateClass(classInfo)) { continue; } outComp = new ComponentDefinition<Guid>(classInfo.Clsid); foreach (ComAdminInterfaceInfo interfaceInfo in classInfo.Interfaces) { if (ComPlusTypeValidator.VerifyInterface(interfaceInfo, options.AllowReferences, classInfo.Clsid)) outComp.AddInterface(interfaceInfo.Iid, ComPlusTypeValidator.FetchAllMethodsForInterface(interfaceInfo)); } if (mex && (outComp.Interfaces != null)) outComp.AddInterface(typeof(IMetadataExchange).GUID, null); if (outComp.Interfaces != null) outComps.Add(outComp); else ToolConsole.WriteWarning(SR.GetString(SR.NoneOfTheSpecifiedInterfacesForComponentWereFoundSkipping, Tool.Options.ShowGuids ? classInfo.Clsid.ToString("B") : classInfo.Name)); } } // returns strongly typed, verified components/interfaces in an application static void GetAllComponentsForRemove(ComAdminAppInfo appInfo, out IList<ComponentDefinition<Guid>> outComps) { outComps = new List<ComponentDefinition<Guid>>(); foreach (ComAdminClassInfo classInfo in appInfo.Classes) { ComponentDefinition<Guid> outComp; outComp = new ComponentDefinition<Guid>(classInfo.Clsid); foreach (ComAdminInterfaceInfo interfaceInfo in classInfo.Interfaces) outComp.AddInterface(interfaceInfo.Iid, null); outComp.AddInterface(typeof(IMetadataExchange).GUID, null); outComps.Add(outComp); } } // returns strongly typed, verified components, from loosely-typed (string) user inputs static void GetComponentsFromInputForAdd(ComAdminAppInfo appInfo, IList<ComponentDefinition<string>> inComps, bool mex, bool priorEndpointsExist, out IList<ComponentDefinition<Guid>> outComps) { string missingInterface = String.Empty; outComps = new List<ComponentDefinition<Guid>>(); foreach (ComponentDefinition<string> inComp in inComps) { ComponentDefinition<Guid> outComp = null; ComAdminClassInfo classInfo = appInfo.FindClass(inComp.Component); if (classInfo == null) { ToolConsole.WriteWarning(SR.GetString(SR.CannotFindComponentInApplicationSkipping, inComp.Component, Tool.Options.ShowGuids ? appInfo.ID.ToString("B") : appInfo.Name)); continue; } if (!ValidateClass(classInfo)) continue; // Find existing componentDef if it was referenced in an earlier iteration foreach (ComponentDefinition<Guid> cd in outComps) { if (cd.Component == classInfo.Clsid) { outComp = cd; } } if (outComp == null) { outComp = new ComponentDefinition<Guid>(classInfo.Clsid); } if (inComp.AllInterfaces) { foreach (ComAdminInterfaceInfo interfaceInfo in classInfo.Interfaces) { if (ComPlusTypeValidator.VerifyInterface(interfaceInfo, options.AllowReferences, classInfo.Clsid)) outComp.AddInterface(interfaceInfo.Iid, ComPlusTypeValidator.FetchAllMethodsForInterface(interfaceInfo)); } if ((outComp.Interfaces != null) && mex) outComp.AddInterface(typeof(IMetadataExchange).GUID, null); } else { foreach (InterfaceDefination<string> comInterface in inComp.Interfaces) { string itfName = comInterface.Interface; if (itfName == typeof(IMetadataExchange).GUID.ToString("B")) { if (!mex) outComp.AddInterface(typeof(IMetadataExchange).GUID, null); } else { ComAdminInterfaceInfo interfaceInfo = classInfo.FindInterface(itfName); if (interfaceInfo == null) { ToolConsole.WriteWarning(SR.GetString(SR.CannotFindInterfaceInCatalogForComponentSkipping, itfName, inComp.Component)); missingInterface = itfName; continue; } if (comInterface.AllMethods) { if (ComPlusTypeValidator.VerifyInterface(interfaceInfo, options.AllowReferences, classInfo.Clsid, true)) outComp.AddInterface(interfaceInfo.Iid, ComPlusTypeValidator.FetchAllMethodsForInterface(interfaceInfo)); else throw CreateException(SR.GetString(SR.InvalidInterface), null); } else { if (ComPlusTypeValidator.VerifyInterfaceMethods(interfaceInfo, comInterface.Methods, options.AllowReferences, true)) outComp.AddInterface(interfaceInfo.Iid, (List<string>)comInterface.Methods); else throw CreateException(SR.GetString(SR.InvalidMethod), null); } } } if ((outComp.Interfaces != null) || priorEndpointsExist) { if (mex) outComp.AddInterface(typeof(IMetadataExchange).GUID, null); } } if (outComp.Interfaces != null) outComps.Add(outComp); else ToolConsole.WriteWarning(SR.GetString(SR.NoneOfTheSpecifiedInterfacesForComponentWereFoundSkipping, inComp.Component)); } if (outComps.Count == 0 && (!String.IsNullOrEmpty(missingInterface))) throw Tool.CreateException(SR.GetString(SR.NoComponentContainsInterface, missingInterface), null); } static void GetComponentsFromInputForRemove(ComAdminAppInfo appInfo, IList<ComponentDefinition<string>> inComps, out IList<ComponentDefinition<Guid>> outComps) { outComps = new List<ComponentDefinition<Guid>>(); foreach (ComponentDefinition<string> inComp in inComps) { ComponentDefinition<Guid> outComp = null; ComAdminClassInfo classInfo = appInfo.FindClass(inComp.Component); if (classInfo == null) { ToolConsole.WriteWarning(SR.GetString(SR.CannotFindComponentInApplicationSkipping, inComp.Component, Tool.Options.ShowGuids ? appInfo.ID.ToString("B") : appInfo.Name)); continue; } // Find existing componentDef if it was referenced in an earlier iteration foreach (ComponentDefinition<Guid> cd in outComps) { if (cd.Component == classInfo.Clsid) { outComp = cd; } } if (outComp == null) { outComp = new ComponentDefinition<Guid>(classInfo.Clsid); } if (inComp.AllInterfaces) { foreach (ComAdminInterfaceInfo interfaceInfo in classInfo.Interfaces) outComp.AddInterface(interfaceInfo.Iid, ComPlusTypeValidator.FetchAllMethodsForInterface(interfaceInfo, false)); outComp.AddInterface(typeof(IMetadataExchange).GUID, null); } else { foreach (InterfaceDefination<string> comInterface in inComp.Interfaces) { string itfName = comInterface.Interface; if (itfName == typeof(IMetadataExchange).GUID.ToString("B")) { outComp.AddInterface(typeof(IMetadataExchange).GUID, null); } else { ComAdminInterfaceInfo interfaceInfo = classInfo.FindInterface(itfName); if (interfaceInfo == null) { ToolConsole.WriteWarning(SR.GetString(SR.CannotFindInterfaceInCatalogForComponentSkipping, itfName, inComp.Component)); continue; } if (comInterface.AllMethods) { outComp.AddInterface(interfaceInfo.Iid, ComPlusTypeValidator.FetchAllMethodsForInterface(interfaceInfo)); } else { outComp.AddInterface(interfaceInfo.Iid, (List<string>)comInterface.Methods); } } } } if (outComp.Interfaces != null) outComps.Add(outComp); else { ToolConsole.WriteWarning(SR.GetString(SR.NoneOfTheSpecifiedInterfacesForComponentWereFoundSkipping, inComp.Component)); } } } public static bool CheckForCorrectOle32() { Guid clsid = new Guid("0000032E-0000-0000-C000-000000000046"); IPSFactoryBuffer psFac = SafeNativeMethods.DllGetClassObject(clsid, typeof(IPSFactoryBuffer).GUID) as IPSFactoryBuffer; object o1; object o2; try { psFac.CreateProxy(IntPtr.Zero, clsid, out o1, out o2); } catch (ArgumentException) { return true; } catch (COMException) { return false; } return false; } public static int Main(string[] args) { // make sure the text output displays properly on various languages Thread.CurrentThread.CurrentUICulture = CultureInfo.CurrentUICulture.GetConsoleFallbackUICulture(); if ((System.Console.OutputEncoding.CodePage != 65001) && (System.Console.OutputEncoding.CodePage != Thread.CurrentThread.CurrentUICulture.TextInfo.OEMCodePage)) { Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); } object serviceConfig = new CServiceConfig(); IServiceSysTxnConfig sysTxnconfing = serviceConfig as IServiceSysTxnConfig; if (sysTxnconfing == null) { ToolConsole.WriteError(SR.GetString(SR.WindowsFunctionalityMissing), ""); return 1; } if ((Environment.OSVersion.Version.Major == 5) && (Environment.OSVersion.Version.Minor == 1)) { if (!CheckForCorrectOle32()) { ToolConsole.WriteError(SR.GetString(SR.WindowsFunctionalityMissing), ""); return 1; } } try { EnsureUserIsAdministrator(); Tool.options = Options.ParseArguments(args); ToolConsole.Verbose = options.Verbose; Run(); } catch (ArgumentException ae) { ToolConsole.WriteError(ae); Console.WriteLine(SR.GetString(SR.MoreHelp, Abbr.Help)); return 1; } catch (ApplicationException appException) { ToolConsole.WriteError(appException); return 1; } catch (Exception e) { if (e is NullReferenceException || e is SEHException) { throw; } ToolConsole.WriteDetailedException(e, SR.GetString(SR.UnExpectedError)); return 1; } return 0; } static void Run() { if (!options.NoLogo) { DisplayLogo(); } if (options.Help) { ToolConsole.Verbose = false; // For Help-mode, ignore quiet flag DisplayHelp(options.Mode); return; } switch (options.Mode) { case Mode.NotSpecified: { throw CreateArgumentException(Cmd.Mode, "", SR.GetString(SR.ArgumentRequired, Cmd.Mode), null); } case Mode.Install: { DoInstall(); break; } case Mode.Uninstall: { DoUninstall(); break; } case Mode.List: { DoList(); break; } default: { Debug.Assert(false, "unknown mode"); break; } } } static void ValidateAddParams() { if (options.Application == null) { throw CreateArgumentException(Cmd.Application, null, SR.GetString(SR.ArgumentRequired, Cmd.Application), null); } if (!options.AllComponents && ((options.Components == null) || options.Components.Count == 0)) { throw CreateArgumentException(Cmd.Contract, null, SR.GetString(SR.ArgumentRequired, Cmd.Contract), null); } switch (options.Hosting) { case Hosting.NotSpecified: { throw CreateArgumentException(Cmd.Hosting, null, SR.GetString(SR.ArgumentRequired, Cmd.Hosting), null); } case Hosting.Complus: { if (options.WebDirectory != null) { throw CreateArgumentException(Cmd.WebDirectory, options.WebDirectory, SR.GetString(SR.InvalidArgumentForHostingMode, Cmd.WebDirectory), null); } if (options.WebServer != null) { throw CreateArgumentException(Cmd.WebServer, options.WebServer, SR.GetString(SR.InvalidArgumentForHostingMode, Cmd.WebServer), null); } break; } case Hosting.Was: { if (options.WebDirectory == null) { throw CreateArgumentException(Cmd.WebDirectory, null, SR.GetString(SR.ArgumentRequired, Cmd.WebDirectory), null); } break; } } } static void ValidateRemoveParams() { if (options.Application == null) { throw CreateArgumentException(Cmd.Application, null, SR.GetString(SR.ArgumentRequired, Cmd.Application), null); } if (!options.AllComponents && ((options.Components == null) || options.Components.Count == 0)) { throw CreateArgumentException(Cmd.Contract, null, SR.GetString(SR.ArgumentRequired, Cmd.Contract), null); } switch (options.Hosting) { case Hosting.NotSpecified: { if (options.WebDirectory != null) { throw CreateArgumentException(Cmd.WebDirectory, options.WebDirectory, SR.GetString(SR.InvalidArgumentForHostingMode, Cmd.WebDirectory), null); } break; } case Hosting.Complus: { if (options.WebDirectory != null) { throw CreateArgumentException(Cmd.WebDirectory, options.WebDirectory, SR.GetString(SR.InvalidArgumentForHostingMode, Cmd.WebDirectory), null); } if (options.WebServer != null) { throw CreateArgumentException(Cmd.WebServer, options.WebServer, SR.GetString(SR.InvalidArgumentForHostingMode, Cmd.WebServer), null); } break; } case Hosting.Was: { break; } } } static void ValidateQueryParams() { if (options.AllComponents || ((options.Components != null) && options.Components.Count > 0)) { throw CreateArgumentException(Cmd.Contract, null, SR.GetString(SR.ExclusiveOptionsSpecified, Cmd.Contract, Cmd.Mode + ":query"), null); } switch (options.Hosting) { case Hosting.NotSpecified: { if (options.WebDirectory != null) { throw CreateArgumentException(Cmd.WebDirectory, options.WebDirectory, SR.GetString(SR.InvalidArgumentForHostingMode, Cmd.WebDirectory), null); } break; } case Hosting.Complus: { if (options.WebDirectory != null) { throw CreateArgumentException(Cmd.WebDirectory, options.WebDirectory, SR.GetString(SR.InvalidArgumentForHostingMode, Cmd.WebDirectory), null); } if (options.WebServer != null) { throw CreateArgumentException(Cmd.WebServer, options.WebServer, SR.GetString(SR.InvalidArgumentForHostingMode, Cmd.WebServer), null); } break; } case Hosting.Was: { break; } } } static void ValidateApplication(ComAdminAppInfo appInfo, Hosting hosting) { if (appInfo.IsSystemApplication) { throw CreateArgumentException(Cmd.Application, appInfo.Name, SR.GetString(SR.SystemApplicationsNotSupported), null); } if (hosting == Hosting.Complus) { if (!appInfo.IsServerActivated) { throw CreateArgumentException(Cmd.Application, appInfo.Name, SR.GetString(SR.LibraryApplicationsNotSupported), null); } if (appInfo.IsAutomaticRecycling) { throw CreateArgumentException(Cmd.Application, appInfo.Name, SR.GetString(SR.ProcessRecyclingNotSupported), null); } if (appInfo.IsProcessPooled) { throw CreateArgumentException(Cmd.Application, appInfo.Name, SR.GetString(SR.ProcessPoolingNotSupported), null); } } } static bool ValidateClass(ComAdminClassInfo classInfo) { if (classInfo.IsPrivate) { ToolConsole.WriteWarning(SR.GetString(SR.CannotExposePrivateComponentsSkipping, Tool.Options.ShowGuids ? classInfo.Clsid.ToString("B") : classInfo.Name)); return false; } return true; } } }
using DevExpress.Mvvm; using DevExpress.Mvvm.Native; using DevExpress.Mvvm.POCO; using DevExpress.Mvvm.UI; using DevExpress.Mvvm.UI.Interactivity; using DevExpress.Mvvm.UI.Tests; using DevExpress.Utils; using NUnit.Framework; using System; using System.ComponentModel; using System.Reflection; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Media; using System.Windows.Shell; using System.Windows.Input; namespace DevExpress.Mvvm.UI.Tests { [TestFixture] public class TaskbarButtonServiceTests : BaseWpfFixture { double clipMarginShift = 0.0; bool getThumbnailClipMarginExecute = false; protected override void SetUpCore() { base.SetUpCore(); ApplicationJumpListServiceTestsImageSourceHelper.RegisterPackScheme(); clipMarginShift = 0.0; getThumbnailClipMarginExecute = false; } protected override void TearDownCore() { RealWindow.TaskbarItemInfo = null; Interaction.GetBehaviors(RealWindow).Clear(); base.TearDownCore(); } [Test] public void SetProgressIndicatorState() { TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); EnqueueShowRealWindow(); ITaskbarButtonService taskbarService = taskbarServiceImpl; taskbarService.ProgressState = TaskbarItemProgressState.Indeterminate; Assert.AreEqual(TaskbarItemProgressState.Indeterminate, RealWindow.TaskbarItemInfo.ProgressState); taskbarService.ProgressState = TaskbarItemProgressState.None; Assert.AreEqual(TaskbarItemProgressState.None, RealWindow.TaskbarItemInfo.ProgressState); taskbarService.ProgressState = TaskbarItemProgressState.Normal; Assert.AreEqual(TaskbarItemProgressState.Normal, RealWindow.TaskbarItemInfo.ProgressState); taskbarService.ProgressState = TaskbarItemProgressState.Paused; Assert.AreEqual(TaskbarItemProgressState.Paused, RealWindow.TaskbarItemInfo.ProgressState); taskbarService.ProgressState = TaskbarItemProgressState.Error; Assert.AreEqual(TaskbarItemProgressState.Error, RealWindow.TaskbarItemInfo.ProgressState); } [Test] public void BindProgressIndicatorState() { VM vm = VM.Create(); RealWindow.DataContext = vm; TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); BindingOperations.SetBinding(taskbarServiceImpl, TaskbarButtonService.ProgressStateProperty, new Binding("ProgressState")); EnqueueShowRealWindow(); ITaskbarButtonService taskbarService = taskbarServiceImpl; vm.ProgressState = TaskbarItemProgressState.Indeterminate; Assert.AreEqual(TaskbarItemProgressState.Indeterminate, RealWindow.TaskbarItemInfo.ProgressState); vm.ProgressState = TaskbarItemProgressState.None; Assert.AreEqual(TaskbarItemProgressState.None, RealWindow.TaskbarItemInfo.ProgressState); vm.ProgressState = TaskbarItemProgressState.Normal; Assert.AreEqual(TaskbarItemProgressState.Normal, RealWindow.TaskbarItemInfo.ProgressState); vm.ProgressState = TaskbarItemProgressState.Paused; Assert.AreEqual(TaskbarItemProgressState.Paused, RealWindow.TaskbarItemInfo.ProgressState); vm.ProgressState = TaskbarItemProgressState.Error; Assert.AreEqual(TaskbarItemProgressState.Error, RealWindow.TaskbarItemInfo.ProgressState); } [Test] public void SetProgressIndicatorValue() { TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); EnqueueShowRealWindow(); ITaskbarButtonService taskbarService = taskbarServiceImpl; taskbarService.ProgressValue = 0.0; Assert.AreEqual(0, RealWindow.TaskbarItemInfo.ProgressValue); taskbarService.ProgressValue = 0.5; Assert.AreEqual(0.5, RealWindow.TaskbarItemInfo.ProgressValue); taskbarService.ProgressValue = 1.0; Assert.AreEqual(1, RealWindow.TaskbarItemInfo.ProgressValue); } [Test] public void BindProgressIndicatorValue() { VM vm = VM.Create(); RealWindow.DataContext = vm; TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); BindingOperations.SetBinding(taskbarServiceImpl, TaskbarButtonService.ProgressValueProperty, new Binding("ProgressValue")); EnqueueShowRealWindow(); ITaskbarButtonService taskbarService = taskbarServiceImpl; vm.ProgressValue = 0.0; Assert.AreEqual(0, RealWindow.TaskbarItemInfo.ProgressValue); vm.ProgressValue = 0.5; Assert.AreEqual(0.5, RealWindow.TaskbarItemInfo.ProgressValue); vm.ProgressValue = 1.0; Assert.AreEqual(1, RealWindow.TaskbarItemInfo.ProgressValue); } [Test] public void AttachToWindowChild() { Grid grid = new Grid(); RealWindow.Content = grid; TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(grid).Add(taskbarServiceImpl); EnqueueShowRealWindow(); ITaskbarButtonService taskbarService = taskbarServiceImpl; taskbarService.ProgressState = TaskbarItemProgressState.Paused; taskbarService.ProgressValue = 0.81; Assert.AreEqual(TaskbarItemProgressState.Paused, RealWindow.TaskbarItemInfo.ProgressState); Assert.AreEqual(0.81, RealWindow.TaskbarItemInfo.ProgressValue); } [Test] public void LateBoundWindow() { Grid grid = new Grid(); TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(grid).Add(taskbarServiceImpl); EnqueueShowRealWindow(); ITaskbarButtonService taskbarService = taskbarServiceImpl; taskbarService.ProgressState = TaskbarItemProgressState.Paused; taskbarService.ProgressValue = 0.81; RealWindow.Content = grid; DispatcherHelper.UpdateLayoutAndDoEvents(RealWindow); Assert.AreEqual(TaskbarItemProgressState.Paused, RealWindow.TaskbarItemInfo.ProgressState); Assert.AreEqual(0.81, RealWindow.TaskbarItemInfo.ProgressValue); } [Test] public void DoNotResetTaskBarItemInfoProperties() { RealWindow.TaskbarItemInfo = new TaskbarItemInfo() { Description = "desc" }; TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); EnqueueShowRealWindow(); ITaskbarButtonService taskbarService = taskbarServiceImpl; taskbarService.ProgressValue = 0.5; taskbarService.Description = "desc2"; Assert.AreEqual("desc2", RealWindow.TaskbarItemInfo.Description); Assert.AreEqual(0.5, RealWindow.TaskbarItemInfo.ProgressValue); } [Test] public void AttachServiceToWindowWithTaskbarButtonInfo() { ImageSource icon_1 = ApplicationJumpListServiceTestsImageSourceHelper.GetImageSource(AssemblyHelper.GetResourceUri(typeof(TaskbarButtonServiceTests).Assembly, "Icons/icon1.ico")); ImageSource icon_2 = ApplicationJumpListServiceTestsImageSourceHelper.GetImageSource(AssemblyHelper.GetResourceUri(typeof(TaskbarButtonServiceTests).Assembly, "Icons/icon2.png")); RealWindow.TaskbarItemInfo = new TaskbarItemInfo() { ProgressState = TaskbarItemProgressState.Paused, ProgressValue = 0.1, Description = "desc", Overlay = icon_1, ThumbButtonInfos = new ThumbButtonInfoCollection { new ThumbButtonInfo() { Description = "thumbButton1" } }, ThumbnailClipMargin = new Thickness { Left = 100, Top = 105, Right = 130, Bottom = 110 } }; TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService() { ProgressState = TaskbarItemProgressState.Error, ProgressValue = 0.2, Description = "desc2", OverlayIcon = icon_2, ThumbButtonInfos = new TaskbarThumbButtonInfoCollection { new TaskbarThumbButtonInfo() { Description = "thumbButton2" } }, ThumbnailClipMargin = new Thickness { Left = 50, Top = 555, Right = 135, Bottom = 90 } }; Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); EnqueueShowRealWindow(); Assert.AreEqual(TaskbarItemProgressState.Error, RealWindow.TaskbarItemInfo.ProgressState); Assert.AreEqual(0.2, RealWindow.TaskbarItemInfo.ProgressValue); Assert.AreEqual("desc2", RealWindow.TaskbarItemInfo.Description); AssertHelper.AssertEnumerablesAreEqual(new ThumbButtonInfo[] { new ThumbButtonInfo() { Description = "thumbButton2" }, }, RealWindow.TaskbarItemInfo.ThumbButtonInfos, true, new string[] { "Command" }); Assert.AreEqual(new Thickness { Left = 50, Top = 555, Right = 135, Bottom = 90 }, RealWindow.TaskbarItemInfo.ThumbnailClipMargin); } [Test] public void UpdateServicePropertiesOnWindowTaskbarButtonInfoChanged() { TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); EnqueueShowRealWindow(); taskbarServiceImpl.Description = "new desc"; taskbarServiceImpl.ProgressValue = 0.5; RealWindow.TaskbarItemInfo = null; Assert.IsTrue(string.IsNullOrEmpty(taskbarServiceImpl.Description)); } [Test] public void ExplicitWindow() { var testWindow = new Window(); TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); taskbarServiceImpl.Window = testWindow; Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); EnqueueShowRealWindow(); ITaskbarButtonService taskbarService = taskbarServiceImpl; taskbarService.ProgressValue = 0.5; Assert.IsNull(RealWindow.TaskbarItemInfo); Assert.AreEqual(0.5, testWindow.TaskbarItemInfo.ProgressValue); } [Test] public void RemoveAssociatedObjectFromTree_CheckWindowIsNull() { Grid grid = new Grid(); RealWindow.Content = grid; TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(grid).Add(taskbarServiceImpl); EnqueueShowRealWindow(); Assert.AreEqual(RealWindow, taskbarServiceImpl.ActualWindow); RealWindow.Content = null; DispatcherHelper.UpdateLayoutAndDoEvents(RealWindow); Assert.IsNull(taskbarServiceImpl.ActualWindow); } [Test] public void TryUsingServiceWithoutWindow() { Grid grid = new Grid(); TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(grid).Add(taskbarServiceImpl); ITaskbarButtonService taskbarService = taskbarServiceImpl; taskbarService.ProgressState = TaskbarItemProgressState.Paused; taskbarService.ProgressValue = 0.81; } [Test] public void SeveralServices() { TaskbarButtonService taskbarService_1 = new TaskbarButtonService(); TaskbarButtonService taskbarService_2 = new TaskbarButtonService(); taskbarService_1.Window = RealWindow; taskbarService_2.Window = RealWindow; EnqueueShowRealWindow(); taskbarService_1.ProgressValue = 0.5; Assert.AreEqual(0.5, taskbarService_2.ProgressValue); taskbarService_2.ProgressValue = 0.8; Assert.AreEqual(0.8, taskbarService_1.ProgressValue); taskbarService_1.ProgressState = TaskbarItemProgressState.Normal; Assert.AreEqual(TaskbarItemProgressState.Normal, taskbarService_2.ProgressState); taskbarService_2.ProgressState = TaskbarItemProgressState.Paused; Assert.AreEqual(TaskbarItemProgressState.Paused, taskbarService_1.ProgressState); } [Test] public void SetOverlayIcon() { TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); EnqueueShowRealWindow(); ITaskbarButtonService taskbarService = taskbarServiceImpl; ImageSource icon_1 = ApplicationJumpListServiceTestsImageSourceHelper.GetImageSource(AssemblyHelper.GetResourceUri(typeof(TaskbarButtonServiceTests).Assembly, "Icons/icon1.ico")); ImageSource icon_2 = ApplicationJumpListServiceTestsImageSourceHelper.GetImageSource(AssemblyHelper.GetResourceUri(typeof(TaskbarButtonServiceTests).Assembly, "Icons/icon2.ico")); taskbarService.OverlayIcon = icon_1; Assert.AreEqual(icon_1, RealWindow.TaskbarItemInfo.Overlay); taskbarService.OverlayIcon = icon_2; Assert.AreEqual(icon_2, RealWindow.TaskbarItemInfo.Overlay); } [Test] public void BindOverlayIcon() { VM vm = VM.Create(); RealWindow.DataContext = vm; TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); BindingOperations.SetBinding(taskbarServiceImpl, TaskbarButtonService.OverlayIconProperty, new Binding("OverlayIcon")); EnqueueShowRealWindow(); ITaskbarButtonService taskbarService = taskbarServiceImpl; ImageSource icon_1 = ApplicationJumpListServiceTestsImageSourceHelper.GetImageSource(AssemblyHelper.GetResourceUri(typeof(TaskbarButtonServiceTests).Assembly, "Icons/icon1.ico")); ImageSource icon_2 = ApplicationJumpListServiceTestsImageSourceHelper.GetImageSource(AssemblyHelper.GetResourceUri(typeof(TaskbarButtonServiceTests).Assembly, "Icons/icon2.ico")); vm.OverlayIcon = icon_1; Assert.AreEqual(icon_1, RealWindow.TaskbarItemInfo.Overlay); vm.OverlayIcon = icon_2; Assert.AreEqual(icon_2, RealWindow.TaskbarItemInfo.Overlay); } [Test] public void SetDescription() { TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); EnqueueShowRealWindow(); ITaskbarButtonService taskbarService = taskbarServiceImpl; taskbarService.Description = "test1"; Assert.AreEqual("test1", RealWindow.TaskbarItemInfo.Description); taskbarService.Description = "test2"; Assert.AreEqual("test2", RealWindow.TaskbarItemInfo.Description); } [Test] public void BindDescription() { VM vm = VM.Create(); RealWindow.DataContext = vm; TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); BindingOperations.SetBinding(taskbarServiceImpl, TaskbarButtonService.DescriptionProperty, new Binding("Description")); EnqueueShowRealWindow(); ITaskbarButtonService taskbarService = taskbarServiceImpl; vm.Description = "test1"; Assert.AreEqual("test1", RealWindow.TaskbarItemInfo.Description); vm.Description = "test2"; Assert.AreEqual("test2", RealWindow.TaskbarItemInfo.Description); } [Test] public void SetThumbButtonInfos() { TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); EnqueueShowRealWindow(); ITaskbarButtonService taskbarService = taskbarServiceImpl; TaskbarThumbButtonInfo thumbButtonInfo_1 = new TaskbarThumbButtonInfo() { Description = "thumbButton1" }; TaskbarThumbButtonInfo thumbButtonInfo_2 = new TaskbarThumbButtonInfo() { Description = "thumbButton2" }; taskbarService.ThumbButtonInfos.Add(thumbButtonInfo_1); taskbarService.ThumbButtonInfos.Add(thumbButtonInfo_2); AssertHelper.AssertEnumerablesAreEqual(new ThumbButtonInfo[] { new ThumbButtonInfo() { Description = "thumbButton1" }, new ThumbButtonInfo() { Description = "thumbButton2" }, }, RealWindow.TaskbarItemInfo.ThumbButtonInfos, true, new string[] { "Command" }); } [Test] public void TaskbarThumbButtonPropertiesChanged() { TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); EnqueueShowRealWindow(); ImageSource imageSource1 = ApplicationJumpListServiceTestsImageSourceHelper.GetImageSource(AssemblyHelper.GetResourceUri(typeof(TaskbarButtonServiceTests).Assembly, "Icons/icon1.ico")); ImageSource imageSource2 = ApplicationJumpListServiceTestsImageSourceHelper.GetImageSource(AssemblyHelper.GetResourceUri(typeof(TaskbarButtonServiceTests).Assembly, "Icons/icon2.png")); ITaskbarButtonService taskbarService = taskbarServiceImpl; TaskbarThumbButtonInfo thumbButtonInfo_1 = new TaskbarThumbButtonInfo() { Description = "thumbButton1", IsEnabled = true, IsInteractive = true, IsBackgroundVisible = false, DismissWhenClicked = false, Visibility = Visibility.Visible, ImageSource = imageSource1 }; taskbarService.ThumbButtonInfos.Add(thumbButtonInfo_1); taskbarService.ThumbButtonInfos[0].Description = "thumbButton2"; taskbarService.ThumbButtonInfos[0].IsEnabled = false; taskbarService.ThumbButtonInfos[0].IsInteractive = false; taskbarService.ThumbButtonInfos[0].IsBackgroundVisible = true; taskbarService.ThumbButtonInfos[0].DismissWhenClicked = true; taskbarService.ThumbButtonInfos[0].Visibility = Visibility.Collapsed; taskbarService.ThumbButtonInfos[0].ImageSource = imageSource2; AssertHelper.AssertEnumerablesAreEqual(new ThumbButtonInfo[] { new ThumbButtonInfo() { Description = "thumbButton2", IsEnabled = false, IsInteractive = false, IsBackgroundVisible = true, DismissWhenClicked = true, Visibility = Visibility.Collapsed, ImageSource = imageSource2 }, }, RealWindow.TaskbarItemInfo.ThumbButtonInfos, true, new string[] { "Command" }); } [Test] public void TaskbarThumbButtonBindCommandWithParameter() { TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); EnqueueShowRealWindow(); ButtonViewModel viewModel = new ButtonViewModel(); ITaskbarButtonService taskbarService = taskbarServiceImpl; TaskbarThumbButtonInfo thumbButtonInfo_1 = new TaskbarThumbButtonInfo(); BindingOperations.SetBinding(thumbButtonInfo_1, TaskbarThumbButtonInfo.CommandParameterProperty, new Binding("CommandParameter") { Source = viewModel, Mode = BindingMode.OneWay }); BindingOperations.SetBinding(thumbButtonInfo_1, TaskbarThumbButtonInfo.CommandProperty, new Binding("Command") { Source = viewModel, Mode = BindingMode.OneWay }); taskbarService.ThumbButtonInfos.Add(thumbButtonInfo_1); int? parameter = null; viewModel.Command = new DelegateCommand<int?>(p => parameter = p); viewModel.CommandParameter = 13; RealWindow.TaskbarItemInfo.ThumbButtonInfos[0].Command.Execute(RealWindow.TaskbarItemInfo.ThumbButtonInfos[0].CommandParameter); Assert.AreEqual(13, parameter); } [Test] public void ThumbButtonPropertiesChanged() { TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); EnqueueShowRealWindow(); ImageSource imageSource1 = ApplicationJumpListServiceTestsImageSourceHelper.GetImageSource(AssemblyHelper.GetResourceUri(typeof(TaskbarButtonServiceTests).Assembly, "Icons/icon1.ico")); ImageSource imageSource2 = ApplicationJumpListServiceTestsImageSourceHelper.GetImageSource(AssemblyHelper.GetResourceUri(typeof(TaskbarButtonServiceTests).Assembly, "Icons/icon2.ico")); ITaskbarButtonService taskbarService = taskbarServiceImpl; TaskbarThumbButtonInfo thumbButtonInfo_1 = new TaskbarThumbButtonInfo() { Description = "thumbButton1", IsEnabled = true, IsInteractive = true, IsBackgroundVisible = false, DismissWhenClicked = false, Visibility = Visibility.Visible, ImageSource = imageSource1 }; taskbarService.ThumbButtonInfos.Add(thumbButtonInfo_1); RealWindow.TaskbarItemInfo.ThumbButtonInfos[0].Description = "thumbButton2"; RealWindow.TaskbarItemInfo.ThumbButtonInfos[0].IsEnabled = false; RealWindow.TaskbarItemInfo.ThumbButtonInfos[0].IsInteractive = false; RealWindow.TaskbarItemInfo.ThumbButtonInfos[0].IsBackgroundVisible = true; RealWindow.TaskbarItemInfo.ThumbButtonInfos[0].DismissWhenClicked = true; RealWindow.TaskbarItemInfo.ThumbButtonInfos[0].Visibility = Visibility.Collapsed; RealWindow.TaskbarItemInfo.ThumbButtonInfos[0].ImageSource = imageSource2; EnqueueShowRealWindow(); AssertHelper.AssertEnumerablesAreEqual(new TaskbarThumbButtonInfo[] { new TaskbarThumbButtonInfo() { Description = "thumbButton2", IsEnabled = false, IsInteractive = false, IsBackgroundVisible = true, DismissWhenClicked = true, Visibility = Visibility.Collapsed, ImageSource = imageSource2 }, }, taskbarService.ThumbButtonInfos, true, new string[] { "ItemInfo" }); } [Test] public void SetThumbButtonInfosClickAction() { TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); EnqueueShowRealWindow(); ITaskbarButtonService taskbarService = taskbarServiceImpl; TaskbarThumbButtonInfo taskbarThumbButtonInfo = new TaskbarThumbButtonInfo() { Description = "xxx" }; bool actionExecuted = false; bool clickExecuted = false; taskbarThumbButtonInfo.Action = () => { actionExecuted = true; }; taskbarThumbButtonInfo.Click += (s, e) => clickExecuted = true; taskbarService.ThumbButtonInfos.Add(taskbarThumbButtonInfo); ThumbButtonInfo thumbButtonInfo = RealWindow.TaskbarItemInfo.ThumbButtonInfos[0]; ClickThumbButton(thumbButtonInfo); Assert.IsTrue(actionExecuted); Assert.IsTrue(clickExecuted); } static void ClickThumbButton(ThumbButtonInfo thumbButtonInfo) { EventHandler clickHandler = (EventHandler)typeof(ThumbButtonInfo).GetField("Click", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(thumbButtonInfo); if(clickHandler != null) clickHandler(thumbButtonInfo, EventArgs.Empty); if(thumbButtonInfo.Command != null && thumbButtonInfo.Command.CanExecute(thumbButtonInfo.CommandParameter)) thumbButtonInfo.Command.Execute(thumbButtonInfo.CommandParameter); } [Test] public void ThumbButtonInfoFalseTriggering() { TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); EnqueueShowRealWindow(); ITaskbarButtonService taskbarService = taskbarServiceImpl; int CommandClickCounter_0 = 0; int ActionClickCounter_0 = 0; int CommandClickCounter_1 = 0; int ActionClickCounter_1 = 0; taskbarService.ThumbButtonInfos.Add( new TaskbarThumbButtonInfo() { Command = new DelegateCommand(() => ++CommandClickCounter_0), Action = () => ++ActionClickCounter_0 }); taskbarService.ThumbButtonInfos.Add( new TaskbarThumbButtonInfo() { Command = new DelegateCommand(() => ++CommandClickCounter_1), Action = () => ++ActionClickCounter_1 }); ClickThumbButton(RealWindow.TaskbarItemInfo.ThumbButtonInfos[0]); ClickThumbButton(RealWindow.TaskbarItemInfo.ThumbButtonInfos[1]); Assert.AreEqual(CommandClickCounter_0, 1); Assert.AreEqual(ActionClickCounter_0, 1); Assert.AreEqual(CommandClickCounter_1, 1); Assert.AreEqual(ActionClickCounter_1, 1); } [Test] public void SetThumbButtonInfoProperties() { TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); EnqueueShowRealWindow(); ITaskbarButtonService taskbarService = taskbarServiceImpl; for(int i = 0; i < 10; ++i) taskbarService.ThumbButtonInfos.Add(new TaskbarThumbButtonInfo()); foreach(var item in taskbarService.ThumbButtonInfos) { item.Description = "NewDescription"; item.IsEnabled = false; item.IsBackgroundVisible = false; } foreach(var item in RealWindow.TaskbarItemInfo.ThumbButtonInfos) { Assert.AreEqual("NewDescription", item.Description); Assert.AreEqual(false, item.IsEnabled); Assert.AreEqual(false, item.IsBackgroundVisible); } } [Test] public void SetThumbnailClipMargin() { TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); EnqueueShowRealWindow(); ITaskbarButtonService taskbarService = taskbarServiceImpl; taskbarService.ThumbnailClipMargin = new Thickness { Bottom = 10, Left = 5, Right = 100, Top = 1 }; Assert.AreEqual(new Thickness { Bottom = 10, Left = 5, Right = 100, Top = 1 }, RealWindow.TaskbarItemInfo.ThumbnailClipMargin); } [Test] public void BindThumbnailClipMargin() { VM vm = VM.Create(); RealWindow.DataContext = vm; TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); BindingOperations.SetBinding(taskbarServiceImpl, TaskbarButtonService.ThumbnailClipMarginProperty, new Binding("ThumbnailClipMargin")); EnqueueShowRealWindow(); ITaskbarButtonService taskbarService = taskbarServiceImpl; vm.ThumbnailClipMargin = new Thickness { Bottom = 10, Left = 5, Right = 100, Top = 1 }; Assert.AreEqual(new Thickness { Bottom = 10, Left = 5, Right = 100, Top = 1 }, RealWindow.TaskbarItemInfo.ThumbnailClipMargin); } [Test] public void SetThumbnailClipMarginCallback() { clipMarginShift = 0; TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService() { ThumbnailClipMarginCallback = GetThumbnailClipMargin }; Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); EnqueueShowRealWindow(); ITaskbarButtonService taskbarService = taskbarServiceImpl; Assert.IsTrue(RealWindow.Height > 100 && RealWindow.Width > 100); Assert.AreEqual(CorrectThickness(RealWindow), RealWindow.TaskbarItemInfo.ThumbnailClipMargin); clipMarginShift = 10; taskbarService.UpdateThumbnailClipMargin(); Assert.AreEqual(CorrectThickness(RealWindow, clipMarginShift), RealWindow.TaskbarItemInfo.ThumbnailClipMargin); } [Test] public void SetThumbnailClipMarginCallback_LateBinding() { clipMarginShift = 0; TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); EnqueueShowRealWindow(); ITaskbarButtonService taskbarService = taskbarServiceImpl; taskbarService.ThumbnailClipMarginCallback = GetThumbnailClipMargin; Assert.IsTrue(RealWindow.Height > 100 && RealWindow.Width > 100); Assert.AreEqual(CorrectThickness(RealWindow), RealWindow.TaskbarItemInfo.ThumbnailClipMargin); } [Test] public void SetThumbnailClipMarginCallback_SizeChanged() { clipMarginShift = 0; TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService() { ThumbnailClipMarginCallback = GetThumbnailClipMargin }; Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); EnqueueShowRealWindow(); Assert.IsTrue(RealWindow.Height > 100 && RealWindow.Width > 100); Assert.AreEqual(CorrectThickness(RealWindow), RealWindow.TaskbarItemInfo.ThumbnailClipMargin); RealWindow.Width += 200; RealWindow.Width -= 50; Assert.AreEqual(CorrectThickness(RealWindow), RealWindow.TaskbarItemInfo.ThumbnailClipMargin); } [Test] public void SetThumbnailClipMarginCallback_TwoWindows() { EnqueueShowRealWindow(); Window testWindow = new Window() { Height = 480, Width = 640, IsEnabled = true, Visibility = Visibility.Visible }; testWindow.Show(); try { clipMarginShift = 0; TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService() { ThumbnailClipMarginCallback = GetThumbnailClipMargin }; Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); Assert.IsTrue(RealWindow.Height > 100 && RealWindow.Width > 100); Assert.AreEqual(CorrectThickness(RealWindow), RealWindow.TaskbarItemInfo.ThumbnailClipMargin); taskbarServiceImpl.Window = testWindow; Assert.AreEqual(CorrectThickness(testWindow), testWindow.TaskbarItemInfo.ThumbnailClipMargin); getThumbnailClipMarginExecute = false; RealWindow.Width += 200; Assert.IsFalse(getThumbnailClipMarginExecute); testWindow.Width += 300; DispatcherHelper.UpdateLayoutAndDoEvents(testWindow); Assert.IsTrue(getThumbnailClipMarginExecute); } finally { testWindow.Close(); } } [Test] public void ItemInfoBinding() { TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); EnqueueShowRealWindow(); ITaskbarButtonService taskbarService = taskbarServiceImpl; ImageSource icon_1 = ApplicationJumpListServiceTestsImageSourceHelper.GetImageSource(AssemblyHelper.GetResourceUri(typeof(TaskbarButtonServiceTests).Assembly, "Icons/icon1.ico")); ThumbButtonInfo thumbButtonInfo = new ThumbButtonInfo() { Description = "thumbButton51" }; RealWindow.TaskbarItemInfo.ProgressValue = 0.5; RealWindow.TaskbarItemInfo.ProgressState = TaskbarItemProgressState.Error; RealWindow.TaskbarItemInfo.Overlay = icon_1; RealWindow.TaskbarItemInfo.Description = "test1"; RealWindow.TaskbarItemInfo.ThumbButtonInfos.Add(thumbButtonInfo); RealWindow.TaskbarItemInfo.ThumbnailClipMargin = new Thickness { Bottom = 1, Left = 50, Right = 99, Top = 11 }; Assert.AreEqual(0.5, taskbarService.ProgressValue); Assert.AreEqual(TaskbarItemProgressState.Error, taskbarService.ProgressState); Assert.AreEqual(icon_1, taskbarService.OverlayIcon); Assert.AreEqual("test1", taskbarService.Description); AssertHelper.AssertEnumerablesAreEqual(new TaskbarThumbButtonInfo[] { new TaskbarThumbButtonInfo() { Description = "thumbButton51" } }, taskbarService.ThumbButtonInfos, true, new string[] { "ItemInfo" }); Assert.AreEqual(new Thickness { Bottom = 1, Left = 50, Right = 99, Top = 11 }, taskbarService.ThumbnailClipMargin); } Thickness GetThumbnailClipMargin(Size size) { getThumbnailClipMarginExecute = true; return new Thickness { Left = 0.1 * size.Width + clipMarginShift, Top = 0.4 * size.Height - clipMarginShift, Right = 0.2 * size.Width + clipMarginShift, Bottom = 0.3 * size.Height - clipMarginShift }; } Thickness CorrectThickness(Window window, double shift = 0.0) { return new Thickness { Left = 0.1 * window.Width + shift, Top = 0.4 * window.Height - shift, Right = 0.2 * window.Width + shift, Bottom = 0.3 * window.Height - shift }; } [Test] public void BindPropertyAndListenPropertyChanged() { VM vm = VM.Create(); RealWindow.DataContext = vm; TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); int progressStateChangedCount = 0; int progressValueChangedCount = 0; int overlayIconChangedCount = 0; int descriptionChangedCount = 0; int thumbnailClipMarginChangedCount = 0; ((INotifyPropertyChanged)vm).PropertyChanged += (d, e) => { if(e.PropertyName == "ProgressState") progressStateChangedCount++; if(e.PropertyName == "ProgressValue") progressValueChangedCount++; if(e.PropertyName == "OverlayIcon") overlayIconChangedCount++; if(e.PropertyName == "Description") descriptionChangedCount++; if(e.PropertyName == "ThumbnailClipMargin") thumbnailClipMarginChangedCount++; }; BindingOperations.SetBinding(taskbarServiceImpl, TaskbarButtonService.ProgressStateProperty, new Binding("ProgressState")); BindingOperations.SetBinding(taskbarServiceImpl, TaskbarButtonService.ProgressValueProperty, new Binding("ProgressValue")); BindingOperations.SetBinding(taskbarServiceImpl, TaskbarButtonService.OverlayIconProperty, new Binding("OverlayIcon")); BindingOperations.SetBinding(taskbarServiceImpl, TaskbarButtonService.DescriptionProperty, new Binding("Description")); BindingOperations.SetBinding(taskbarServiceImpl, TaskbarButtonService.ThumbnailClipMarginProperty, new Binding("ThumbnailClipMargin")); EnqueueShowRealWindow(); ITaskbarButtonService taskbarService = taskbarServiceImpl; vm.ProgressState = TaskbarItemProgressState.Indeterminate; Assert.AreEqual(TaskbarItemProgressState.Indeterminate, RealWindow.TaskbarItemInfo.ProgressState); Assert.AreEqual(1, progressStateChangedCount); vm.ProgressValue = 0.5d; Assert.AreEqual(0.5d, RealWindow.TaskbarItemInfo.ProgressValue); Assert.AreEqual(1, progressValueChangedCount); ImageSource icon_1 = ApplicationJumpListServiceTestsImageSourceHelper.GetImageSource(AssemblyHelper.GetResourceUri(typeof(TaskbarButtonServiceTests).Assembly, "Icons/icon1.ico")); vm.OverlayIcon = icon_1; Assert.AreEqual(icon_1, RealWindow.TaskbarItemInfo.Overlay); Assert.AreEqual(1, overlayIconChangedCount); vm.Description = "Test"; Assert.AreEqual("Test", RealWindow.TaskbarItemInfo.Description); Assert.AreEqual(1, descriptionChangedCount); vm.ThumbnailClipMargin = new Thickness(45); Assert.AreEqual(new Thickness(45), RealWindow.TaskbarItemInfo.ThumbnailClipMargin); Assert.AreEqual(1, thumbnailClipMarginChangedCount); } [Test] public void BindTaskbarThumbButtonInfoCommand() { VM vm = VM.Create(); RealWindow.DataContext = vm; TaskbarButtonService taskbarServiceImpl = new TaskbarButtonService(); TaskbarThumbButtonInfo bt = new TaskbarThumbButtonInfo(); BindingOperations.SetBinding(bt, TaskbarThumbButtonInfo.CommandProperty, new Binding("DoCommand")); taskbarServiceImpl.ThumbButtonInfos.Add(bt); Interaction.GetBehaviors(RealWindow).Add(taskbarServiceImpl); EnqueueShowRealWindow(); Assert.AreEqual(POCOViewModelExtensions.GetCommand(vm, x => x.Do()), bt.Command); } public class ButtonViewModel : BindableBase { public ICommand Command { get { return GetProperty(() => Command); } set { SetProperty(() => Command, value); } } public object CommandParameter { get { return GetProperty(() => CommandParameter); } set { SetProperty(() => CommandParameter, value); } } } public class VM { public virtual TaskbarItemProgressState ProgressState { get; set; } public virtual double ProgressValue { get; set; } public virtual ImageSource OverlayIcon { get; set; } public virtual string Description { get; set; } public virtual Thickness ThumbnailClipMargin { get; set; } public static VM Create() { return ViewModelSource.Create(() => new VM()); } protected VM() { } public void Do() { } } } }
using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Squareup.Okhttp.Internal.Spdy { // Metadata.xml XPath interface reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/interface[@name='FrameReader.Handler']" [Register ("com/squareup/okhttp/internal/spdy/FrameReader$Handler", "", "Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandlerInvoker")] public partial interface IFrameReaderHandler : IJavaObject { // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/interface[@name='FrameReader.Handler']/method[@name='data' and count(parameter)=4 and parameter[1][@type='boolean'] and parameter[2][@type='int'] and parameter[3][@type='java.io.InputStream'] and parameter[4][@type='int']]" [Register ("data", "(ZILjava/io/InputStream;I)V", "GetData_ZILjava_io_InputStream_IHandler:Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandlerInvoker, Cordova.Android.Binding")] void Data (bool p0, int p1, global::System.IO.Stream p2, int p3); // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/interface[@name='FrameReader.Handler']/method[@name='goAway' and count(parameter)=2 and parameter[1][@type='int'] and parameter[2][@type='com.squareup.okhttp.internal.spdy.ErrorCode']]" [Register ("goAway", "(ILcom/squareup/okhttp/internal/spdy/ErrorCode;)V", "GetGoAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_Handler:Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandlerInvoker, Cordova.Android.Binding")] void GoAway (int p0, global::Com.Squareup.Okhttp.Internal.Spdy.ErrorCode p1); // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/interface[@name='FrameReader.Handler']/method[@name='noop' and count(parameter)=0]" [Register ("noop", "()V", "GetNoopHandler:Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandlerInvoker, Cordova.Android.Binding")] void Noop (); // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/interface[@name='FrameReader.Handler']/method[@name='ping' and count(parameter)=3 and parameter[1][@type='boolean'] and parameter[2][@type='int'] and parameter[3][@type='int']]" [Register ("ping", "(ZII)V", "GetPing_ZIIHandler:Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandlerInvoker, Cordova.Android.Binding")] void Ping (bool p0, int p1, int p2); // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/interface[@name='FrameReader.Handler']/method[@name='priority' and count(parameter)=2 and parameter[1][@type='int'] and parameter[2][@type='int']]" [Register ("priority", "(II)V", "GetPriority_IIHandler:Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandlerInvoker, Cordova.Android.Binding")] void Priority (int p0, int p1); // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/interface[@name='FrameReader.Handler']/method[@name='rstStream' and count(parameter)=2 and parameter[1][@type='int'] and parameter[2][@type='com.squareup.okhttp.internal.spdy.ErrorCode']]" [Register ("rstStream", "(ILcom/squareup/okhttp/internal/spdy/ErrorCode;)V", "GetRstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_Handler:Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandlerInvoker, Cordova.Android.Binding")] void RstStream (int p0, global::Com.Squareup.Okhttp.Internal.Spdy.ErrorCode p1); // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/interface[@name='FrameReader.Handler']/method[@name='windowUpdate' and count(parameter)=3 and parameter[1][@type='int'] and parameter[2][@type='int'] and parameter[3][@type='boolean']]" [Register ("windowUpdate", "(IIZ)V", "GetWindowUpdate_IIZHandler:Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandlerInvoker, Cordova.Android.Binding")] void WindowUpdate (int p0, int p1, bool p2); } [global::Android.Runtime.Register ("com/squareup/okhttp/internal/spdy/FrameReader$Handler", DoNotGenerateAcw=true)] internal class IFrameReaderHandlerInvoker : global::Java.Lang.Object, IFrameReaderHandler { static IntPtr java_class_ref = JNIEnv.FindClass ("com/squareup/okhttp/internal/spdy/FrameReader$Handler"); IntPtr class_ref; public static IFrameReaderHandler GetObject (IntPtr handle, JniHandleOwnership transfer) { return global::Java.Lang.Object.GetObject<IFrameReaderHandler> (handle, transfer); } static IntPtr Validate (IntPtr handle) { if (!JNIEnv.IsInstanceOf (handle, java_class_ref)) throw new InvalidCastException (string.Format ("Unable to convert instance of type '{0}' to type '{1}'.", JNIEnv.GetClassNameFromInstance (handle), "com.squareup.okhttp.internal.spdy.FrameReader.Handler")); return handle; } protected override void Dispose (bool disposing) { if (this.class_ref != IntPtr.Zero) JNIEnv.DeleteGlobalRef (this.class_ref); this.class_ref = IntPtr.Zero; base.Dispose (disposing); } public IFrameReaderHandlerInvoker (IntPtr handle, JniHandleOwnership transfer) : base (Validate (handle), transfer) { IntPtr local_ref = JNIEnv.GetObjectClass (Handle); this.class_ref = JNIEnv.NewGlobalRef (local_ref); JNIEnv.DeleteLocalRef (local_ref); } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override System.Type ThresholdType { get { return typeof (IFrameReaderHandlerInvoker); } } static Delegate cb_data_ZILjava_io_InputStream_I; #pragma warning disable 0169 static Delegate GetData_ZILjava_io_InputStream_IHandler () { if (cb_data_ZILjava_io_InputStream_I == null) cb_data_ZILjava_io_InputStream_I = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, bool, int, IntPtr, int>) n_Data_ZILjava_io_InputStream_I); return cb_data_ZILjava_io_InputStream_I; } static void n_Data_ZILjava_io_InputStream_I (IntPtr jnienv, IntPtr native__this, bool p0, int p1, IntPtr native_p2, int p3) { global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandler __this = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandler> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); System.IO.Stream p2 = global::Android.Runtime.InputStreamInvoker.FromJniHandle (native_p2, JniHandleOwnership.DoNotTransfer); __this.Data (p0, p1, p2, p3); } #pragma warning restore 0169 IntPtr id_data_ZILjava_io_InputStream_I; public void Data (bool p0, int p1, global::System.IO.Stream p2, int p3) { if (id_data_ZILjava_io_InputStream_I == IntPtr.Zero) id_data_ZILjava_io_InputStream_I = JNIEnv.GetMethodID (class_ref, "data", "(ZILjava/io/InputStream;I)V"); IntPtr native_p2 = global::Android.Runtime.InputStreamAdapter.ToLocalJniHandle (p2); JNIEnv.CallVoidMethod (Handle, id_data_ZILjava_io_InputStream_I, new JValue (p0), new JValue (p1), new JValue (native_p2), new JValue (p3)); JNIEnv.DeleteLocalRef (native_p2); } static Delegate cb_goAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_; #pragma warning disable 0169 static Delegate GetGoAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_Handler () { if (cb_goAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_ == null) cb_goAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int, IntPtr>) n_GoAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_); return cb_goAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_; } static void n_GoAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_ (IntPtr jnienv, IntPtr native__this, int p0, IntPtr native_p1) { global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandler __this = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandler> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Com.Squareup.Okhttp.Internal.Spdy.ErrorCode p1 = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.ErrorCode> (native_p1, JniHandleOwnership.DoNotTransfer); __this.GoAway (p0, p1); } #pragma warning restore 0169 IntPtr id_goAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_; public void GoAway (int p0, global::Com.Squareup.Okhttp.Internal.Spdy.ErrorCode p1) { if (id_goAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_ == IntPtr.Zero) id_goAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_ = JNIEnv.GetMethodID (class_ref, "goAway", "(ILcom/squareup/okhttp/internal/spdy/ErrorCode;)V"); JNIEnv.CallVoidMethod (Handle, id_goAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_, new JValue (p0), new JValue (p1)); } static Delegate cb_noop; #pragma warning disable 0169 static Delegate GetNoopHandler () { if (cb_noop == null) cb_noop = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_Noop); return cb_noop; } static void n_Noop (IntPtr jnienv, IntPtr native__this) { global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandler __this = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandler> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.Noop (); } #pragma warning restore 0169 IntPtr id_noop; public void Noop () { if (id_noop == IntPtr.Zero) id_noop = JNIEnv.GetMethodID (class_ref, "noop", "()V"); JNIEnv.CallVoidMethod (Handle, id_noop); } static Delegate cb_ping_ZII; #pragma warning disable 0169 static Delegate GetPing_ZIIHandler () { if (cb_ping_ZII == null) cb_ping_ZII = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, bool, int, int>) n_Ping_ZII); return cb_ping_ZII; } static void n_Ping_ZII (IntPtr jnienv, IntPtr native__this, bool p0, int p1, int p2) { global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandler __this = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandler> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.Ping (p0, p1, p2); } #pragma warning restore 0169 IntPtr id_ping_ZII; public void Ping (bool p0, int p1, int p2) { if (id_ping_ZII == IntPtr.Zero) id_ping_ZII = JNIEnv.GetMethodID (class_ref, "ping", "(ZII)V"); JNIEnv.CallVoidMethod (Handle, id_ping_ZII, new JValue (p0), new JValue (p1), new JValue (p2)); } static Delegate cb_priority_II; #pragma warning disable 0169 static Delegate GetPriority_IIHandler () { if (cb_priority_II == null) cb_priority_II = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int, int>) n_Priority_II); return cb_priority_II; } static void n_Priority_II (IntPtr jnienv, IntPtr native__this, int p0, int p1) { global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandler __this = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandler> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.Priority (p0, p1); } #pragma warning restore 0169 IntPtr id_priority_II; public void Priority (int p0, int p1) { if (id_priority_II == IntPtr.Zero) id_priority_II = JNIEnv.GetMethodID (class_ref, "priority", "(II)V"); JNIEnv.CallVoidMethod (Handle, id_priority_II, new JValue (p0), new JValue (p1)); } static Delegate cb_rstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_; #pragma warning disable 0169 static Delegate GetRstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_Handler () { if (cb_rstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_ == null) cb_rstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int, IntPtr>) n_RstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_); return cb_rstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_; } static void n_RstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_ (IntPtr jnienv, IntPtr native__this, int p0, IntPtr native_p1) { global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandler __this = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandler> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Com.Squareup.Okhttp.Internal.Spdy.ErrorCode p1 = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.ErrorCode> (native_p1, JniHandleOwnership.DoNotTransfer); __this.RstStream (p0, p1); } #pragma warning restore 0169 IntPtr id_rstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_; public void RstStream (int p0, global::Com.Squareup.Okhttp.Internal.Spdy.ErrorCode p1) { if (id_rstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_ == IntPtr.Zero) id_rstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_ = JNIEnv.GetMethodID (class_ref, "rstStream", "(ILcom/squareup/okhttp/internal/spdy/ErrorCode;)V"); JNIEnv.CallVoidMethod (Handle, id_rstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_, new JValue (p0), new JValue (p1)); } static Delegate cb_windowUpdate_IIZ; #pragma warning disable 0169 static Delegate GetWindowUpdate_IIZHandler () { if (cb_windowUpdate_IIZ == null) cb_windowUpdate_IIZ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int, int, bool>) n_WindowUpdate_IIZ); return cb_windowUpdate_IIZ; } static void n_WindowUpdate_IIZ (IntPtr jnienv, IntPtr native__this, int p0, int p1, bool p2) { global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandler __this = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandler> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.WindowUpdate (p0, p1, p2); } #pragma warning restore 0169 IntPtr id_windowUpdate_IIZ; public void WindowUpdate (int p0, int p1, bool p2) { if (id_windowUpdate_IIZ == IntPtr.Zero) id_windowUpdate_IIZ = JNIEnv.GetMethodID (class_ref, "windowUpdate", "(IIZ)V"); JNIEnv.CallVoidMethod (Handle, id_windowUpdate_IIZ, new JValue (p0), new JValue (p1), new JValue (p2)); } } // Metadata.xml XPath interface reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/interface[@name='FrameReader']" [Register ("com/squareup/okhttp/internal/spdy/FrameReader", "", "Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderInvoker")] public partial interface IFrameReader : global::Java.IO.ICloseable { // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/interface[@name='FrameReader']/method[@name='nextFrame' and count(parameter)=1 and parameter[1][@type='com.squareup.okhttp.internal.spdy.FrameReader.Handler']]" [Register ("nextFrame", "(Lcom/squareup/okhttp/internal/spdy/FrameReader$Handler;)Z", "GetNextFrame_Lcom_squareup_okhttp_internal_spdy_FrameReader_Handler_Handler:Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderInvoker, Cordova.Android.Binding")] bool NextFrame (global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandler p0); // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/interface[@name='FrameReader']/method[@name='readConnectionHeader' and count(parameter)=0]" [Register ("readConnectionHeader", "()V", "GetReadConnectionHeaderHandler:Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderInvoker, Cordova.Android.Binding")] void ReadConnectionHeader (); } [global::Android.Runtime.Register ("com/squareup/okhttp/internal/spdy/FrameReader", DoNotGenerateAcw=true)] internal class IFrameReaderInvoker : global::Java.Lang.Object, IFrameReader { static IntPtr java_class_ref = JNIEnv.FindClass ("com/squareup/okhttp/internal/spdy/FrameReader"); IntPtr class_ref; public static IFrameReader GetObject (IntPtr handle, JniHandleOwnership transfer) { return global::Java.Lang.Object.GetObject<IFrameReader> (handle, transfer); } static IntPtr Validate (IntPtr handle) { if (!JNIEnv.IsInstanceOf (handle, java_class_ref)) throw new InvalidCastException (string.Format ("Unable to convert instance of type '{0}' to type '{1}'.", JNIEnv.GetClassNameFromInstance (handle), "com.squareup.okhttp.internal.spdy.FrameReader")); return handle; } protected override void Dispose (bool disposing) { if (this.class_ref != IntPtr.Zero) JNIEnv.DeleteGlobalRef (this.class_ref); this.class_ref = IntPtr.Zero; base.Dispose (disposing); } public IFrameReaderInvoker (IntPtr handle, JniHandleOwnership transfer) : base (Validate (handle), transfer) { IntPtr local_ref = JNIEnv.GetObjectClass (Handle); this.class_ref = JNIEnv.NewGlobalRef (local_ref); JNIEnv.DeleteLocalRef (local_ref); } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override System.Type ThresholdType { get { return typeof (IFrameReaderInvoker); } } static Delegate cb_nextFrame_Lcom_squareup_okhttp_internal_spdy_FrameReader_Handler_; #pragma warning disable 0169 static Delegate GetNextFrame_Lcom_squareup_okhttp_internal_spdy_FrameReader_Handler_Handler () { if (cb_nextFrame_Lcom_squareup_okhttp_internal_spdy_FrameReader_Handler_ == null) cb_nextFrame_Lcom_squareup_okhttp_internal_spdy_FrameReader_Handler_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, bool>) n_NextFrame_Lcom_squareup_okhttp_internal_spdy_FrameReader_Handler_); return cb_nextFrame_Lcom_squareup_okhttp_internal_spdy_FrameReader_Handler_; } static bool n_NextFrame_Lcom_squareup_okhttp_internal_spdy_FrameReader_Handler_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReader __this = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReader> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandler p0 = (global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandler)global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandler> (native_p0, JniHandleOwnership.DoNotTransfer); bool __ret = __this.NextFrame (p0); return __ret; } #pragma warning restore 0169 IntPtr id_nextFrame_Lcom_squareup_okhttp_internal_spdy_FrameReader_Handler_; public bool NextFrame (global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandler p0) { if (id_nextFrame_Lcom_squareup_okhttp_internal_spdy_FrameReader_Handler_ == IntPtr.Zero) id_nextFrame_Lcom_squareup_okhttp_internal_spdy_FrameReader_Handler_ = JNIEnv.GetMethodID (class_ref, "nextFrame", "(Lcom/squareup/okhttp/internal/spdy/FrameReader$Handler;)Z"); bool __ret = JNIEnv.CallBooleanMethod (Handle, id_nextFrame_Lcom_squareup_okhttp_internal_spdy_FrameReader_Handler_, new JValue (p0)); return __ret; } static Delegate cb_readConnectionHeader; #pragma warning disable 0169 static Delegate GetReadConnectionHeaderHandler () { if (cb_readConnectionHeader == null) cb_readConnectionHeader = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_ReadConnectionHeader); return cb_readConnectionHeader; } static void n_ReadConnectionHeader (IntPtr jnienv, IntPtr native__this) { global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReader __this = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReader> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.ReadConnectionHeader (); } #pragma warning restore 0169 IntPtr id_readConnectionHeader; public void ReadConnectionHeader () { if (id_readConnectionHeader == IntPtr.Zero) id_readConnectionHeader = JNIEnv.GetMethodID (class_ref, "readConnectionHeader", "()V"); JNIEnv.CallVoidMethod (Handle, id_readConnectionHeader); } static Delegate cb_close; #pragma warning disable 0169 static Delegate GetCloseHandler () { if (cb_close == null) cb_close = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_Close); return cb_close; } static void n_Close (IntPtr jnienv, IntPtr native__this) { global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReader __this = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReader> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.Close (); } #pragma warning restore 0169 IntPtr id_close; public void Close () { if (id_close == IntPtr.Zero) id_close = JNIEnv.GetMethodID (class_ref, "close", "()V"); JNIEnv.CallVoidMethod (Handle, id_close); } } }
// Copyright (C) 2014 dot42 // // Original filename: Android.Graphics.Drawable.Shapes.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Android.Graphics.Drawable.Shapes { /// <summary> /// <para>Creates an arc shape. The arc shape starts at a specified angle and sweeps clockwise, drawing slices of pie. The arc can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass the ArcShape to a android.graphics.drawable.ShapeDrawable. </para> /// </summary> /// <java-name> /// android/graphics/drawable/shapes/ArcShape /// </java-name> [Dot42.DexImport("android/graphics/drawable/shapes/ArcShape", AccessFlags = 33)] public partial class ArcShape : global::Android.Graphics.Drawable.Shapes.RectShape /* scope: __dot42__ */ { /// <summary> /// <para>ArcShape constructor.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(FF)V", AccessFlags = 1)] public ArcShape(float startAngle, float sweepAngle) /* MethodBuilder.Create */ { } /// <summary> /// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para> /// </summary> /// <java-name> /// draw /// </java-name> [Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1)] public override void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal ArcShape() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>Creates a rounded-corner rectangle. Optionally, an inset (rounded) rectangle can be included (to make a sort of "O" shape). The rounded rectangle can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass the RoundRectShape to a android.graphics.drawable.ShapeDrawable. </para> /// </summary> /// <java-name> /// android/graphics/drawable/shapes/RoundRectShape /// </java-name> [Dot42.DexImport("android/graphics/drawable/shapes/RoundRectShape", AccessFlags = 33)] public partial class RoundRectShape : global::Android.Graphics.Drawable.Shapes.RectShape /* scope: __dot42__ */ { /// <summary> /// <para>RoundRectShape constructor. Specifies an outer (round)rect and an optional inner (round)rect.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "([FLandroid/graphics/RectF;[F)V", AccessFlags = 1)] public RoundRectShape(float[] outerRadii, global::Android.Graphics.RectF inset, float[] innerRadii) /* MethodBuilder.Create */ { } /// <summary> /// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para> /// </summary> /// <java-name> /// draw /// </java-name> [Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1)] public override void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */ { } /// <summary> /// <para>Callback method called when resize(float,float) is executed.</para><para></para> /// </summary> /// <java-name> /// onResize /// </java-name> [Dot42.DexImport("onResize", "(FF)V", AccessFlags = 4)] protected internal override void OnResize(float width, float height) /* MethodBuilder.Create */ { } /// <java-name> /// clone /// </java-name> [Dot42.DexImport("clone", "()Landroid/graphics/drawable/shapes/RoundRectShape;", AccessFlags = 1)] public new virtual global::Android.Graphics.Drawable.Shapes.RoundRectShape Clone() /* MethodBuilder.Create */ { return default(global::Android.Graphics.Drawable.Shapes.RoundRectShape); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal RoundRectShape() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>Defines a generic graphical "shape." Any Shape can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass it to a android.graphics.drawable.ShapeDrawable. </para> /// </summary> /// <java-name> /// android/graphics/drawable/shapes/Shape /// </java-name> [Dot42.DexImport("android/graphics/drawable/shapes/Shape", AccessFlags = 1057)] public abstract partial class Shape : global::Java.Lang.ICloneable /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public Shape() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the width of the Shape. </para> /// </summary> /// <java-name> /// getWidth /// </java-name> [Dot42.DexImport("getWidth", "()F", AccessFlags = 17)] public float GetWidth() /* MethodBuilder.Create */ { return default(float); } /// <summary> /// <para>Returns the height of the Shape. </para> /// </summary> /// <java-name> /// getHeight /// </java-name> [Dot42.DexImport("getHeight", "()F", AccessFlags = 17)] public float GetHeight() /* MethodBuilder.Create */ { return default(float); } /// <summary> /// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para> /// </summary> /// <java-name> /// draw /// </java-name> [Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1025)] public abstract void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */ ; /// <summary> /// <para>Resizes the dimensions of this shape. Must be called before draw(Canvas,Paint).</para><para></para> /// </summary> /// <java-name> /// resize /// </java-name> [Dot42.DexImport("resize", "(FF)V", AccessFlags = 17)] public void Resize(float width, float height) /* MethodBuilder.Create */ { } /// <summary> /// <para>Checks whether the Shape is opaque. Default impl returns true. Override if your subclass can be opaque.</para><para></para> /// </summary> /// <returns> /// <para>true if any part of the drawable is <b>not</b> opaque. </para> /// </returns> /// <java-name> /// hasAlpha /// </java-name> [Dot42.DexImport("hasAlpha", "()Z", AccessFlags = 1)] public virtual bool HasAlpha() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Callback method called when resize(float,float) is executed.</para><para></para> /// </summary> /// <java-name> /// onResize /// </java-name> [Dot42.DexImport("onResize", "(FF)V", AccessFlags = 4)] protected internal virtual void OnResize(float width, float height) /* MethodBuilder.Create */ { } /// <java-name> /// clone /// </java-name> [Dot42.DexImport("clone", "()Landroid/graphics/drawable/shapes/Shape;", AccessFlags = 1)] public virtual global::Android.Graphics.Drawable.Shapes.Shape Clone() /* MethodBuilder.Create */ { return default(global::Android.Graphics.Drawable.Shapes.Shape); } /// <summary> /// <para>Returns the width of the Shape. </para> /// </summary> /// <java-name> /// getWidth /// </java-name> public float Width { [Dot42.DexImport("getWidth", "()F", AccessFlags = 17)] get{ return GetWidth(); } } /// <summary> /// <para>Returns the height of the Shape. </para> /// </summary> /// <java-name> /// getHeight /// </java-name> public float Height { [Dot42.DexImport("getHeight", "()F", AccessFlags = 17)] get{ return GetHeight(); } } } /// <summary> /// <para>Defines a rectangle shape. The rectangle can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass the RectShape to a android.graphics.drawable.ShapeDrawable. </para> /// </summary> /// <java-name> /// android/graphics/drawable/shapes/RectShape /// </java-name> [Dot42.DexImport("android/graphics/drawable/shapes/RectShape", AccessFlags = 33)] public partial class RectShape : global::Android.Graphics.Drawable.Shapes.Shape /* scope: __dot42__ */ { /// <summary> /// <para>RectShape constructor. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public RectShape() /* MethodBuilder.Create */ { } /// <summary> /// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para> /// </summary> /// <java-name> /// draw /// </java-name> [Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1)] public override void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */ { } /// <summary> /// <para>Callback method called when resize(float,float) is executed.</para><para></para> /// </summary> /// <java-name> /// onResize /// </java-name> [Dot42.DexImport("onResize", "(FF)V", AccessFlags = 4)] protected internal override void OnResize(float width, float height) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the RectF that defines this rectangle's bounds. </para> /// </summary> /// <java-name> /// rect /// </java-name> [Dot42.DexImport("rect", "()Landroid/graphics/RectF;", AccessFlags = 20)] protected internal global::Android.Graphics.RectF Rect() /* MethodBuilder.Create */ { return default(global::Android.Graphics.RectF); } /// <java-name> /// clone /// </java-name> [Dot42.DexImport("clone", "()Landroid/graphics/drawable/shapes/RectShape;", AccessFlags = 1)] public new virtual global::Android.Graphics.Drawable.Shapes.RectShape Clone() /* MethodBuilder.Create */ { return default(global::Android.Graphics.Drawable.Shapes.RectShape); } } /// <summary> /// <para>Creates geometric paths, utilizing the android.graphics.Path class. The path can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass the PathShape to a android.graphics.drawable.ShapeDrawable. </para> /// </summary> /// <java-name> /// android/graphics/drawable/shapes/PathShape /// </java-name> [Dot42.DexImport("android/graphics/drawable/shapes/PathShape", AccessFlags = 33)] public partial class PathShape : global::Android.Graphics.Drawable.Shapes.Shape /* scope: __dot42__ */ { /// <summary> /// <para>PathShape constructor.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Landroid/graphics/Path;FF)V", AccessFlags = 1)] public PathShape(global::Android.Graphics.Path path, float stdWidth, float stdHeight) /* MethodBuilder.Create */ { } /// <summary> /// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para> /// </summary> /// <java-name> /// draw /// </java-name> [Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1)] public override void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */ { } /// <summary> /// <para>Callback method called when resize(float,float) is executed.</para><para></para> /// </summary> /// <java-name> /// onResize /// </java-name> [Dot42.DexImport("onResize", "(FF)V", AccessFlags = 4)] protected internal override void OnResize(float width, float height) /* MethodBuilder.Create */ { } /// <java-name> /// clone /// </java-name> [Dot42.DexImport("clone", "()Landroid/graphics/drawable/shapes/PathShape;", AccessFlags = 1)] public new virtual global::Android.Graphics.Drawable.Shapes.PathShape Clone() /* MethodBuilder.Create */ { return default(global::Android.Graphics.Drawable.Shapes.PathShape); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal PathShape() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>Defines an oval shape. The oval can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass the OvalShape to a android.graphics.drawable.ShapeDrawable. </para> /// </summary> /// <java-name> /// android/graphics/drawable/shapes/OvalShape /// </java-name> [Dot42.DexImport("android/graphics/drawable/shapes/OvalShape", AccessFlags = 33)] public partial class OvalShape : global::Android.Graphics.Drawable.Shapes.RectShape /* scope: __dot42__ */ { /// <summary> /// <para>OvalShape constructor. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public OvalShape() /* MethodBuilder.Create */ { } /// <summary> /// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para> /// </summary> /// <java-name> /// draw /// </java-name> [Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1)] public override void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */ { } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Client { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Security.Authentication; using System.Text.RegularExpressions; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Client; using Apache.Ignite.Core.Client.Cache; using Apache.Ignite.Core.Impl.Client; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.Tests.Client.Cache; using NUnit.Framework; /// <summary> /// Base class for client tests. /// </summary> public class ClientTestBase { /** Cache name. */ protected const string CacheName = "cache"; /** */ protected const string RequestNamePrefixCache = "cache.ClientCache"; /** */ protected const string RequestNamePrefixBinary = "binary.ClientBinary"; /** Grid count. */ private readonly int _gridCount = 1; /** SSL. */ private readonly bool _enableSsl; /** Partition Awareness */ private readonly bool _enablePartitionAwareness; /// <summary> /// Initializes a new instance of the <see cref="ClientTestBase"/> class. /// </summary> public ClientTestBase() { // No-op. } /// <summary> /// Initializes a new instance of the <see cref="ClientTestBase"/> class. /// </summary> public ClientTestBase( int gridCount, bool enableSsl = false, bool enablePartitionAwareness = false) { _gridCount = gridCount; _enableSsl = enableSsl; _enablePartitionAwareness = enablePartitionAwareness; } /// <summary> /// Fixture set up. /// </summary> [TestFixtureSetUp] public virtual void FixtureSetUp() { var cfg = GetIgniteConfiguration(); Ignition.Start(cfg); for (var i = 1; i < _gridCount; i++) { cfg = GetIgniteConfiguration(); cfg.IgniteInstanceName = i.ToString(); Ignition.Start(cfg); } Client = GetClient(); } /// <summary> /// Fixture tear down. /// </summary> [TestFixtureTearDown] public void FixtureTearDown() { Ignition.StopAll(true); Client.Dispose(); } /// <summary> /// Sets up the test. /// </summary> [SetUp] public virtual void TestSetUp() { var cache = GetCache<int>(); cache.RemoveAll(); cache.Clear(); Assert.AreEqual(0, cache.GetSize(CachePeekMode.All)); Assert.AreEqual(0, GetClientCache<int>().GetSize(CachePeekMode.All)); ClearLoggers(); } /// <summary> /// Gets the client. /// </summary> public IIgniteClient Client { get; set; } /// <summary> /// Gets Ignite. /// </summary> protected static IIgnite GetIgnite(int? idx = null) { if (idx == null) { return Ignition.GetAll().First(i => i.Name == null); } return Ignition.GetIgnite(idx.ToString()); } /// <summary> /// Gets the cache. /// </summary> protected static ICache<int, T> GetCache<T>() { return Ignition.GetAll().First().GetOrCreateCache<int, T>(CacheName); } /// <summary> /// Gets the client cache. /// </summary> protected ICacheClient<int, T> GetClientCache<T>() { return GetClientCache<int, T>(); } /// <summary> /// Gets the client cache. /// </summary> protected virtual ICacheClient<TK, TV> GetClientCache<TK, TV>(string cacheName = CacheName) { return Client.GetCache<TK, TV>(cacheName ?? CacheName); } /// <summary> /// Gets the client. /// </summary> protected IIgniteClient GetClient() { return Ignition.StartClient(GetClientConfiguration()); } /// <summary> /// Gets the client configuration. /// </summary> protected virtual IgniteClientConfiguration GetClientConfiguration() { var port = _enableSsl ? 11110 : IgniteClientConfiguration.DefaultPort; return new IgniteClientConfiguration { Endpoints = new List<string> {IPAddress.Loopback + ":" + port}, SocketTimeout = TimeSpan.FromSeconds(15), Logger = new ListLogger(new ConsoleLogger {MinLevel = LogLevel.Trace}), SslStreamFactory = _enableSsl ? new SslStreamFactory { CertificatePath = Path.Combine("Config", "Client", "thin-client-cert.pfx"), CertificatePassword = "123456", SkipServerCertificateValidation = true, CheckCertificateRevocation = true, #if !NETCOREAPP SslProtocols = SslProtocols.Tls #else SslProtocols = SslProtocols.Tls12 #endif } : null, EnablePartitionAwareness = _enablePartitionAwareness }; } /// <summary> /// Gets the Ignite configuration. /// </summary> protected virtual IgniteConfiguration GetIgniteConfiguration() { return new IgniteConfiguration(TestUtils.GetTestConfiguration()) { Logger = new ListLogger(new TestUtils.TestContextLogger()), SpringConfigUrl = _enableSsl ? Path.Combine("Config", "Client", "server-with-ssl.xml") : null }; } /// <summary> /// Converts object to binary form. /// </summary> private IBinaryObject ToBinary(object o) { return Client.GetBinary().ToBinary<IBinaryObject>(o); } /// <summary> /// Gets the binary cache. /// </summary> protected ICacheClient<int, IBinaryObject> GetBinaryCache() { return Client.GetCache<int, Person>(CacheName).WithKeepBinary<int, IBinaryObject>(); } /// <summary> /// Gets the binary key cache. /// </summary> protected ICacheClient<IBinaryObject, int> GetBinaryKeyCache() { return Client.GetCache<Person, int>(CacheName).WithKeepBinary<IBinaryObject, int>(); } /// <summary> /// Gets the binary key-val cache. /// </summary> protected ICacheClient<IBinaryObject, IBinaryObject> GetBinaryKeyValCache() { return Client.GetCache<Person, Person>(CacheName).WithKeepBinary<IBinaryObject, IBinaryObject>(); } /// <summary> /// Gets the binary person. /// </summary> protected IBinaryObject GetBinaryPerson(int id) { return ToBinary(new Person(id) { DateTime = DateTime.MinValue.ToUniversalTime() }); } /// <summary> /// Gets the logs. /// </summary> protected static List<ListLogger.Entry> GetLogs(IIgniteClient client) { var igniteClient = (IgniteClient) client; var logger = igniteClient.GetConfiguration().Logger; var listLogger = (ListLogger) logger; return listLogger.Entries; } /// <summary> /// Gets client request names for a given server node. /// </summary> protected static IEnumerable<string> GetServerRequestNames(int serverIndex = 0, string prefix = null) { var instanceName = serverIndex == 0 ? null : serverIndex.ToString(); var grid = Ignition.GetIgnite(instanceName); var logger = (ListLogger) grid.Logger; return GetServerRequestNames(logger, prefix); } /// <summary> /// Gets client request names from a given logger. /// </summary> protected static IEnumerable<string> GetServerRequestNames(ListLogger logger, string prefix = null) { // Full request class name examples: // org.apache.ignite.internal.processors.platform.client.binary.ClientBinaryTypeGetRequest // org.apache.ignite.internal.processors.platform.client.cache.ClientCacheGetRequest var messageRegex = new Regex( @"Client request received \[reqId=\d+, addr=/127.0.0.1:\d+, " + @"req=org\.apache\.ignite\.internal\.processors\.platform\.client\..*?" + prefix + @"(\w+)Request@"); return logger.Entries .Select(m => messageRegex.Match(m.Message)) .Where(m => m.Success) .Select(m => m.Groups[1].Value); } /// <summary> /// Gets client request names from all server nodes. /// </summary> protected static IEnumerable<string> GetAllServerRequestNames(string prefix = null) { return GetLoggers().SelectMany(l => GetServerRequestNames(l, prefix)); } /// <summary> /// Gets loggers from all server nodes. /// </summary> protected static IEnumerable<ListLogger> GetLoggers() { return Ignition.GetAll() .OrderBy(i => i.Name) .Select(i => i.Logger) .Cast<ListLogger>(); } /// <summary> /// Clears loggers of all server nodes. /// </summary> protected static void ClearLoggers() { foreach (var logger in GetLoggers()) { logger.Clear(); } } /// <summary> /// Asserts the client configs are equal. /// </summary> public static void AssertClientConfigsAreEqual(CacheClientConfiguration cfg, CacheClientConfiguration cfg2) { if (cfg2.QueryEntities != null) { // Remove identical aliases which are added during config roundtrip. foreach (var e in cfg2.QueryEntities) { e.Aliases = e.Aliases.Where(x => x.Alias != x.FullName).ToArray(); } } HashSet<string> ignoredProps = null; if (cfg.ExpiryPolicyFactory != null && cfg2.ExpiryPolicyFactory != null) { ignoredProps = new HashSet<string> {"ExpiryPolicyFactory"}; AssertExtensions.ReflectionEqual(cfg.ExpiryPolicyFactory.CreateInstance(), cfg2.ExpiryPolicyFactory.CreateInstance()); } AssertExtensions.ReflectionEqual(cfg, cfg2, ignoredProperties : ignoredProps); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using System.Threading; using System.Windows.Threading; using Microsoft.CodeAnalysis.Editor.Shared.Threading; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Threading { public class AsynchronousWorkerTests { private readonly SynchronizationContext _foregroundSyncContext; public AsynchronousWorkerTests() { TestWorkspace.ResetThreadAffinity(); SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext()); _foregroundSyncContext = SynchronizationContext.Current; Assert.NotNull(_foregroundSyncContext); } // Ensure a background action actually runs on the background. [Fact] public void TestBackgroundAction() { var listener = new AggregateAsynchronousOperationListener(Enumerable.Empty<Lazy<IAsynchronousOperationListener, FeatureMetadata>>(), "Test"); var worker = new AsynchronousSerialWorkQueue(listener); var doneEvent = new AutoResetEvent(initialState: false); var actionRan = false; worker.EnqueueBackgroundWork(() => { // Assert.NotNull(SynchronizationContext.Current); Assert.NotSame(_foregroundSyncContext, SynchronizationContext.Current); actionRan = true; doneEvent.Set(); }, GetType().Name + ".TestBackgroundAction", CancellationToken.None); doneEvent.WaitOne(); Assert.True(actionRan); } [Fact] public void TestMultipleBackgroundAction() { // Test that background actions don't run at the same time. var listener = new AggregateAsynchronousOperationListener(Enumerable.Empty<Lazy<IAsynchronousOperationListener, FeatureMetadata>>(), "Test"); var worker = new AsynchronousSerialWorkQueue(listener); var doneEvent = new AutoResetEvent(false); var action1Ran = false; var action2Ran = false; worker.EnqueueBackgroundWork(() => { Assert.NotSame(_foregroundSyncContext, SynchronizationContext.Current); action1Ran = true; // Simulate work to ensure that if tasks overlap that we will // see it. Thread.Sleep(1000); Assert.False(action2Ran); }, "Test", CancellationToken.None); worker.EnqueueBackgroundWork(() => { Assert.NotSame(_foregroundSyncContext, SynchronizationContext.Current); action2Ran = true; doneEvent.Set(); }, "Test", CancellationToken.None); doneEvent.WaitOne(); Assert.True(action1Ran); Assert.True(action2Ran); } [Fact] public void TestBackgroundCancel1() { // Ensure that we can cancel a background action. var listener = new AggregateAsynchronousOperationListener(Enumerable.Empty<Lazy<IAsynchronousOperationListener, FeatureMetadata>>(), "Test"); var worker = new AsynchronousSerialWorkQueue(listener); var taskRunningEvent = new AutoResetEvent(false); var cancelEvent = new AutoResetEvent(false); var doneEvent = new AutoResetEvent(false); var source = new CancellationTokenSource(); var cancellationToken = source.Token; var actionRan = false; worker.EnqueueBackgroundWork(() => { actionRan = true; Assert.NotSame(_foregroundSyncContext, SynchronizationContext.Current); Assert.False(cancellationToken.IsCancellationRequested); taskRunningEvent.Set(); cancelEvent.WaitOne(); Assert.True(cancellationToken.IsCancellationRequested); doneEvent.Set(); }, "Test", source.Token); taskRunningEvent.WaitOne(); source.Cancel(); cancelEvent.Set(); doneEvent.WaitOne(); Assert.True(actionRan); } [Fact] public void TestBackgroundCancelOneAction() { // Ensure that when a background action is cancelled the next // one starts (if it has a different cancellation token). var listener = new AggregateAsynchronousOperationListener(Enumerable.Empty<Lazy<IAsynchronousOperationListener, FeatureMetadata>>(), "Test"); var worker = new AsynchronousSerialWorkQueue(listener); var taskRunningEvent = new AutoResetEvent(false); var cancelEvent = new AutoResetEvent(false); var doneEvent = new AutoResetEvent(false); var source1 = new CancellationTokenSource(); var source2 = new CancellationTokenSource(); var token1 = source1.Token; var token2 = source2.Token; var action1Ran = false; var action2Ran = false; worker.EnqueueBackgroundWork(() => { action1Ran = true; Assert.NotSame(_foregroundSyncContext, SynchronizationContext.Current); Assert.False(token1.IsCancellationRequested); taskRunningEvent.Set(); cancelEvent.WaitOne(); token1.ThrowIfCancellationRequested(); Assert.True(false); }, "Test", source1.Token); worker.EnqueueBackgroundWork(() => { action2Ran = true; Assert.NotSame(_foregroundSyncContext, SynchronizationContext.Current); Assert.False(token2.IsCancellationRequested); taskRunningEvent.Set(); cancelEvent.WaitOne(); doneEvent.Set(); }, "Test", source2.Token); // Wait for the first task to start. taskRunningEvent.WaitOne(); // Cancel it source1.Cancel(); cancelEvent.Set(); // Wait for the second task to start. taskRunningEvent.WaitOne(); cancelEvent.Set(); // Wait for the second task to complete. doneEvent.WaitOne(); Assert.True(action1Ran); Assert.True(action2Ran); } [Fact] public void TestBackgroundCancelMultipleActions() { // Ensure that multiple background actions are cancelled if they // use the same cancellation token. var listener = new AggregateAsynchronousOperationListener(Enumerable.Empty<Lazy<IAsynchronousOperationListener, FeatureMetadata>>(), "Test"); var worker = new AsynchronousSerialWorkQueue(listener); var taskRunningEvent = new AutoResetEvent(false); var cancelEvent = new AutoResetEvent(false); var doneEvent = new AutoResetEvent(false); var source = new CancellationTokenSource(); var cancellationToken = source.Token; var action1Ran = false; var action2Ran = false; worker.EnqueueBackgroundWork(() => { action1Ran = true; Assert.NotSame(_foregroundSyncContext, SynchronizationContext.Current); Assert.False(cancellationToken.IsCancellationRequested); taskRunningEvent.Set(); cancelEvent.WaitOne(); cancellationToken.ThrowIfCancellationRequested(); Assert.True(false); }, "Test", source.Token); // We should not run this action. worker.EnqueueBackgroundWork(() => { action2Ran = true; Assert.False(true); }, "Test", source.Token); taskRunningEvent.WaitOne(); source.Cancel(); cancelEvent.Set(); try { worker.WaitUntilCompletion_ForTestingPurposesOnly(); Assert.True(false); } catch (AggregateException ae) { Assert.IsAssignableFrom<OperationCanceledException>(ae.InnerException); } Assert.True(action1Ran); Assert.False(action2Ran); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Xunit; namespace Test { public class SumTests { public static IEnumerable<object[]> SumData(int[] counts) { foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), x => Functions.SumRange(0L, x))) yield return results; } // // Sum // [Theory] [MemberData("SumData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Sum_Int(Labeled<ParallelQuery<int>> labeled, int count, int sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(sum, query.Sum()); Assert.Equal(sum, query.Select(x => (int?)x).Sum()); Assert.Equal(default(int), query.Select(x => (int?)null).Sum()); Assert.Equal(-sum, query.Sum(x => -x)); Assert.Equal(-sum, query.Sum(x => -(int?)x)); Assert.Equal(default(int), query.Sum(x => (int?)null)); } [Theory] [MemberData("SumData", (object)(new int[] { 1, 2, 16 }))] public static void Sum_Int_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, int sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (int?)x : null).Sum()); Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(int?)x : null)); } [Theory] [MemberData("SumData", (object)(new int[] { 1, 2, 16 }))] public static void Sum_Int_AllNull(Labeled<ParallelQuery<int>> labeled, int count, int sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => (int?)null).Sum()); Assert.Equal(0, query.Sum(x => (int?)null)); } [Theory] [OuterLoop] [MemberData("SumData", (object)(new int[] { 1024 * 4, 1024 * 64 }))] public static void Sum_Int_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int sum) { Sum_Int(labeled, count, sum); } [Theory] [MemberData("SumData", (object)(new int[] { 2 }))] public static void Sum_Int_Overflow(Labeled<ParallelQuery<int>> labeled, int count, int sum) { Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? int.MaxValue : x).Sum()); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? int.MaxValue : (int?)x).Sum()); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? int.MinValue : -x)); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? int.MinValue : -(int?)x)); } [Theory] [MemberData("SumData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Sum_Long(Labeled<ParallelQuery<int>> labeled, int count, long sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(sum, query.Select(x => (long)x).Sum()); Assert.Equal(sum, query.Select(x => (long?)x).Sum()); Assert.Equal(default(long), query.Select(x => (long?)null).Sum()); Assert.Equal(-sum, query.Sum(x => -(long)x)); Assert.Equal(-sum, query.Sum(x => -(long?)x)); Assert.Equal(default(long), query.Sum(x => (long?)null)); } [Theory] [OuterLoop] [MemberData("SumData", (object)(new int[] { 1024 * 4, 1024 * 1024 }))] public static void Sum_Long_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, long sum) { Sum_Long(labeled, count, sum); } [Theory] [MemberData("SumData", (object)(new int[] { 1, 2, 16 }))] public static void Sum_Long_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, long sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Functions.SumRange(0L, count / 2), query.Select(x => x < count / 2 ? (long?)x : null).Sum()); Assert.Equal(-Functions.SumRange(0L, count / 2), query.Sum(x => x < count / 2 ? -(long?)x : null)); } [Theory] [MemberData("SumData", (object)(new int[] { 1, 2, 16 }))] public static void Sum_Long_AllNull(Labeled<ParallelQuery<int>> labeled, int count, long sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => (long?)null).Sum()); Assert.Equal(0, query.Sum(x => (long?)null)); } [Theory] [MemberData("SumData", (object)(new int[] { 2 }))] public static void Sum_Long_Overflow(Labeled<ParallelQuery<int>> labeled, int count, int sum) { Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? long.MaxValue : x).Sum()); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? long.MaxValue : (long?)x).Sum()); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? long.MinValue : -x)); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? long.MinValue : -(long?)x)); } [Theory] [MemberData("SumData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Sum_Float(Labeled<ParallelQuery<int>> labeled, int count, float sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(sum, query.Select(x => (float)x).Sum()); Assert.Equal(sum, query.Select(x => (float?)x).Sum()); Assert.Equal(default(float), query.Select(x => (float?)null).Sum()); Assert.Equal(-sum, query.Sum(x => -(float)x)); Assert.Equal(-sum, query.Sum(x => -(float?)x)); Assert.Equal(default(float), query.Sum(x => (float?)null)); } [Theory] [OuterLoop] [MemberData("SumData", (object)(new int[] { 1024 * 4, 1024 * 1024 }))] public static void Sum_Float_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, float sum) { Sum_Float(labeled, count, sum); } [Theory] [MemberData("SumData", (object)(new int[] { 2 }))] public static void Sum_Float_Overflow(Labeled<ParallelQuery<int>> labeled, int count, int sum) { Assert.True(float.IsInfinity(labeled.Item.Select(x => float.MaxValue).Sum())); Assert.True(float.IsInfinity(labeled.Item.Select(x => (float?)float.MaxValue).Sum().Value)); Assert.True(float.IsInfinity(labeled.Item.Sum(x => float.MinValue))); Assert.True(float.IsInfinity(labeled.Item.Sum(x => (float?)float.MaxValue).Value)); } [Theory] [MemberData("SumData", (object)(new int[] { 1, 2, 16 }))] public static void Sum_Float_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, float sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (float?)x : null).Sum()); Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(float?)x : null)); } [Theory] [MemberData("SumData", (object)(new int[] { 1, 2, 16 }))] public static void Sum_Float_AllNull(Labeled<ParallelQuery<int>> labeled, int count, float sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => (float?)null).Sum()); Assert.Equal(0, query.Sum(x => (float?)null)); } [Theory] [MemberData("SumData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Sum_Double(Labeled<ParallelQuery<int>> labeled, int count, double sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(sum, query.Select(x => (double)x).Sum()); Assert.Equal(sum, query.Select(x => (double?)x).Sum()); Assert.Equal(default(double), query.Select(x => (double?)null).Sum()); Assert.Equal(-sum, query.Sum(x => -(double)x)); Assert.Equal(-sum, query.Sum(x => -(double?)x)); Assert.Equal(default(double), query.Sum(x => (double?)null)); } [Theory] [OuterLoop] [MemberData("SumData", (object)(new int[] { 1024 * 4, 1024 * 1024 }))] public static void Sum_Double_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, double sum) { Sum_Double(labeled, count, sum); } [Theory] [MemberData("SumData", (object)(new int[] { 2 }))] public static void Sum_Double_Overflow(Labeled<ParallelQuery<int>> labeled, int count, int sum) { Assert.True(double.IsInfinity(labeled.Item.Select(x => double.MaxValue).Sum())); Assert.True(double.IsInfinity(labeled.Item.Select(x => (double?)double.MaxValue).Sum().Value)); Assert.True(double.IsInfinity(labeled.Item.Sum(x => double.MinValue))); Assert.True(double.IsInfinity(labeled.Item.Sum(x => (double?)double.MaxValue).Value)); } [Theory] [MemberData("SumData", (object)(new int[] { 1, 2, 16 }))] public static void Sum_Double_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, double sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (double?)x : null).Sum()); Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(double?)x : null)); } [Theory] [MemberData("SumData", (object)(new int[] { 1, 2, 16 }))] public static void Sum_Double_AllNull(Labeled<ParallelQuery<int>> labeled, int count, double sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => (double?)null).Sum()); Assert.Equal(0, query.Sum(x => (double?)null)); } [Theory] [MemberData("SumData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Sum_Decimal(Labeled<ParallelQuery<int>> labeled, int count, decimal sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(sum, query.Select(x => (decimal)x).Sum()); Assert.Equal(sum, query.Select(x => (decimal?)x).Sum()); Assert.Equal(default(decimal), query.Select(x => (decimal?)null).Sum()); Assert.Equal(-sum, query.Sum(x => -(decimal)x)); Assert.Equal(default(decimal), query.Sum(x => (decimal?)null)); } [Theory] [OuterLoop] [MemberData("SumData", (object)(new int[] { 1024 * 4, 1024 * 1024 }))] public static void Sum_Decimal_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, decimal sum) { Sum_Decimal(labeled, count, sum); } [Theory] [MemberData("SumData", (object)(new int[] { 2 }))] public static void Sum_Decimal_Overflow(Labeled<ParallelQuery<int>> labeled, int count, int sum) { Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? decimal.MaxValue : x).Sum()); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? decimal.MaxValue : (decimal?)x).Sum()); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? decimal.MinValue : -x)); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? decimal.MinValue : -(decimal?)x)); } [Theory] [MemberData("SumData", (object)(new int[] { 1, 2, 16 }))] public static void Sum_Decimal_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, decimal sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (decimal?)x : null).Sum()); Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(decimal?)x : null)); } [Theory] [MemberData("SumData", (object)(new int[] { 1, 2, 16 }))] public static void Sum_Decimal_AllNull(Labeled<ParallelQuery<int>> labeled, int count, decimal sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => (decimal?)null).Sum()); Assert.Equal(0, query.Sum(x => (decimal?)null)); } [Theory] [MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))] public static void Sum_OperationCanceledException_PreCanceled(Labeled<ParallelQuery<int>> labeled, int count) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (int?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (long)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (long?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (float)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (float?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (double)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (double?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (decimal)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (decimal?)x)); } [Theory] [MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))] public static void Sum_AggregateException(Labeled<ParallelQuery<int>> labeled, int count) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, int>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, int?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, long>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, long?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, float>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, float?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, double>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, double?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, decimal>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, decimal?>)(x => { throw new DeliberateTestException(); }))); } [Fact] public static void Sum_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat(0, 1).Sum((Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int?>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((int?)0, 1).Sum((Func<int?, int?>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long)0, 1).Sum((Func<long, long>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long?>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long?)0, 1).Sum((Func<long?, long?>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float)0, 1).Sum((Func<float, float>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float?>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float?)0, 1).Sum((Func<float?, float>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double)0, 1).Sum((Func<double, double>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double?>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double?)0, 1).Sum((Func<double?, double>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal)0, 1).Sum((Func<decimal, decimal>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal?>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal?)0, 1).Sum((Func<decimal?, decimal>)null)); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal sealed partial class SolutionCrawlerRegistrationService { private sealed partial class WorkCoordinator { private sealed partial class IncrementalAnalyzerProcessor { private sealed class LowPriorityProcessor : GlobalOperationAwareIdleProcessor { private readonly Lazy<ImmutableArray<IIncrementalAnalyzer>> _lazyAnalyzers; private readonly AsyncProjectWorkItemQueue _workItemQueue; public LowPriorityProcessor( IAsynchronousOperationListener listener, IncrementalAnalyzerProcessor processor, Lazy<ImmutableArray<IIncrementalAnalyzer>> lazyAnalyzers, IGlobalOperationNotificationService globalOperationNotificationService, int backOffTimeSpanInMs, CancellationToken shutdownToken) : base(listener, processor, globalOperationNotificationService, backOffTimeSpanInMs, shutdownToken) { _lazyAnalyzers = lazyAnalyzers; _workItemQueue = new AsyncProjectWorkItemQueue(processor._registration.ProgressReporter); Start(); } internal ImmutableArray<IIncrementalAnalyzer> Analyzers { get { return _lazyAnalyzers.Value; } } protected override Task WaitAsync(CancellationToken cancellationToken) { return _workItemQueue.WaitAsync(cancellationToken); } protected override async Task ExecuteAsync() { try { // we wait for global operation, higher and normal priority processor to finish its working await WaitForHigherPriorityOperationsAsync().ConfigureAwait(false); // process any available project work, preferring the active project. WorkItem workItem; CancellationTokenSource projectCancellation; if (_workItemQueue.TryTakeAnyWork(this.Processor.GetActiveProject(), this.Processor.DependencyGraph, out workItem, out projectCancellation)) { await ProcessProjectAsync(this.Analyzers, workItem, projectCancellation).ConfigureAwait(false); } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } protected override Task HigherQueueOperationTask { get { return Task.WhenAll(this.Processor._highPriorityProcessor.Running, this.Processor._normalPriorityProcessor.Running); } } protected override bool HigherQueueHasWorkItem { get { return this.Processor._highPriorityProcessor.HasAnyWork || this.Processor._normalPriorityProcessor.HasAnyWork; } } protected override void PauseOnGlobalOperation() { _workItemQueue.RequestCancellationOnRunningTasks(); } public void Enqueue(WorkItem item) { this.UpdateLastAccessTime(); // Project work item = item.With(documentId: null, projectId: item.ProjectId, asyncToken: this.Processor._listener.BeginAsyncOperation("WorkItem")); var added = _workItemQueue.AddOrReplace(item); // lower priority queue gets lowest time slot possible. if there is any activity going on in higher queue, it drop whatever it has // and let higher work item run CancelRunningTaskIfHigherQueueHasWorkItem(); Logger.Log(FunctionId.WorkCoordinator_Project_Enqueue, s_enqueueLogger, Environment.TickCount, item.ProjectId, !added); SolutionCrawlerLogger.LogWorkItemEnqueue(this.Processor._logAggregator, item.ProjectId); } private void CancelRunningTaskIfHigherQueueHasWorkItem() { if (!HigherQueueHasWorkItem) { return; } _workItemQueue.RequestCancellationOnRunningTasks(); } private async Task ProcessProjectAsync(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, CancellationTokenSource source) { if (this.CancellationToken.IsCancellationRequested) { return; } // we do have work item for this project var projectId = workItem.ProjectId; var processedEverything = false; var processingSolution = this.Processor.CurrentSolution; try { using (Logger.LogBlock(FunctionId.WorkCoordinator_ProcessProjectAsync, source.Token)) { var cancellationToken = source.Token; var project = processingSolution.GetProject(projectId); if (project != null) { var semanticsChanged = workItem.InvocationReasons.Contains(PredefinedInvocationReasons.SemanticChanged) || workItem.InvocationReasons.Contains(PredefinedInvocationReasons.SolutionRemoved); if (project.Solution.Services.CacheService != null) { using (project.Solution.Services.CacheService.EnableCaching(project.Id)) { await RunAnalyzersAsync(analyzers, project, (a, p, c) => a.AnalyzeProjectAsync(p, semanticsChanged, c), cancellationToken).ConfigureAwait(false); } } else { await RunAnalyzersAsync(analyzers, project, (a, p, c) => a.AnalyzeProjectAsync(p, semanticsChanged, c), cancellationToken).ConfigureAwait(false); } } else { SolutionCrawlerLogger.LogProcessProjectNotExist(this.Processor._logAggregator); RemoveProject(projectId); } } processedEverything = true; } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } finally { // we got cancelled in the middle of processing the project. // let's make sure newly enqueued work item has all the flag needed. if (!processedEverything) { _workItemQueue.AddOrReplace(workItem.Retry(this.Listener.BeginAsyncOperation("ReenqueueWorkItem"))); } SolutionCrawlerLogger.LogProcessProject(this.Processor._logAggregator, projectId.Id, processedEverything); // remove one that is finished running _workItemQueue.RemoveCancellationSource(projectId); } } private void RemoveProject(ProjectId projectId) { foreach (var analyzer in this.Analyzers) { analyzer.RemoveProject(projectId); } } public override void Shutdown() { base.Shutdown(); _workItemQueue.Dispose(); } internal void WaitUntilCompletion_ForTestingPurposesOnly(ImmutableArray<IIncrementalAnalyzer> analyzers, List<WorkItem> items) { CancellationTokenSource source = new CancellationTokenSource(); var uniqueIds = new HashSet<ProjectId>(); foreach (var item in items) { if (uniqueIds.Add(item.ProjectId)) { ProcessProjectAsync(analyzers, item, source).Wait(); } } } internal void WaitUntilCompletion_ForTestingPurposesOnly() { // this shouldn't happen. would like to get some diagnostic while (_workItemQueue.HasAnyWork) { Environment.FailFast("How?"); } } } } } } }
using System; using System.Collections.Generic; using NUnit.Framework; using SimpleContainer.Infection; using SimpleContainer.Tests.Helpers; namespace SimpleContainer.Tests { public abstract class GetDependenciesTest : SimpleContainerTestBase { public class NoConstructors_NoDependencies : GetDependenciesTest { public class A { } [Test] public void Test() { var container = Container(); Assert.That(container.GetDependencies(typeof (A)), Is.Empty); } } public class Simple : GetDependenciesTest { public class A { public A(B b) { } } public class B { } [Test] public void Test() { var container = Container(); Assert.That(container.GetDependencies(typeof (A)), Is.EqualTo(new[] {typeof (B)})); } } public class GetDependenciesForInjections : GetDependenciesTest { public class A { #pragma warning disable 169 [Inject] private B b; #pragma warning restore 169 } public class B { } [Test] public void Test() { var container = Container(); Assert.That(container.GetDependencies(typeof (A)), Is.EqualTo(new[] {typeof (B)})); } } public class GetDependenciesForInjectionsInlineEnumerables : GetDependenciesTest { public class A { #pragma warning disable 169 [Inject] private IEnumerable<IIntf> b; #pragma warning restore 169 } public interface IIntf { } [Test] public void Test() { var container = Container(); Assert.That(container.GetDependencies(typeof (A)), Is.EqualTo(new[] {typeof (IIntf)})); } } public class DependencyValues : GetDependenciesTest { public class A { public A(B b) { } } public class B { } [Test] public void Test() { var container = Container(); Assert.That(container.GetDependencyValues(typeof (A)), Is.EqualTo(new object[] {container.Get<B>()})); } } public class Recursive : GetDependenciesTest { public class A { #pragma warning disable 169 [Inject] private B b; #pragma warning restore 169 } public class B { public B(C c) { } } public class C { } [Test] public void Test() { var container = Container(); Assert.That(container.GetDependenciesRecursive(typeof (A)), Is.EquivalentTo(new[] {typeof (B), typeof (C)})); } } public class GetDependencyValuesRecursive : GetDependenciesTest { public class A { #pragma warning disable 169 [Inject] private B b; #pragma warning restore 169 } public class B { public B(C c) { } } public class C { } [Test] public void Test() { var container = Container(); Assert.That(container.GetDependencyValuesRecursive(typeof (A)), Is.EquivalentTo(new object[] {container.Get<B>(), container.Get<C>()})); } } public class Uniqueness : GetDependenciesTest { public class A { public A(B b, C c) { } } public class B { public B(C c) { } } public class C { } [Test] public void Test() { var container = Container(); Assert.That(container.GetDependenciesRecursive(typeof (A)), Is.EquivalentTo(new[] {typeof (B), typeof (C)})); } } public class ManyDependenciesInOneClass : GetDependenciesTest { public class A { public A(B b, C c) { } } public class B { } public class C { } [Test] public void Test() { var container = Container(); Assert.That(container.GetDependenciesRecursive(typeof (A)), Is.EquivalentTo(new[] {typeof (B), typeof (C)})); } } public class InterfacesCannotContainInjections : GetDependenciesTest { public class Class { public Class(IA a) { } } public interface IA { } public class A : IA { } [Test] public void Test() { var container = Container(); Assert.That(container.GetDependencyValuesRecursive(typeof (Class)), Is.EqualTo(new object[] {container.Get<A>()})); } } public class SkipFuncs : GetDependenciesTest { public class Class { public Class(A a, Func<B> getB) { } } public class B { } public class A { } [Test] public void Test() { var container = Container(); Assert.That(container.GetDependencyValuesRecursive(typeof (Class)), Is.EqualTo(new object[] {container.Get<A>()})); } } public class SkipSimpleTypes : GetDependenciesTest { public class Class { public Class(B b, int a, string[] strs) { } } public class B { } [Test] public void Test() { var container = Container(); Assert.That(container.GetDependencyValuesRecursive(typeof (Class)), Is.EqualTo(new object[] {container.Get<B>()})); } } public class SkipExplicitlyConfiguredDependencyValues : GetDependenciesTest { public class X { public readonly Y y; public X(Y y) { this.y = y; } } public class Y { } [Test] public void Test() { var container = Container(x => x.BindDependency<X>("y", new Y())); Assert.That(container.GetDependencies(typeof (X)), Is.Empty); } } public class SkipExplicitlyConfiguredServices : GetDependenciesTest { public class X { public readonly Y y; public X(Y y) { this.y = y; } } public class Y { } [Test] public void Test() { var container = Container(x => x.Bind<Y>(new Y())); Assert.That(container.GetDependencies(typeof (X)), Is.Empty); } } public class SkipDependenciesWithFactories : GetDependenciesTest { public class X { public readonly Y y; public X(Y y) { this.y = y; } } public class Y { } [Test] public void Test() { var container = Container(x => x.BindDependencyFactory<X>("y", _ => new Y())); Assert.That(container.GetDependencies(typeof (X)), Is.Empty); } } public class Enumerable : GetDependenciesTest { public class Class { public Class(IEnumerable<IB> b) { } } public interface IB { } public class B1 : IB { } public class B2 : IB { } [Test] public void Test() { var container = Container(); Assert.That(container.GetDependencyValuesRecursive(typeof (Class)), Is.EquivalentTo(new object[] {container.Get<B1>(), container.Get<B2>()})); } } } }
/* Copyright (c) 2009-11, ReactionGrid Inc. http://reactiongrid.com * See License.txt for full licence information. * * ChatController.cs Revision 1.3.1105.25 * Controls all chat functionality */ using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using ReactionGrid.Jibe; using System.Text.RegularExpressions; using System.IO; public class ChatController : MonoBehaviour { public GUISkin skin; private Vector2 scrollPosition; private int PaddingHoriz = 4; private int PaddingVert = 56; public int WindowWidth = 360; public int WindowHeight = 400; public bool showChatWindow = true; // can be set in inspector to show or hide chat window by default private bool resizewindow = false; public int maxMessageHistoryDisplay = 100; // more messages to display is more of a hit on performance - limit this as much as possible and use logging or export for full history public Texture2D[] backgroundStyles; // choose window background style private int blink = 50; private float sizeX = 0; private float sizeY = 0; // Keep all chat message history here, the key of the pair is the chat ID (0 = public, non-zero is avatar ID for a private chat) // Note that this will store the entire chat history with some good metadata so you can export it later! public Dictionary<int, List<ChatMessage>> messages = new Dictionary<int, List<ChatMessage>>(); public Dictionary<string, Dictionary<int, List<ChatMessage>>> groupMessages = new Dictionary<string, Dictionary<int, List<ChatMessage>>>(); // Available background styles - alternatives for private chat easy identification public Dictionary<int, int> messageBackgrounds = new Dictionary<int, int>(); private List<int> unreadMessages = new List<int>(); private int currentUnreadCount = 0; private int activeChat = 0; public bool groupChatEnabled; // Set of private variables to store window sizes private Rect chatWindow; private Rect messagesWindow; private Rect userMessageWindow; private Rect privateMessageWindow; private Rect privateMessageWindowLabel; private string userMessage = ""; private int userMessageLengthLastCheck = 0; // User Is Typing settings public float typingDelay = 1.0f; private float typingTime = 0.0f; public string typingIndicator = " ... "; // Message sounds public AudioClip messageSound; public float messageSoundVolume = 0.5f; // Combination of character and camera controls are needed when resizing the chat window. lost focus will disable chat (chatModeEnabled) etc. private GameObject character; private GameObject localPlayer; private GameObject playerCam; private bool resizing = false; private bool chatModeEnabled = false; // Show/hide functionality private float messageReceivedTime = 0.0f; public float messageShowTime = 5.0f; public float messageFadeTime = 5.0f; private bool showMessagesReceivedWhileChatMinimized = false; // Chat message tweaks private string chatButtonText = "Public Chat"; public string hideChatPrompt = "Public Chat"; public string showChatPrompt = "Public Chat"; private bool showTimeStamp = true; private Color guiColor; private Color guiTextColor; private float transparency; // Welcome message handy for greeting users in the Jibe space public bool showWelcomeMessage = true; public string[] welcomeMessages; public bool hideInstantlyIfNoMessagesReceived = false; public bool continualChatHistoryExport = true; private Vector3 mousepos; private string privateMessage = ""; private int privateMessageRecipient = -1; private float chatDistanceLimit = 15; public NetworkController networkController; public GameObject cursor; private Rect roomListWindow; private Vector2 roomScrollPosition; private bool showRoomList = false; public Texture2D roomListUnreadMessagesIndicator; public Texture2D[] chatIcons; public Texture2D[] voiceIcons; public Texture2D resizeIcon; public string chatWindowName = "Public Chat"; // Web Chat Export public bool logChatToWeb = true; WWW webChatStoreRequest; public string chatStoreUrl = ""; private Dictionary<string, bool> notificationShow = new Dictionary<string, bool>(); //keeps track of whether to show the new chat message for diferrent groups public Texture2D newMessageNotificationColor; public Texture2D newMessageNotificationColorScrollOver; private string currentGroup = "GlobalChat"; public Texture2D currentChatTexture; public Texture2D currentChatTextureScrollOver; public bool permissionToStoreMessagesToDatabase = false; //only want one person to be logging the chat to the database, to prevent the same thing being done multiple times void Start() { messages[0] = new List<ChatMessage>(); messageBackgrounds[0] = 0; guiColor = GUI.color; guiTextColor = GUI.contentColor; chatWindow = new Rect(Screen.width - WindowWidth - PaddingHoriz, Screen.height - WindowHeight - PaddingVert, WindowWidth, WindowHeight); messagesWindow = new Rect(Screen.width - WindowWidth - PaddingHoriz, Screen.height - WindowHeight - PaddingVert, WindowWidth, WindowHeight); userMessageWindow = new Rect(100, Screen.height - 23, Screen.width - 355, 22); roomListWindow = new Rect(4, Screen.height - 326, 160, 300); privateMessageWindow = new Rect(100, Screen.height - 23, Screen.width - 200, 22); privateMessageWindowLabel = new Rect(100, Screen.height - 40, 120, 22); roomListWindow = new Rect(4, Screen.height - 326, 160, 300); sizeX = chatWindow.xMin; sizeY = chatWindow.yMin; character = GameObject.FindGameObjectWithTag("Character"); if (networkController == null) { networkController = GameObject.Find("NetworkController").GetComponent<NetworkController>(); } if (cursor == null) cursor = GameObject.Find("Cursor"); // TO REMOVE THE WELCOME MESSAGE // remove these lines. if (showWelcomeMessage) { foreach (string msg in welcomeMessages) { AddChatMessage(msg, ""); } } } void OnMouseUp() { if (resizing) { if (playerCam != null && playerCam.GetComponent<Camera>().enabled) playerCam.SendMessage("SetCameraEnabled", true); resizing = false; } } void OnGUI() { blink--; if(blink==0) { blink=50; Texture2D filler = newMessageNotificationColor; newMessageNotificationColor=newMessageNotificationColorScrollOver; newMessageNotificationColorScrollOver=filler; } bool enterAlreadyUsed = false; GUI.skin = skin; // Choose appropriate text for the show/hide button if (showChatWindow && activeChat == 0 && currentGroup.Equals("GlobalChat")) { chatButtonText = hideChatPrompt; } else if (showChatWindow && activeChat != 0) { chatButtonText = "Public Chat"; } else { chatButtonText = showChatPrompt; } // Draw show/hide button and use it to toggle active / inactive chat mode GUI.SetNextControlName("ChatButton"); float offset=170f; GUIStyle globalChatStyle = new GUIStyle("Button"); if(notificationShow.ContainsKey("GlobalChat") && notificationShow["GlobalChat"]==true) //notifcation of new chat message in globalchat { globalChatStyle.normal.background = newMessageNotificationColor; globalChatStyle.hover.background = newMessageNotificationColorScrollOver; } else if(currentGroup.Equals("GlobalChat") && showChatWindow) { globalChatStyle.normal.background = currentChatTexture; globalChatStyle.hover.background = currentChatTextureScrollOver; } if (GUI.Button(new Rect(Screen.width - 80, Screen.height - 24, 82, 24), chatButtonText, globalChatStyle) || Input.GetKeyDown(KeyCode.Return)) { chatWindowName="Public Chat"; if(!currentGroup.Equals("GlobalChat")) //so that chat doesn't hide if you change group while chat is open { networkController.SetCurrentGroup("GlobalChat",networkController.localPlayer.PlayerID); SwitchGroup("GlobalChat"); notificationShow["GlobalChat"]=false; if(!showChatWindow) { ChatButtonToggled(); } } else { notificationShow["GlobalChat"]=false; ChatButtonToggled(); } } if(networkController.CheckIfLocalPlayerIsInGroup("Management") || networkController.CheckIfLocalPlayerIsInGroup("GlobalChat")) { GUIStyle managementChatStyle = new GUIStyle("Button"); if(notificationShow.ContainsKey("Management") && notificationShow["Management"]==true) //notifcation of new chat message in globalchat { managementChatStyle.normal.background = newMessageNotificationColor; managementChatStyle.hover.background = newMessageNotificationColorScrollOver; } else if(currentGroup.Equals("Management") && showChatWindow) { managementChatStyle.normal.background = currentChatTexture; managementChatStyle.hover.background = currentChatTextureScrollOver; } //placement of management chat gui box if(GUI.Button(new Rect(Screen.width - 165, Screen.height -24, 82, 24), "Management", managementChatStyle)) { chatWindowName="Management Chat"; if(!currentGroup.Equals("Management"))//so that chat doesn't hide if you change group while chat is open { networkController.SetCurrentGroup("Management", networkController.localPlayer.PlayerID); SwitchGroup("Management"); notificationShow["Management"]=false; if(!showChatWindow) { ChatButtonToggled(); } } else { notificationShow["Management"]=false; ChatButtonToggled(); } } offset-=85; } if( networkController.CheckIfLocalPlayerIsInGroup("Union") || networkController.CheckIfLocalPlayerIsInGroup("GlobalChat")) { offset-=85; GUIStyle unionChatStyle = new GUIStyle("Button"); if(notificationShow.ContainsKey("Union") && notificationShow["Union"]==true) //notifcation of new chat message in globalchat { unionChatStyle.normal.background = newMessageNotificationColor; unionChatStyle.hover.background = newMessageNotificationColorScrollOver; } else if(currentGroup.Equals("Union") && showChatWindow) { unionChatStyle.normal.background = currentChatTexture; unionChatStyle.hover.background = currentChatTextureScrollOver; } if(GUI.Button(new Rect(Screen.width - 250+offset, Screen.height -24, 82, 24), "Union", unionChatStyle)) { chatWindowName="Union Chat"; if(!currentGroup.Equals("Union"))//so that chat doesn't hide if you change group while chat is open { networkController.SetCurrentGroup("Union", networkController.localPlayer.PlayerID); SwitchGroup("Union"); notificationShow["Union"] = false; if(!showChatWindow) { ChatButtonToggled(); } } else { notificationShow["Union"] = false; ChatButtonToggled(); } } } GUIStyle roomListButtonStyle = new GUIStyle("Button"); if (unreadMessages.Count > 0) { roomListButtonStyle.normal.background = roomListUnreadMessagesIndicator; roomListButtonStyle.normal.textColor = Color.white; } if (GUI.Button(new Rect(0, Screen.height - 24, 100, 24), showRoomList ? "Hide" : "Online Users", roomListButtonStyle)) { if (showRoomList) { showRoomList = false; } else { showRoomList = true; } } if (showRoomList) { RenderRoomList(); } // If the chat system is currently active and enabled if (showChatWindow) { // Handle a resize request - on resize, disable the player's camera HandleResizing(); // If the user is ready to send a message, they will press the Enter key if (EnterPressed()) { enterAlreadyUsed=true; CheckSendMessages(); Event.current.Use(); } // Set up the window to display chat messages GUIStyle windowStyle = new GUIStyle("ChatMessagesWindow"); windowStyle.normal.background = backgroundStyles[messageBackgrounds[activeChat]]; if (activeChat == 0) { GUIContent windowTitle = new GUIContent(chatWindowName, backgroundStyles[0]); chatWindow = GUI.Window(1, chatWindow, ShowChatWindow, windowTitle, windowStyle); } else { GUIContent windowTitle = new GUIContent("Private Chat: " + networkController.GetRemoteName(activeChat), backgroundStyles[messageBackgrounds[activeChat]]); chatWindow = GUI.Window(1, chatWindow, ShowChatWindow, windowTitle, windowStyle); MarkMessagesAsRead(); } if (chatModeEnabled && activeChat == 0) { // PUBLIC CHAT GUI.SetNextControlName("text"); userMessage = GUI.TextField(new Rect(userMessageWindow.x,userMessageWindow.y,userMessageWindow.width+offset,userMessageWindow.height), userMessage, "ChatTextField"); GUI.FocusControl("text"); } else if (chatModeEnabled && activeChat != 0) { // PRIVATE CHAT GUI.Label(privateMessageWindowLabel, "Send to " + networkController.GetRemoteName(activeChat) + ":", "PrivateChatLabel"); ChoosePrivateMessageBackgroundColor(); GUI.SetNextControlName("privatetext"); privateMessage = GUI.TextField(privateMessageWindow, privateMessage, "ChatTextField"); //this spams whatever is in the text field while you are typing in "Private Message" form Debug.Log("Private message: " + privateMessage); } else { GUI.Label(new Rect(userMessageWindow.x,userMessageWindow.y,userMessageWindow.width+offset,userMessageWindow.height), userMessage, "ChatTextField"); } if (Input.GetKey(KeyCode.Escape))//this allows quick unfocus, re-enabling camera and movement { GUI.UnfocusWindow(); ChatLostFocus(); } if (Input.GetMouseButtonDown(0)) { // Get mouse position mousepos = Input.mousePosition; mousepos.y = Screen.height - mousepos.y; // Did the user click outside of the chat window? if (chatWindow.Contains(mousepos) == false && userMessageWindow.Contains(mousepos) == false && mousepos.x < (Screen.width - 100)) { GUI.UnfocusWindow(); GUI.FocusControl("ChatButton"); ChatLostFocus(); } if (mousepos.y > Screen.height - 40) { // assume click on the text label, convert it back to a live text box ChatMode(true); } } } else // user has chat window hidden { if (showMessagesReceivedWhileChatMinimized) { // Show recent messages as they arrived for a specified period of time messageReceivedTime += Time.deltaTime; if (messageReceivedTime < messageShowTime) { SetTransparency(1); messagesWindow = GUI.Window(1, messagesWindow, ShowChatWindow, "", "ChatWindowNoFocus"); } else if (messageReceivedTime > messageShowTime && messageReceivedTime < (messageShowTime + messageFadeTime)) { // Gradually fade out the chat window float totallyTransparent = messageShowTime + messageFadeTime; float fullyVisible = messageShowTime; transparency = 1 - (messageReceivedTime - fullyVisible) / (totallyTransparent - fullyVisible); SetTransparency(transparency); messagesWindow = GUI.Window(1, messagesWindow, ShowChatWindow, "", "ChatWindowNoFocus"); } else { messageReceivedTime = 0.0f; showMessagesReceivedWhileChatMinimized = false; } } } InitiatePrivateChat(); if(EnterPressed() || enterAlreadyUsed && showChatWindow==false) { ChatButtonToggled(); } } private void RenderRoomList() { GUI.Box(roomListWindow, "Online Users", "ChatMessagesWindow"); GUILayout.BeginArea(roomListWindow); GUI.SetNextControlName("roomscroll"); roomScrollPosition = GUILayout.BeginScrollView(roomScrollPosition); GUILayout.BeginHorizontal(); RenderUserName(networkController.GetLocalPlayer()); GUILayout.EndHorizontal(); foreach (IJibePlayer user in networkController.GetAllUsers()) { GUILayout.BeginHorizontal(); RenderUserName(user); if (chatIcons.Length == 4) { /* chat icons are as follows: * 0 = no chats available * 1 = chat history available * 2 = actively chatting * 3 = unread messages from player */ Texture2D iconToUse = chatIcons[0]; if (messages.ContainsKey(user.PlayerID)) iconToUse = chatIcons[1]; else if (activeChat == user.PlayerID) iconToUse = chatIcons[2]; if (unreadMessages.Contains(user.PlayerID)) iconToUse = chatIcons[3]; if (GUILayout.Button(iconToUse, "PrivateChatButton")) { InitiatePrivateChatById(user.PlayerID, user.Name); } } GUILayout.EndHorizontal(); GUILayout.Space(3); } GUILayout.EndScrollView(); GUILayout.EndArea(); } private void RenderUserName(IJibePlayer user) { GUIStyle voiceIndicatorStyle = new GUIStyle("PrivateChatButton"); switch (user.Voice) { case JibePlayerVoice.IsSpeaking: GUILayout.Label(user.Name, "VoiceUserSpeaking"); if (voiceIcons.Length > 0) { GUILayout.Label(voiceIcons[0], voiceIndicatorStyle); GUILayout.Space(2); } break; case JibePlayerVoice.HasVoice: GUILayout.Label(user.Name, "VoiceUser"); if (voiceIcons.Length > 1) { GUILayout.Label(voiceIcons[1], voiceIndicatorStyle); GUILayout.Space(2); } break; case JibePlayerVoice.None: GUILayout.Label(user.Name, "WindowText"); break; } } private void ChoosePrivateMessageBackgroundColor() { GUIStyle backgroundChooserStyle = new GUIStyle("Button"); backgroundChooserStyle.fixedHeight = 20; backgroundChooserStyle.fixedWidth = 20; // Offer all available background styles for private chat backgrounds. Choice will persist on a chat-by-chat basis messageBackgrounds[activeChat] = GUI.SelectionGrid(new Rect(220, Screen.height - 40, 160, 20), messageBackgrounds[activeChat], backgroundStyles, 6, backgroundChooserStyle); } private void HandleResizing() { // Resizing handled by a RepeatButton - strange concept but this is a pretty good way to handle persistent mouse down drag events! resizewindow = GUI.RepeatButton(GetResizeButton(), resizeIcon, "WindowResize"); Rect closeButtonRect = GetResizeButton(); closeButtonRect.yMax-=10; closeButtonRect.x+=chatWindow.width-10; if(GUI.Button(closeButtonRect, "X")) { GameObject.Find("PlayerCamera").SendMessage("DisableSitThisFrame"); ChatButtonToggled(); } if (resizewindow) { // if (playerCam != null && playerCam.camera.enabled) // playerCam.SendMessage("SetCameraEnabled", false); resizing = true; ResizeChatbox(); } if (ResizeMouseDrag()) { ResizeChatbox(); } if (MouseDrag()) { if (GUI.GetNameOfFocusedControl() == "Chat") { ResizeChatbox(); } } } void Update() { if (showChatWindow) { CheckIsTyping(); } } private void CheckIsTyping() { if (userMessage.Length > 0 && activeChat == 0 && chatModeEnabled) { // player is typing in public // Only show the typing notification for a certain amount of time - if the user is idle too long, they are not deemed to be chatting typingTime += Time.deltaTime; if (typingTime > typingDelay) { if (userMessageLengthLastCheck != userMessage.Length) { userMessageLengthLastCheck = userMessage.Length; AddMyChatMessage(typingIndicator); typingTime = 0; } } } } public void ChangeCurrentChat(int newChat) { if (activeChat != newChat) { Debug.Log("Changing to chat window " + newChat); activeChat = newChat; } scrollPosition.y = 10000000000; // To scroll down the messages window } private void CheckSendMessages() { if (activeChat == 0) { // Send message if there is one to be sent if (userMessage.Length > 0) { AddMyChatMessage(userMessage); userMessage = ""; } } else if (privateMessage.Length > 0) { AddMyPrivateChatMessage(privateMessage); } } private void AddToChatHistory(ChatMessage message) { string messageToSend = message.MessageTime + " " + message.Sender + ": " + message.Message; // Handle this differently for web player to offer history via javascript to containing page if (Application.platform == RuntimePlatform.WebGLPlayer) { // for web player option, sync current chat with hosting web page Application.ExternalCall("ChatHistory", messageToSend); } else { WriteToChatLogFile(messageToSend); } } private static void WriteToChatLogFile(string messageToSend) { string filePath = Path.Combine(Application.dataPath, "chatlog_" + DateTime.Now.ToString("yyyyMMdd") + ".txt"); //Debug.Log(filePath); try { using (FileStream fs = new FileStream(filePath, FileMode.Append)) using (StreamWriter sw = new StreamWriter(fs)) { sw.WriteLine(messageToSend); } } catch (Exception ex) { Debug.LogWarning("Failed to log chat: " + ex.Message + ex.StackTrace); } } private void InitiatePrivateChat() { // Hovering over remote players offers option of initiating a chat on click GameObject playerCam = GameObject.FindGameObjectWithTag("MainCamera"); if (playerCam != null) { if (playerCam.GetComponent<Camera>().enabled) { Ray mouseRay = playerCam.GetComponent<Camera>().ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(mouseRay, out hit, chatDistanceLimit)) { if (hit.transform.tag == "RemotePlayer") { cursor.SendMessage("ShowPrivateChatCursor", true); if (Input.GetMouseButtonDown(0)) { // mildly unpleasant way to extract a user name from a gameobject, but we control both ends of this code and it is not hardcoded beyond the convention of using a prefix string messageRecipient = hit.transform.name.TrimStart(networkController.RemotePlayerGameObjectPrefix.ToCharArray()); if (int.TryParse(messageRecipient, out privateMessageRecipient)) { Debug.Log("Initiate Chat with remote user"); cursor.SendMessage("ShowPrivateChatCursor", false); Debug.Log(privateMessageRecipient.ToString()); showChatWindow = true; EnsureChatQueue(privateMessageRecipient); chatModeEnabled = true; activeChat = privateMessageRecipient; } } } else { cursor.SendMessage("ShowPrivateChatCursor", false); } } } } } private void InitiatePrivateChatById(int userId, string username) { privateMessageRecipient = userId; EnsureChatQueue(userId); activeChat = userId; showChatWindow = true; } private void ChatLostFocus() { ChatMode(false); typingTime = 0; } private void ChatButtonToggled() { if (activeChat == 0) { if (!hideInstantlyIfNoMessagesReceived) { messageReceivedTime = 0.0f; showMessagesReceivedWhileChatMinimized = true; } showChatWindow = !showChatWindow; if(!showChatWindow) { GUIUtility.keyboardControl = 0; } ChatMode(showChatWindow); } else if (showChatWindow) { activeChat = 0; } scrollPosition.y = 10000000000; // To scroll down the messages window } private void ChatMode(bool setEnabled) { chatModeEnabled = setEnabled; // if enabled, disable camera panning and movement if (character == null) character = GameObject.FindGameObjectWithTag("Player"); if (playerCam == null) playerCam = GameObject.FindGameObjectWithTag("MainCamera"); if (GameObject.Find("localPlayer").transform.GetChild(0).GetComponent<PlayerMovement>() != null) { GameObject.Find("localPlayer").transform.GetChild(0).GetComponent<PlayerMovement>().enabled = !chatModeEnabled; GameObject.Find("localPlayer").transform.GetChild(0).GetComponent<PlayerMovement>().SetChatting(chatModeEnabled); playerCam.SendMessage("SetChatting", chatModeEnabled, SendMessageOptions.DontRequireReceiver); } else { // could be non-Jibe avatar - try using local player instead if (localPlayer == null) localPlayer = GameObject.FindGameObjectWithTag("Player"); if (localPlayer.GetComponent<PlayerMovement>() != null) { localPlayer.GetComponent<PlayerMovement>().enabled = !chatModeEnabled; localPlayer.GetComponent<PlayerMovement>().SetChatting(chatModeEnabled); playerCam.SendMessage("SetChatting", chatModeEnabled, SendMessageOptions.DontRequireReceiver); } } if (playerCam != null && playerCam.GetComponent<Camera>().enabled) playerCam.SendMessage("SetCameraEnabled", !chatModeEnabled, SendMessageOptions.DontRequireReceiver); } private void SetTransparency(float currentTransparency) { guiColor.a = currentTransparency; guiTextColor.a = currentTransparency; GUI.color = guiColor; GUI.contentColor = guiTextColor; } private void ResizeChatbox() { sizeX = Input.mousePosition.x; sizeY = (Input.mousePosition.y * -1) + Screen.height; if (chatWindow.xMax - sizeX > 150) // allow a resize, but there's a minimum of 150px wide { chatWindow.xMin = sizeX; // resize the hidden view window at the same time messagesWindow.xMin = sizeX; } if (chatWindow.yMax - sizeY > 100) // allow a resize, but there's a minimum of 100px tall { chatWindow.yMin = sizeY; messagesWindow.yMin = sizeY; } scrollPosition.y = 10000000000; // To scroll down the messages window } private Rect GetResizeButton() { return new Rect(chatWindow.x - 10, chatWindow.y - 46, 20, 40); } private bool MouseDrag() { return (Event.current.type == EventType.MouseDrag); } private bool ResizeMouseDrag() { if (Event.current.type == EventType.MouseDrag) { return (Input.mousePosition.x >= chatWindow.xMin - 60 && Input.mousePosition.x < chatWindow.xMin + 60 && Input.mousePosition.y >= Screen.height - chatWindow.yMin - 60 && Input.mousePosition.y < Screen.height - chatWindow.yMin + 60); } else { return false; } } private bool EnterPressed() { return (Event.current.type == EventType.keyDown && Event.current.character == '\n'); } void ShowChatWindow(int id) { // This section controls the appearance of the chat window when enabled for live chatting GUI.SetNextControlName("scroll"); scrollPosition = GUILayout.BeginScrollView(scrollPosition); List<ChatMessage> activeMessages; if(messages.ContainsKey(activeChat)) { activeMessages = messages[activeChat]; } else { activeMessages = new List<ChatMessage>(); } for (int i = Math.Max(0, activeMessages.Count - maxMessageHistoryDisplay); i < activeMessages.Count; i++) { ChatMessage message = activeMessages[i]; GUILayout.BeginHorizontal(); if (message.IsHyperLink) { if (GUILayout.Button(message.Message, "HyperLink")) { // Web players - if you do an OpenURL the whole page navigates elsewhere... not ideal! // Instead, do a JavaScript call to a function called LoadExternal on the containing page // and do whatever is needed there to display the linked content. if (Application.platform == RuntimePlatform.WindowsWebPlayer || Application.platform == RuntimePlatform.OSXWebPlayer) { Application.ExternalCall("LoadExternal", message.Message); } else { Application.OpenURL(message.Message); } } } else { if (showTimeStamp) { GUILayout.Label(message.MessageTime + " ", "ChatMessagesPrefix"); GUILayout.Label(message.Sender + ": ", "ChatMessagesPrefix"); GUILayout.Label(message.Message, "ChatMessages"); } else { GUILayout.Label(message.Sender + ": ", "ChatMessagesPrefix"); GUILayout.Label(message.Message, "ChatMessages"); } } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.Space(3); } GUILayout.EndScrollView(); GUI.DragWindow(/*new Rect(0, -50, 10000, 50)*/); } private void AddMyChatMessage(string message) { string userName = networkController.GetMyName(); AddChatMessage(message, userName); if (message != typingIndicator && logChatToWeb) { StartCoroutine(AddChatMessageToWebStore(message)); SendChatMessage(message); } } private IEnumerator AddChatMessageToWebStore(string message) { if (!string.IsNullOrEmpty(chatStoreUrl)) { IJibePlayer localPlayer = networkController.GetLocalPlayer(); string playerId = localPlayer.PlayerID.ToString(); if (PlayerPrefs.GetString("useruuid") != null) playerId = PlayerPrefs.GetString("useruuid"); WWWForm chatMessageForm = new WWWForm(); chatMessageForm.AddField("UserId", playerId); chatMessageForm.AddField("UserName", localPlayer.Name); chatMessageForm.AddField("Message", message); chatMessageForm.AddField("RoomId", Application.loadedLevelName); chatMessageForm.AddField("JibeInstance", Application.dataPath); chatMessageForm.AddField("LocX", localPlayer.PosX.ToString()); chatMessageForm.AddField("LocY", localPlayer.PosY.ToString()); chatMessageForm.AddField("LocZ", localPlayer.PosZ.ToString()); webChatStoreRequest = new WWW(chatStoreUrl, chatMessageForm); yield return (webChatStoreRequest); if (!string.IsNullOrEmpty(webChatStoreRequest.error)) { Debug.Log(webChatStoreRequest.error); } } } private void AddMyPrivateChatMessage(string message) { EnsureChatQueue(privateMessageRecipient); string userName = networkController.GetMyName(); AddPrivateChatMessage(message, userName, privateMessageRecipient); SendPrivateChatMessage(message); } private void EnsureChatQueue(int chatQueue) { // Prevent nasty errors - always make sure there's an element in the messages collection for the specified chat session if (!messages.ContainsKey(chatQueue)) { messages[chatQueue] = new List<ChatMessage>(); messageBackgrounds[chatQueue] = 1; } } private void SendPrivateChatMessage(string message) { networkController.SendPrivateChatMessage(message, privateMessageRecipient); privateMessage = ""; } // This method to be called when remote chat message is received public void AddChatMessage(string message, string sender) { AddMessage(message, sender, 0, networkController.onlyChatWithGroup[networkController.localPlayer.PlayerID]); } public void StoreChatMessage(string message, string sender, string groupName) //remember what other groups are chatting about in case we switch to their chat { Debug.Log("Storing chat message"); ChatMessage newMessage = new ChatMessage(); newMessage.Message = message; newMessage.Sender = sender; newMessage.IsHyperLink = false; if(groupMessages.ContainsKey(groupName)) { groupMessages[groupName][0].Add(newMessage); } else { groupMessages[groupName] = new Dictionary<int, List<ChatMessage>>(); groupMessages[groupName][0] = new List<ChatMessage>(); groupMessages[groupName][0].Add(newMessage); } if(!sender.Equals(networkController.localPlayer.Name)) { notificationShow[groupName]=true; } if(permissionToStoreMessagesToDatabase) { Application.ExternalCall("StoreChatMessageInDatabase", message, sender, groupName); } } public void SwitchGroup(string groupName) { if(groupMessages.ContainsKey(groupName)) { // messages=groupMessages[groupName]; Dictionary<int, List<ChatMessage>> filler = new Dictionary<int, List<ChatMessage>>(); foreach(int i in groupMessages[groupName].Keys) { filler[i] = new List<ChatMessage>(); foreach(ChatMessage ii in groupMessages[groupName][i]) { filler[i].Add(ii); } } messages = filler; } else { groupMessages[groupName] = new Dictionary<int, List<ChatMessage>>(); groupMessages[groupName][0]=new List<ChatMessage>(); //the default chat list messages=new Dictionary<int, List<ChatMessage>>(); } currentGroup=groupName; } // This method to be called when private chat message is received public void AddPrivateChatMessage(string message, string sender, int senderId) { EnsureChatQueue(senderId); if (!unreadMessages.Contains(senderId)) { unreadMessages.Add(senderId); AlertUnreadMessages(); } AddMessage(message, sender, senderId, networkController.onlyChatWithGroup[networkController.localPlayer.PlayerID]); } private void MarkMessagesAsRead() { if (unreadMessages.Contains(activeChat)) { unreadMessages.Remove(activeChat); AlertUnreadMessages(); } } public void RemoteUserLeaves(int playerID, string playerName) { if (unreadMessages.Contains(playerID)) { unreadMessages.Remove(playerID); AlertUnreadMessages(); } //AddChatMessage("leaves", playerName); } private void AlertUnreadMessages() { if (currentUnreadCount != unreadMessages.Count) { currentUnreadCount = unreadMessages.Count; Application.ExternalCall("ChatAlert", currentUnreadCount); } } public void AddDebugMessage(string message) { /* ChatMessage newMessage = new ChatMessage(); newMessage.Message = message; newMessage.Sender = "Debug"; newMessage.IsHyperLink = false; if(messages.ContainsKey(0)) { messages[0].Add(newMessage); } else { messages[0] = new List<ChatMessage>(); messages[0].Add(newMessage); } Debug.Log("Adding a debug message to the chat log");*/ } private void AddMessage(string message, string sender, int senderId) //this is the old version from vanilla jibe - shouldn't be called anymore { if (!message.EndsWith(typingIndicator)) { // Do a basic test if (message.Contains("http")) { // Try a more complex Regular Expression to match an internet address Regex reg = new Regex(@"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"); MatchCollection matches = reg.Matches(message); if (matches.Count > 0) { // found some hyperlinks foreach (Match match in matches) { if (match != null && match.Value.Length > 0) { // Add a hyperlink chatmessage with just the matching link ChatMessage hyperlinkMessage = new ChatMessage(); hyperlinkMessage.Message = match.Value; hyperlinkMessage.Sender = sender; hyperlinkMessage.IsHyperLink = true; messages[senderId].Add(hyperlinkMessage); } } } } // Add the whole chat message (even if the message contains a hyperlink, it may also contain other text, so show all of it here) ChatMessage newMessage = new ChatMessage(); newMessage.Message = message; newMessage.Sender = sender; newMessage.IsHyperLink = false; if (continualChatHistoryExport) { AddToChatHistory(newMessage); } if(messages.ContainsKey(senderId)) { Debug.Log("Storing chat message"); messages[senderId].Add(newMessage); } else { messages[senderId] = new List<ChatMessage>(); messages[senderId].Add(newMessage); } // groupMessages["GlobalChat"][senderId].Add(newMessage); scrollPosition.y = 10000000000; // To scroll down the messages window GameObject guiObject = GameObject.Find("UIBase"); if (guiObject != null) { float playVolume = messageSoundVolume * guiObject.GetComponent<UIBase>().volume / guiObject.GetComponent<UIBase>().audioIcons.Length; AudioSource.PlayClipAtPoint(messageSound, transform.position, playVolume); } if (senderId == 0) { showMessagesReceivedWhileChatMinimized = true; messageReceivedTime = 0.0f; } } } public void AddMessage(string message, string sender, int senderId, string groupName) { if (!message.EndsWith(typingIndicator)) { // Do a basic test if (message.Contains("http")) { // Try a more complex Regular Expression to match an internet address Regex reg = new Regex(@"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"); MatchCollection matches = reg.Matches(message); if (matches.Count > 0) { // found some hyperlinks foreach (Match match in matches) { if (match != null && match.Value.Length > 0) { // Add a hyperlink chatmessage with just the matching link ChatMessage hyperlinkMessage = new ChatMessage(); hyperlinkMessage.Message = match.Value; hyperlinkMessage.Sender = sender; hyperlinkMessage.IsHyperLink = true; messages[senderId].Add(hyperlinkMessage); } } } } // Add the whole chat message (even if the message contains a hyperlink, it may also contain other text, so show all of it here) ChatMessage newMessage = new ChatMessage(); newMessage.Message = message; newMessage.Sender = sender; newMessage.IsHyperLink = false; if (continualChatHistoryExport) { AddToChatHistory(newMessage); } if(messages.ContainsKey(senderId)) { messages[senderId].Add(newMessage); } else { messages[senderId] = new List<ChatMessage>(); messages[senderId].Add(newMessage); } StoreChatMessage(message, sender, groupName); scrollPosition.y = 10000000000; // To scroll down the messages window /*GameObject guiObject = GameObject.Find("UIBase"); //spawn popup when new chat message is received if (guiObject != null) { float playVolume = messageSoundVolume * guiObject.GetComponent<UIBase>().volume / guiObject.GetComponent<UIBase>().audioIcons.Length; AudioSource.PlayClipAtPoint(messageSound, transform.position, playVolume); } if (senderId == 0) { showMessagesReceivedWhileChatMinimized = true; messageReceivedTime = 0.0f; }*/ } } // Send the chat message to all other users private void SendChatMessage(String message) { networkController.SendChatMessage(message); } public bool IsChatting() { return chatModeEnabled; } } /// <summary> /// Data structure for a chat message /// </summary> public class ChatMessage { /// <summary> /// Default constructor - whenever a new ChatMessage object is created, initialise the timestamp to current datetime /// </summary> public ChatMessage() { _timestamp = DateTime.Now; } private string _message = ""; /// <summary> /// The chat message body /// </summary> public string Message { get { return _message; } set { _message = value; } } private bool _isHyperLink = false; /// <summary> /// Boolean value - if the message is a hyperlink we can optionally treat it differently /// </summary> public bool IsHyperLink { get { return _isHyperLink; } set { _isHyperLink = value; } } private DateTime _timestamp; /// <summary> /// When the message was received (full timestamp) /// </summary> public DateTime MessageTimeStamp { get { return _timestamp; } } /// <summary> /// Formatted time when message was received (easier to display in chat history) /// </summary> public string MessageTime { get { return _timestamp.ToString("h:mm"); } } private string _sender; /// <summary> /// The name of the sender of the message /// </summary> public string Sender { get { return _sender; } set { _sender = value; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.IO; using System.Reflection; using System.ComponentModel; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Management.Automation; using System.Management.Automation.Provider; using System.Xml; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using Microsoft.Win32; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Security; using System.Threading; using Dbg = System.Management.Automation; namespace Microsoft.WSMan.Management { #region WSManCredSSP cmdlet base /// <summary> /// Base class used *-WSManCredSSP cmdlets (Enable-WSManCredSSP, Disable-WSManCredSSP) /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSP")] public class WSManCredSSPCommandBase : PSCmdlet { #region Protected / Internal Data internal const string Server = "Server"; internal const string Client = "Client"; #endregion #region Parameters /// <summary> /// Role can either "Client" or "Server". /// </summary> [Parameter(Mandatory = true, Position = 0)] [ValidateSet(Client, Server)] public string Role { get { return role; } set { role = value; } } private string role; #endregion #region Utilities /// <summary> /// </summary> /// <returns> /// Returns a session object upon successful creation..otherwise /// writes an error using WriteError and returns null. /// </returns> internal IWSManSession CreateWSManSession() { IWSManEx wsmanObject = (IWSManEx)new WSManClass(); IWSManSession m_SessionObj = null; try { m_SessionObj = (IWSManSession)wsmanObject.CreateSession(null, 0, null); return m_SessionObj; } catch (COMException ex) { ErrorRecord er = new ErrorRecord(ex, "COMException", ErrorCategory.InvalidOperation, null); WriteError(er); } return null; } #endregion } #endregion #region DisableWsManCredSsp /// <summary> /// Disables CredSSP authentication on the client. CredSSP authentication /// enables an application to delegate the user's credentials from the client to /// the server, hence allowing the user to perform management operations that /// access a second hop. /// </summary> [Cmdlet(VerbsLifecycle.Disable, "WSManCredSSP", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=141438")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSP")] public class DisableWSManCredSSPCommand : WSManCredSSPCommandBase, IDisposable { #region private // The application name MUST be "wsman" as wsman got approval from security // folks who suggested to register the SPN with name "wsman". private const string applicationname = "wsman"; private void DisableClientSideSettings() { WSManHelper helper = new WSManHelper(this); IWSManSession m_SessionObj = CreateWSManSession(); if (m_SessionObj == null) { return; } try { string result = m_SessionObj.Get(helper.CredSSP_RUri, 0); XmlDocument resultopxml = new XmlDocument(); string inputXml = null; resultopxml.LoadXml(result); XmlNamespaceManager nsmgr = new XmlNamespaceManager(resultopxml.NameTable); nsmgr.AddNamespace("cfg", helper.CredSSP_XMLNmsp); XmlNode xNode = resultopxml.SelectSingleNode(helper.CredSSP_SNode, nsmgr); if (!(xNode == null)) { inputXml = @"<cfg:Auth xmlns:cfg=""http://schemas.microsoft.com/wbem/wsman/1/config/client/auth""><cfg:CredSSP>false</cfg:CredSSP></cfg:Auth>"; } else { InvalidOperationException ex = new InvalidOperationException(); ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); WriteError(er); return; } m_SessionObj.Put(helper.CredSSP_RUri, inputXml, 0); if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) { this.DeleteUserDelegateSettings(); } else { ThreadStart start = new ThreadStart(this.DeleteUserDelegateSettings); Thread thread = new Thread(start); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); } if (!helper.ValidateCreadSSPRegistryRetry(false, null, applicationname)) { helper.AssertError(helper.GetResourceMsgFromResourcetext("DisableCredSSPPolicyValidateError"), false, null); } } catch (System.Xml.XPath.XPathException ex) { ErrorRecord er = new ErrorRecord(ex, "XpathException", ErrorCategory.InvalidOperation, null); WriteError(er); } finally { if (!string.IsNullOrEmpty(m_SessionObj.Error)) { helper.AssertError(m_SessionObj.Error, true, null); } if (m_SessionObj != null) Dispose(m_SessionObj); } } private void DisableServerSideSettings() { WSManHelper helper = new WSManHelper(this); IWSManSession m_SessionObj = CreateWSManSession(); if (m_SessionObj == null) { return; } try { string result = m_SessionObj.Get(helper.Service_CredSSP_Uri, 0); XmlDocument resultopxml = new XmlDocument(); string inputXml = null; resultopxml.LoadXml(result); XmlNamespaceManager nsmgr = new XmlNamespaceManager(resultopxml.NameTable); nsmgr.AddNamespace("cfg", helper.Service_CredSSP_XMLNmsp); XmlNode xNode = resultopxml.SelectSingleNode(helper.CredSSP_SNode, nsmgr); if (!(xNode == null)) { inputXml = string.Format(CultureInfo.InvariantCulture, @"<cfg:Auth xmlns:cfg=""{0}""><cfg:CredSSP>false</cfg:CredSSP></cfg:Auth>", helper.Service_CredSSP_XMLNmsp); } else { InvalidOperationException ex = new InvalidOperationException(); ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); WriteError(er); return; } m_SessionObj.Put(helper.Service_CredSSP_Uri, inputXml, 0); } finally { if (!string.IsNullOrEmpty(m_SessionObj.Error)) { helper.AssertError(m_SessionObj.Error, true, null); } if (m_SessionObj != null) { Dispose(m_SessionObj); } } } private void DeleteUserDelegateSettings() { System.IntPtr KeyHandle = System.IntPtr.Zero; IGroupPolicyObject GPO = (IGroupPolicyObject)new GPClass(); GPO.OpenLocalMachineGPO(1); KeyHandle = GPO.GetRegistryKey(2); RegistryKey rootKey = Registry.CurrentUser; string GPOpath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy Objects"; RegistryKey GPOKey = rootKey.OpenSubKey(GPOpath, true); foreach (string keyname in GPOKey.GetSubKeyNames()) { if (keyname.EndsWith("Machine", StringComparison.OrdinalIgnoreCase)) { string key = GPOpath + "\\" + keyname + "\\" + @"Software\Policies\Microsoft\Windows"; DeleteDelegateSettings(applicationname, Registry.CurrentUser, key, GPO); } } KeyHandle = System.IntPtr.Zero; } private void DeleteDelegateSettings(string applicationname, RegistryKey rootKey, string Registry_Path, IGroupPolicyObject GPO) { WSManHelper helper = new WSManHelper(this); RegistryKey rKey; int i = 0; bool otherkeys = false; try { string Registry_Path_Credentials_Delegation = Registry_Path + @"\CredentialsDelegation"; RegistryKey Allow_Fresh_Credential_Key = rootKey.OpenSubKey(Registry_Path_Credentials_Delegation + @"\" + helper.Key_Allow_Fresh_Credentials, true); if (Allow_Fresh_Credential_Key != null) { string[] valuenames = Allow_Fresh_Credential_Key.GetValueNames(); if (valuenames.Length > 0) { Collection<string> KeyCollection = new Collection<string>(); foreach (string value in valuenames) { object keyvalue = Allow_Fresh_Credential_Key.GetValue(value); if (keyvalue != null) { if (!keyvalue.ToString().StartsWith(applicationname, StringComparison.OrdinalIgnoreCase)) { KeyCollection.Add(keyvalue.ToString()); otherkeys = true; } } Allow_Fresh_Credential_Key.DeleteValue(value); } foreach (string keyvalue in KeyCollection) { Allow_Fresh_Credential_Key.SetValue(Convert.ToString(i + 1, CultureInfo.InvariantCulture), keyvalue, RegistryValueKind.String); i++; } } } if (!otherkeys) { rKey = rootKey.OpenSubKey(Registry_Path_Credentials_Delegation, true); if (rKey != null) { object regval1 = rKey.GetValue(helper.Key_Allow_Fresh_Credentials); if (regval1 != null) { rKey.DeleteValue(helper.Key_Allow_Fresh_Credentials, false); } object regval2 = rKey.GetValue(helper.Key_Concatenate_Defaults_AllowFresh); if (regval2 != null) { rKey.DeleteValue(helper.Key_Concatenate_Defaults_AllowFresh, false); } if (rKey.OpenSubKey(helper.Key_Allow_Fresh_Credentials) != null) { rKey.DeleteSubKeyTree(helper.Key_Allow_Fresh_Credentials); } } } GPO.Save(true, true, new Guid("35378EAC-683F-11D2-A89A-00C04FBBCFA2"), new Guid("6AD20875-336C-4e22-968F-C709ACB15814")); } catch (InvalidOperationException ex) { ErrorRecord er = new ErrorRecord(ex, "InvalidOperation", ErrorCategory.InvalidOperation, null); WriteError(er); } catch (ArgumentException ex) { ErrorRecord er = new ErrorRecord(ex, "InvalidArgument", ErrorCategory.InvalidArgument, null); WriteError(er); } catch (SecurityException ex) { ErrorRecord er = new ErrorRecord(ex, "SecurityException", ErrorCategory.SecurityError, null); WriteError(er); } catch (UnauthorizedAccessException ex) { ErrorRecord er = new ErrorRecord(ex, "UnauthorizedAccess", ErrorCategory.SecurityError, null); WriteError(er); } } #endregion private /// <summary> /// Begin processing method. /// </summary> protected override void BeginProcessing() { // If not running elevated, then throw an "elevation required" error message. WSManHelper.ThrowIfNotAdministrator(); if (Role.Equals(Client, StringComparison.OrdinalIgnoreCase)) { DisableClientSideSettings(); } if (Role.Equals(Server, StringComparison.OrdinalIgnoreCase)) { DisableServerSideSettings(); } } #region IDisposable Members /// <summary> /// Public dispose method. /// </summary> public void Dispose() { // CleanUp(); GC.SuppressFinalize(this); } /// <summary> /// Public dispose method. /// </summary> public void Dispose(IWSManSession sessionObject) { sessionObject = null; this.Dispose(); } #endregion IDisposable Members } #endregion DisableWsManCredSSP #region EnableCredSSP /// <summary> /// Enables CredSSP authentication on the client. CredSSP authentication enables /// an application to delegate the user's credentials from the client to the /// server, hence allowing the user to perform management operations that access /// a second hop. /// This cmdlet performs the following: /// /// On the client: /// 1. Enables WSMan local configuration on client to enable CredSSP /// 2. Sets CredSSP policy AllowFreshCredentials to wsman/Delegate. This policy /// allows delegating explicit credentials to a server when server /// authentication is achieved via a trusted X509 certificate or Kerberos. /// </summary> [Cmdlet(VerbsLifecycle.Enable, "WSManCredSSP", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=141442")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSP")] public class EnableWSManCredSSPCommand : WSManCredSSPCommandBase, IDisposable/*, IDynamicParameters*/ { /// <summary> /// Delegate parameter. /// </summary> [Parameter(Position = 1)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] DelegateComputer { get { return delegatecomputer; } set { delegatecomputer = value; } } private string[] delegatecomputer; /// <summary> /// Property that sets force parameter. /// </summary> [Parameter()] public SwitchParameter Force { get { return force; } set { force = value; } } private bool force = false; // helper variable private WSManHelper helper; // The application name MUST be "wsman" as wsman got approval from security // folks who suggested to register the SPN with name "wsman". private const string applicationname = "wsman"; #region Cmdlet Overloads /// <summary> /// BeginProcessing method. /// </summary> protected override void BeginProcessing() { // If not running elevated, then throw an "elevation required" error message. WSManHelper.ThrowIfNotAdministrator(); helper = new WSManHelper(this); // DelegateComputer cannot be specified when Role is other than client if ((delegatecomputer != null) && !Role.Equals(Client, StringComparison.OrdinalIgnoreCase)) { string message = helper.FormatResourceMsgFromResourcetext("CredSSPRoleAndDelegateCannotBeSpecified", "DelegateComputer", "Role", Role, Client); throw new InvalidOperationException(message); } // DelegateComputer must be specified when Role is client if (Role.Equals(Client, StringComparison.OrdinalIgnoreCase) && (delegatecomputer == null)) { string message = helper.FormatResourceMsgFromResourcetext("CredSSPClientAndDelegateMustBeSpecified", "DelegateComputer", "Role", Client); throw new InvalidOperationException(message); } if (Role.Equals(Client, StringComparison.OrdinalIgnoreCase)) { EnableClientSideSettings(); } if (Role.Equals(Server, StringComparison.OrdinalIgnoreCase)) { EnableServerSideSettings(); } } #endregion /// <summary> /// </summary> /// <exception cref="InvalidOperationException"> /// </exception> private void EnableClientSideSettings() { string query = helper.GetResourceMsgFromResourcetext("CredSSPContinueQuery"); string caption = helper.GetResourceMsgFromResourcetext("CredSSPContinueCaption"); if (!force && !ShouldContinue(query, caption)) { return; } IWSManSession m_SessionObj = CreateWSManSession(); if (m_SessionObj == null) { return; } try { // get the credssp node to check if wsman is configured on this machine string result = m_SessionObj.Get(helper.CredSSP_RUri, 0); XmlNode node = helper.GetXmlNode(result, helper.CredSSP_SNode, helper.CredSSP_XMLNmsp); if (node == null) { InvalidOperationException ex = new InvalidOperationException(); ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); WriteError(er); return; } string newxmlcontent = @"<cfg:Auth xmlns:cfg=""http://schemas.microsoft.com/wbem/wsman/1/config/client/auth""><cfg:CredSSP>true</cfg:CredSSP></cfg:Auth>"; try { XmlDocument xmldoc = new XmlDocument(); // push the xml string with credssp enabled xmldoc.LoadXml(m_SessionObj.Put(helper.CredSSP_RUri, newxmlcontent, 0)); // set the Registry using GroupPolicyObject if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) { this.UpdateCurrentUserRegistrySettings(); } else { ThreadStart start = new ThreadStart(this.UpdateCurrentUserRegistrySettings); Thread thread = new Thread(start); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); } if (helper.ValidateCreadSSPRegistryRetry(true, delegatecomputer, applicationname)) { WriteObject(xmldoc.FirstChild); } else { helper.AssertError(helper.GetResourceMsgFromResourcetext("EnableCredSSPPolicyValidateError"), false, delegatecomputer); } } catch (COMException) { helper.AssertError(m_SessionObj.Error, true, delegatecomputer); } } finally { if (!string.IsNullOrEmpty(m_SessionObj.Error)) { helper.AssertError(m_SessionObj.Error, true, delegatecomputer); } if (m_SessionObj != null) { Dispose(m_SessionObj); } } } private void EnableServerSideSettings() { string query = helper.GetResourceMsgFromResourcetext("CredSSPServerContinueQuery"); string caption = helper.GetResourceMsgFromResourcetext("CredSSPContinueCaption"); if (!force && !ShouldContinue(query, caption)) { return; } IWSManSession m_SessionObj = CreateWSManSession(); if (m_SessionObj == null) { return; } try { // get the credssp node to check if wsman is configured on this machine string result = m_SessionObj.Get(helper.Service_CredSSP_Uri, 0); XmlNode node = helper.GetXmlNode(result, helper.CredSSP_SNode, helper.Service_CredSSP_XMLNmsp); if (node == null) { InvalidOperationException ex = new InvalidOperationException(); ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); WriteError(er); return; } try { XmlDocument xmldoc = new XmlDocument(); string newxmlcontent = string.Format(CultureInfo.InvariantCulture, @"<cfg:Auth xmlns:cfg=""{0}""><cfg:CredSSP>true</cfg:CredSSP></cfg:Auth>", helper.Service_CredSSP_XMLNmsp); // push the xml string with credssp enabled xmldoc.LoadXml(m_SessionObj.Put(helper.Service_CredSSP_Uri, newxmlcontent, 0)); WriteObject(xmldoc.FirstChild); } catch (COMException) { helper.AssertError(m_SessionObj.Error, true, delegatecomputer); } } finally { if (!string.IsNullOrEmpty(m_SessionObj.Error)) { helper.AssertError(m_SessionObj.Error, true, delegatecomputer); } if (m_SessionObj != null) { Dispose(m_SessionObj); } } } /// <summary> /// </summary> private void UpdateCurrentUserRegistrySettings() { System.IntPtr KeyHandle = System.IntPtr.Zero; IGroupPolicyObject GPO = (IGroupPolicyObject)new GPClass(); GPO.OpenLocalMachineGPO(1); KeyHandle = GPO.GetRegistryKey(2); RegistryKey rootKey = Registry.CurrentUser; string GPOpath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy Objects"; RegistryKey GPOKey = rootKey.OpenSubKey(GPOpath, true); foreach (string keyname in GPOKey.GetSubKeyNames()) { if (keyname.EndsWith("Machine", StringComparison.OrdinalIgnoreCase)) { string key = GPOpath + "\\" + keyname + "\\" + @"Software\Policies\Microsoft\Windows"; UpdateGPORegistrySettings(applicationname, this.delegatecomputer, Registry.CurrentUser, key); } } // saving gpo settings GPO.Save(true, true, new Guid("35378EAC-683F-11D2-A89A-00C04FBBCFA2"), new Guid("7A9206BD-33AF-47af-B832-D4128730E990")); } /// <summary> /// Updates the grouppolicy registry settings. /// </summary> /// <param name="applicationname"></param> /// <param name="delegatestring"></param> /// <param name="rootKey"></param> /// <param name="Registry_Path"></param> private void UpdateGPORegistrySettings(string applicationname, string[] delegatestring, RegistryKey rootKey, string Registry_Path) { // RegistryKey rootKey = Registry.LocalMachine; RegistryKey Credential_Delegation_Key; RegistryKey Allow_Fresh_Credential_Key; int i = 0; try { string Registry_Path_Credentials_Delegation = Registry_Path + @"\CredentialsDelegation"; // open the registry key.If key is not present,create a new one Credential_Delegation_Key = rootKey.OpenSubKey(Registry_Path_Credentials_Delegation, true); if (Credential_Delegation_Key == null) Credential_Delegation_Key = rootKey.CreateSubKey(Registry_Path_Credentials_Delegation, RegistryKeyPermissionCheck.ReadWriteSubTree); Credential_Delegation_Key.SetValue(helper.Key_Allow_Fresh_Credentials, 1, RegistryValueKind.DWord); Credential_Delegation_Key.SetValue(helper.Key_Concatenate_Defaults_AllowFresh, 1, RegistryValueKind.DWord); // add the delegate value Allow_Fresh_Credential_Key = rootKey.OpenSubKey(Registry_Path_Credentials_Delegation + @"\" + helper.Key_Allow_Fresh_Credentials, true); if (Allow_Fresh_Credential_Key == null) Allow_Fresh_Credential_Key = rootKey.CreateSubKey(Registry_Path_Credentials_Delegation + @"\" + helper.Key_Allow_Fresh_Credentials, RegistryKeyPermissionCheck.ReadWriteSubTree); if (Allow_Fresh_Credential_Key != null) { i = Allow_Fresh_Credential_Key.ValueCount; foreach (string del in delegatestring) { Allow_Fresh_Credential_Key.SetValue(Convert.ToString(i + 1, CultureInfo.InvariantCulture), applicationname + @"/" + del, RegistryValueKind.String); i++; } } } catch (UnauthorizedAccessException ex) { ErrorRecord er = new ErrorRecord(ex, "UnauthorizedAccessException", ErrorCategory.PermissionDenied, null); WriteError(er); } catch (SecurityException ex) { ErrorRecord er = new ErrorRecord(ex, "SecurityException", ErrorCategory.InvalidOperation, null); WriteError(er); } catch (ArgumentException ex) { ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidOperation, null); WriteError(er); } } #region IDisposable Members /// <summary> /// Public dispose method. /// </summary> public void Dispose() { GC.SuppressFinalize(this); } /// <summary> /// Public dispose method. /// </summary> public void Dispose(IWSManSession sessionObject) { sessionObject = null; this.Dispose(); } #endregion IDisposable Members } #endregion EnableCredSSP #region Get-CredSSP /// <summary> /// Gets the CredSSP related configuration on the client. CredSSP authentication /// enables an application to delegate the user's credentials from the client to /// the server, hence allowing the user to perform management operations that /// access a second hop. /// This cmdlet performs the following: /// 1. Gets the configuration for WSMan policy on client to enable/disable /// CredSSP /// 2. Gets the configuration information for the CredSSP policy /// AllowFreshCredentials . This policy allows delegating explicit credentials /// to a server when server authentication is achieved via a trusted X509 /// certificate or Kerberos. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSP")] [Cmdlet(VerbsCommon.Get, "WSManCredSSP", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=141443")] public class GetWSManCredSSPCommand : PSCmdlet, IDisposable { #region private WSManHelper helper = null; /// <summary> /// Method to get the values. /// </summary> private string GetDelegateSettings(string applicationname) { RegistryKey rootKey = Registry.LocalMachine; RegistryKey rKey; string result = string.Empty; string[] valuenames = null; try { string Reg_key = helper.Registry_Path_Credentials_Delegation + @"\CredentialsDelegation"; rKey = rootKey.OpenSubKey(Reg_key); if (rKey != null) { rKey = rKey.OpenSubKey(helper.Key_Allow_Fresh_Credentials); if (rKey != null) { valuenames = rKey.GetValueNames(); if (valuenames.Length > 0) { string listvalue = CultureInfo.CurrentCulture.TextInfo.ListSeparator; foreach (string value in valuenames) { object keyvalue = rKey.GetValue(value); if (keyvalue != null) { if (keyvalue.ToString().StartsWith(applicationname, StringComparison.OrdinalIgnoreCase)) { result = keyvalue.ToString() + listvalue + result; } } } if (result.EndsWith(listvalue, StringComparison.OrdinalIgnoreCase)) { result = result.Remove(result.Length - 1); } } } } } catch (ArgumentException ex) { ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.PermissionDenied, null); WriteError(er); } catch (SecurityException ex) { ErrorRecord er = new ErrorRecord(ex, "SecurityException", ErrorCategory.PermissionDenied, null); WriteError(er); } catch (ObjectDisposedException ex) { ErrorRecord er = new ErrorRecord(ex, "ObjectDisposedException", ErrorCategory.PermissionDenied, null); WriteError(er); } return result; } #endregion private #region overrides /// <summary> /// Method to begin processing. /// </summary> protected override void BeginProcessing() { // If not running elevated, then throw an "elevation required" error message. WSManHelper.ThrowIfNotAdministrator(); helper = new WSManHelper(this); IWSManSession m_SessionObj = null; try { IWSManEx wsmanObject = (IWSManEx)new WSManClass(); m_SessionObj = (IWSManSession)wsmanObject.CreateSession(null, 0, null); string result = m_SessionObj.Get(helper.CredSSP_RUri, 0); XmlNode node = helper.GetXmlNode(result, helper.CredSSP_SNode, helper.CredSSP_XMLNmsp); if (node == null) { InvalidOperationException ex = new InvalidOperationException(); ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); WriteError(er); return; } // The application name MUST be "wsman" as wsman got approval from security // folks who suggested to register the SPN with name "wsman". string applicationname = "wsman"; string credsspResult = GetDelegateSettings(applicationname); if (string.IsNullOrEmpty(credsspResult)) { WriteObject(helper.GetResourceMsgFromResourcetext("NoDelegateFreshCred")); } else { WriteObject(helper.GetResourceMsgFromResourcetext("DelegateFreshCred") + credsspResult); } // Get the server side settings result = m_SessionObj.Get(helper.Service_CredSSP_Uri, 0); node = helper.GetXmlNode(result, helper.CredSSP_SNode, helper.Service_CredSSP_XMLNmsp); if (node == null) { InvalidOperationException ex = new InvalidOperationException(); ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); WriteError(er); return; } if (node.InnerText.Equals("true", StringComparison.OrdinalIgnoreCase)) { WriteObject(helper.GetResourceMsgFromResourcetext("CredSSPServiceConfigured")); } else { WriteObject(helper.GetResourceMsgFromResourcetext("CredSSPServiceNotConfigured")); } } catch (UnauthorizedAccessException ex) { ErrorRecord er = new ErrorRecord(ex, "UnauthorizedAccess", ErrorCategory.PermissionDenied, null); WriteError(er); } catch (SecurityException ex) { ErrorRecord er = new ErrorRecord(ex, "SecurityException", ErrorCategory.InvalidOperation, null); WriteError(er); } catch (ArgumentException ex) { ErrorRecord er = new ErrorRecord(ex, "InvalidArgument", ErrorCategory.InvalidOperation, null); WriteError(er); } catch (System.Xml.XPath.XPathException ex) { ErrorRecord er = new ErrorRecord(ex, "XPathException", ErrorCategory.InvalidOperation, null); WriteError(er); } finally { if (!string.IsNullOrEmpty(m_SessionObj.Error)) { helper.AssertError(m_SessionObj.Error, true, null); } if (m_SessionObj != null) { Dispose(m_SessionObj); } } } #endregion overrides #region IDisposable Members /// <summary> /// Public dispose method. /// </summary> public void Dispose() { GC.SuppressFinalize(this); } /// <summary> /// Public dispose method. /// </summary> public void Dispose(IWSManSession sessionObject) { sessionObject = null; this.Dispose(); } #endregion IDisposable Members } #endregion }
using System; using System.Collections.Generic; using System.Linq.Expressions; using Newtonsoft.Json; using Xunit; namespace Simple.OData.Client.Tests.Core { public class TypedExpressionV3Tests : TypedExpressionTests { public override string MetadataFile => "Northwind3.xml"; public override IFormatSettings FormatSettings => new ODataV3Format(); } public class TypedExpressionV4Tests : TypedExpressionTests { public override string MetadataFile => "Northwind4.xml"; public override IFormatSettings FormatSettings => new ODataV4Format(); [Fact] public void FilterEntitiesWithContains() { var ids = new List<int> {1, 2, 3}; Expression<Func<TestEntity, bool>> filter = x => ids.Contains(x.ProductID); Assert.Equal("(ProductID in (1,2,3))", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void FilterEntitiesByStringPropertyWithContains() { var names = new List<string> {"Chai", "Milk", "Water"}; Expression<Func<TestEntity, bool>> filter = x => names.Contains(x.ProductName); Assert.Equal("(ProductName in ('Chai','Milk','Water'))", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void FilterEntitiesByNestedPropertyWithContains() { var categories = new List<string> {"Chai", "Milk", "Water"}; Expression<Func<TestEntity, bool>> filter = x => categories.Contains(x.Nested.ProductName); Assert.Equal("(Nested/ProductName in ('Chai','Milk','Water'))", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void FilterEntitiesByComplexConditionWithContains() { var categories = new List<string> {"chai", "milk", "water"}; Expression<Func<TestEntity, bool>> filter = x => categories.Contains(x.ProductName.ToLower()); Assert.Equal("(tolower(ProductName) in ('chai','milk','water'))", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void FilterEntitiesWithNotContains() { var ids = new List<int> {1, 2, 3}; Expression<Func<TestEntity, bool>> filter = x => !ids.Contains(x.ProductID); Assert.Equal("not (ProductID in (1,2,3))", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void FilterEntitiesWithContainsAndNotContains() { var ids = new List<int> {1, 2, 3}; var names = new List<string> {"Chai", "Milk", "Water"}; Expression<Func<TestEntity, bool>> filter = x => ids.Contains(x.ProductID) && !names.Contains(x.ProductName); Assert.Equal("(ProductID in (1,2,3)) and not (ProductName in ('Chai','Milk','Water'))", ODataExpression.FromLinqExpression(filter).AsString(_session)); } } public abstract class TypedExpressionTests : CoreTestBase { class DataAttribute : Attribute { public string Name { get; set; } public string PropertyName { get; set; } } class DataMemberAttribute : Attribute { public string Name { get; set; } public string PropertyName { get; set; } } class OtherAttribute : Attribute { public string Name { get; set; } public string PropertyName { get; set; } } internal class TestEntity { public int ProductID { get; set; } public string ProductName { get; set; } public Guid LinkID { get; set; } public decimal Price { get; set; } public Address Address { get; set; } public DateTime CreationTime { get; set; } public DateTimeOffset Updated { get; set; } public TimeSpan Period { get; set; } public TestEntity Nested { get; set; } public TestEntity[] Collection { get; set; } [Column(Name = "Name")] public string MappedNameUsingColumnAttribute { get; set; } [Data(Name = "Name", PropertyName = "OtherName")] public string MappedNameUsingDataAttribute { get; set; } [DataMember(Name = "Name", PropertyName = "OtherName")] public string MappedNameUsingDataMemberAttribute { get; set; } [Other(Name = "Name", PropertyName = "OtherName")] public string MappedNameUsingOtherAttribute { get; set; } [DataMember(Name = "Name", PropertyName = "OtherName")] [Other(Name = "OtherName", PropertyName = "OtherName")] public string MappedNameUsingDataMemberAndOtherAttribute { get; set; } [JsonProperty("Name")] public string MappedNameUsingJsonPropertyAttribute { get; set; } [System.Text.Json.Serialization.JsonPropertyName("Name")] public string MappedNameUsingJsonPropertyNameAttribute { get; set; } } [Fact] public void And() { Expression<Func<TestEntity, bool>> filter = x => x.ProductID == 1 && x.ProductName == "Chai"; Assert.Equal("ProductID eq 1 and ProductName eq 'Chai'", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void Or() { Expression<Func<TestEntity, bool>> filter = x => x.ProductName == "Chai" || x.ProductID == 1; Assert.Equal("ProductName eq 'Chai' or ProductID eq 1", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void Not() { Expression<Func<TestEntity, bool>> filter = x => !(x.ProductName == "Chai"); Assert.Equal("not (ProductName eq 'Chai')", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void Precedence() { Expression<Func<TestEntity, bool>> filter = x => (x.ProductID == 1 || x.ProductID == 2) && x.ProductName == "Chai"; Assert.Equal("(ProductID eq 1 or ProductID eq 2) and ProductName eq 'Chai'", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void EqualString() { Expression<Func<TestEntity, bool>> filter = x => x.ProductName == "Chai"; Assert.Equal("ProductName eq 'Chai'", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void EqualFieldToString() { Expression<Func<TestEntity, bool>> filter = x => x.ProductName.ToString() == "Chai"; Assert.Equal("ProductName eq 'Chai'", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void EqualValueToString() { var name = "Chai"; Expression<Func<TestEntity, bool>> filter = x => x.ProductName.ToString() == name.ToString(); Assert.Equal("ProductName eq 'Chai'", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void EqualNumeric() { Expression<Func<TestEntity, bool>> filter = x => x.ProductID == 1; Assert.Equal("ProductID eq 1", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void NotEqualNumeric() { Expression<Func<TestEntity, bool>> filter = x => x.ProductID != 1; Assert.Equal("ProductID ne 1", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void GreaterNumeric() { Expression<Func<TestEntity, bool>> filter = x => x.ProductID > 1; Assert.Equal("ProductID gt 1", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void GreaterOrEqualNumeric() { Expression<Func<TestEntity, bool>> filter = x => x.ProductID >= 1.5; Assert.Equal($"ProductID ge 1.5{FormatSettings.DoubleNumberSuffix}", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void LessNumeric() { Expression<Func<TestEntity, bool>> filter = x => x.ProductID < 1; Assert.Equal("ProductID lt 1", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void LessOrEqualNumeric() { Expression<Func<TestEntity, bool>> filter = x => x.ProductID <= 1; Assert.Equal("ProductID le 1", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void AddEqualNumeric() { Expression<Func<TestEntity, bool>> filter = x => x.ProductID + 1 == 2; Assert.Equal("ProductID add 1 eq 2", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void SubEqualNumeric() { Expression<Func<TestEntity, bool>> filter = x => x.ProductID - 1 == 2; Assert.Equal("ProductID sub 1 eq 2", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void MulEqualNumeric() { Expression<Func<TestEntity, bool>> filter = x => x.ProductID * 1 == 2; Assert.Equal("ProductID mul 1 eq 2", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void DivEqualNumeric() { Expression<Func<TestEntity, bool>> filter = x => x.ProductID / 1 == 2; Assert.Equal("ProductID div 1 eq 2", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void ModEqualNumeric() { Expression<Func<TestEntity, bool>> filter = x => x.ProductID % 1 == 2; Assert.Equal("ProductID mod 1 eq 2", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void EqualLong() { Expression<Func<TestEntity, bool>> filter = x => x.ProductID == 1L; Assert.Equal($"ProductID eq 1{FormatSettings.LongNumberSuffix}", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void EqualDecimal() { Expression<Func<TestEntity, bool>> filter = x => x.Price == 1M; Assert.Equal($"Price eq 1{FormatSettings.DecimalNumberSuffix}", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void EqualDecimalWithFractionalPart() { Expression<Func<TestEntity, bool>> filter = x => x.Price == 1.23M; Assert.Equal($"Price eq 1.23{FormatSettings.DecimalNumberSuffix}", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void EqualGuid() { Expression<Func<TestEntity, bool>> filter = x => x.LinkID == Guid.Empty; Assert.Equal($"LinkID eq {FormatSettings.GetGuidFormat("00000000-0000-0000-0000-000000000000")}", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void EqualDateTime() { if (FormatSettings.ODataVersion < 4) { Expression<Func<TestEntity, bool>> filter = x => x.CreationTime == new DateTime(2013, 1, 1); Assert.Equal("CreationTime eq datetime'2013-01-01T00:00:00'", ODataExpression.FromLinqExpression(filter).AsString(_session)); } } [Fact] public void EqualDateTimeOffset() { Expression<Func<TestEntity, bool>> filter = x => x.Updated == new DateTimeOffset(new DateTime(2013, 1, 1, 0, 0, 0, DateTimeKind.Utc)); Assert.Equal($"Updated eq {FormatSettings.GetDateTimeOffsetFormat("2013-01-01T00:00:00Z")}", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void EqualTimeSpan() { Expression<Func<TestEntity, bool>> filter = x => x.Period == new TimeSpan(1, 2, 3); Assert.Equal($"Period eq {FormatSettings.TimeSpanPrefix}'PT1H2M3S'", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void LengthOfStringEqual() { Expression<Func<TestEntity, bool>> filter = x => x.ProductName.Length == 4; Assert.Equal("length(ProductName) eq 4", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void StringToLowerEqual() { Expression<Func<TestEntity, bool>> filter = x => x.ProductName.ToLower() == "chai"; Assert.Equal("tolower(ProductName) eq 'chai'", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void StringToUpperEqual() { Expression<Func<TestEntity, bool>> filter = x => x.ProductName.ToUpper() == "CHAI"; Assert.Equal("toupper(ProductName) eq 'CHAI'", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void StringStartsWithEqual() { Expression<Func<TestEntity, bool>> filter = x => x.ProductName.StartsWith("Ch") == true; Assert.Equal("startswith(ProductName,'Ch') eq true", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void StringEndsWithEqual() { Expression<Func<TestEntity, bool>> filter = x => x.ProductName.EndsWith("Ch") == true; Assert.Equal("endswith(ProductName,'Ch') eq true", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void StringContainsEqualTrue() { Expression<Func<TestEntity, bool>> filter = x => x.ProductName.Contains("ai") == true; Assert.Equal($"{FormatSettings.GetContainsFormat("ProductName", "ai")} eq true", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void StringContainsEqualFalse() { Expression<Func<TestEntity, bool>> filter = x => x.ProductName.Contains("ai") == false; Assert.Equal($"{FormatSettings.GetContainsFormat("ProductName", "ai")} eq false", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void StringContains() { Expression<Func<TestEntity, bool>> filter = x => x.ProductName.Contains("ai"); Assert.Equal(FormatSettings.GetContainsFormat("ProductName", "ai"), ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void StringContainedIn() { Expression<Func<TestEntity, bool>> filter = x => "Chai".Contains(x.ProductName); Assert.Equal(FormatSettings.GetContainedInFormat("ProductName", "Chai"), ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void StringNotContains() { Expression<Func<TestEntity, bool>> filter = x => !x.ProductName.Contains("ai"); Assert.Equal($"not {FormatSettings.GetContainsFormat("ProductName", "ai")}", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void StringToLowerAndContains() { Expression<Func<TestEntity, bool>> filter = x => x.ProductName.ToLower().Contains("Chai"); Assert.Equal(FormatSettings.GetContainsFormat("tolower(ProductName)","Chai"), ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void IndexOfStringEqual() { Expression<Func<TestEntity, bool>> filter = x => x.ProductName.IndexOf("ai") == 1; Assert.Equal("indexof(ProductName,'ai') eq 1", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void SubstringWithPositionEqual() { Expression<Func<TestEntity, bool>> filter = x => x.ProductName.Substring(1) == "hai"; Assert.Equal("substring(ProductName,1) eq 'hai'", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void SubstringWithPositionAndLengthEqual() { Expression<Func<TestEntity, bool>> filter = x => x.ProductName.Substring(1, 2) == "ha"; Assert.Equal("substring(ProductName,1,2) eq 'ha'", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void ReplaceStringEqual() { Expression<Func<TestEntity, bool>> filter = x => x.ProductName.Replace("a", "o") == "Choi"; Assert.Equal("replace(ProductName,'a','o') eq 'Choi'", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void TrimEqual() { Expression<Func<TestEntity, bool>> filter = x => x.ProductName.Trim() == "Chai"; Assert.Equal("trim(ProductName) eq 'Chai'", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void ConcatEqual() { Expression<Func<TestEntity, bool>> filter = x => string.Concat(x.ProductName, "Chai") == "ChaiChai"; Assert.Equal("concat(ProductName,'Chai') eq 'ChaiChai'", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void DayEqual() { Expression<Func<TestEntity, bool>> filter = x => x.CreationTime.Day == 1; Assert.Equal("day(CreationTime) eq 1", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void MonthEqual() { Expression<Func<TestEntity, bool>> filter = x => x.CreationTime.Month == 2; Assert.Equal("month(CreationTime) eq 2", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void YearEqual() { Expression<Func<TestEntity, bool>> filter = x => x.CreationTime.Year == 3; Assert.Equal("year(CreationTime) eq 3", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void HourEqual() { Expression<Func<TestEntity, bool>> filter = x => x.CreationTime.Hour == 4; Assert.Equal("hour(CreationTime) eq 4", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void MinuteEqual() { Expression<Func<TestEntity, bool>> filter = x => x.CreationTime.Minute == 5; Assert.Equal("minute(CreationTime) eq 5", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void SecondEqual() { Expression<Func<TestEntity, bool>> filter = x => x.CreationTime.Second == 6; Assert.Equal("second(CreationTime) eq 6", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void RoundEqual() { Expression<Func<TestEntity, bool>> filter = x => decimal.Round(x.Price) == 1; Assert.Equal($"round(Price) eq 1{FormatSettings.DecimalNumberSuffix}", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void FloorEqual() { Expression<Func<TestEntity, bool>> filter = x => decimal.Floor(x.Price) == 1; Assert.Equal($"floor(Price) eq 1{FormatSettings.DecimalNumberSuffix}", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void CeilingEqual() { Expression<Func<TestEntity, bool>> filter = x => decimal.Ceiling(x.Price) == 2; Assert.Equal($"ceiling(Price) eq 2{FormatSettings.DecimalNumberSuffix}", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void EqualNestedProperty() { Expression<Func<TestEntity, bool>> filter = x => x.Nested.ProductID == 1; Assert.Equal("Nested/ProductID eq 1", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void EqualNestedPropertyLengthOfStringEqual() { Expression<Func<TestEntity, bool>> filter = x => x.Nested.ProductName.Length == 4; Assert.Equal("length(Nested/ProductName) eq 4", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void ConvertEqual() { var id = "1"; Expression<Func<TestEntity, bool>> filter = x => x.Nested.ProductID == Convert.ToInt32(id); Assert.Equal("Nested/ProductID eq 1", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void FilterWithMappedPropertiesUsingColumnAttribute() { Expression<Func<TestEntity, bool>> filter = x => x.MappedNameUsingColumnAttribute == "Milk"; Assert.Equal("Name eq 'Milk'", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void FilterWithMappedPropertiesUsingDataAttribute() { Expression<Func<TestEntity, bool>> filter = x => x.MappedNameUsingDataAttribute == "Milk"; Assert.Equal("Name eq 'Milk'", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void FilterWithMappedPropertiesUsingDataMemberAttribute() { Expression<Func<TestEntity, bool>> filter = x => x.MappedNameUsingDataMemberAttribute == "Milk"; Assert.Equal("Name eq 'Milk'", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void FilterWithMappedPropertiesUsingOtherAttribute() { Expression<Func<TestEntity, bool>> filter = x => x.MappedNameUsingOtherAttribute == "Milk"; Assert.Equal("Name eq 'Milk'", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void FilterWithMappedPropertiesUsingDataMemberAndOtherAttribute() { Expression<Func<TestEntity, bool>> filter = x => x.MappedNameUsingDataMemberAndOtherAttribute == "Milk"; Assert.Equal("Name eq 'Milk'", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void FilterWithMappedPropertiesUsingJsonPropertyAttribute() { Expression<Func<TestEntity, bool>> filter = x => x.MappedNameUsingJsonPropertyAttribute == "Milk"; Assert.Equal("Name eq 'Milk'", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void FilterWithMappedPropertiesUsingJsonPropertyNameAttribute() { Expression<Func<TestEntity, bool>> filter = x => x.MappedNameUsingJsonPropertyNameAttribute == "Milk"; Assert.Equal("Name eq 'Milk'", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void FilterWithEnum() { Expression<Func<TestEntity, bool>> filter = x => x.Address.Type == AddressType.Corporate; Assert.Equal($"Address/Type eq {FormatSettings.GetEnumFormat(AddressType.Corporate, typeof(AddressType), "NorthwindModel")}", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void FilterWithEnum_LocalVar() { var addressType = AddressType.Corporate; Expression<Func<TestEntity, bool>> filter = x => x.Address.Type == addressType; Assert.Equal($"Address/Type eq {FormatSettings.GetEnumFormat(AddressType.Corporate, typeof(AddressType), "NorthwindModel")}", ODataExpression.FromLinqExpression(filter).AsString(_session)); } private AddressType addressType = AddressType.Corporate; [Fact] public void FilterWithEnum_MemberVar() { Expression<Func<TestEntity, bool>> filter = x => x.Address.Type == this.addressType; Assert.Equal($"Address/Type eq {FormatSettings.GetEnumFormat(AddressType.Corporate, typeof(AddressType), "NorthwindModel")}", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void FilterWithEnum_Const() { const AddressType addressType = AddressType.Corporate; Expression<Func<TestEntity, bool>> filter = x => x.Address.Type == addressType; Assert.Equal($"Address/Type eq {FormatSettings.GetEnumFormat(AddressType.Corporate, typeof(AddressType), "NorthwindModel")}", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void FilterWithEnum_PrefixFree() { var enumPrefixFree = _session.Settings.EnumPrefixFree; _session.Settings.EnumPrefixFree = true; try { Expression<Func<TestEntity, bool>> filter = x => x.Address.Type == AddressType.Corporate; Assert.Equal($"Address/Type eq {FormatSettings.GetEnumFormat(AddressType.Corporate, typeof(AddressType), "NorthwindModel", true)}", ODataExpression.FromLinqExpression(filter).AsString(_session)); } finally { _session.Settings.EnumPrefixFree = enumPrefixFree; } } [Fact] public void FilterWithEnum_HasFlag() { Expression<Func<TestEntity, bool>> filter = x => x.Address.Type.HasFlag(AddressType.Corporate); Assert.Equal($"Address/Type has {FormatSettings.GetEnumFormat(AddressType.Corporate, typeof(AddressType), "NorthwindModel")}", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void FilterWithEnum_ToString() { Expression<Func<TestEntity, bool>> filter = x => x.Address.Type.ToString() == AddressType.Corporate.ToString(); Assert.Equal($"Address/Type eq {FormatSettings.GetEnumFormat(AddressType.Corporate, typeof(AddressType), "NorthwindModel")}", ODataExpression.FromLinqExpression(filter).AsString(_session)); } [Fact] public void FilterDateTimeRange() { var beforeDT = new DateTime(2013, 1, 1, 0, 0, 0, DateTimeKind.Utc); var afterDT = new DateTime(2014, 2, 2, 0, 0, 0, DateTimeKind.Utc); Expression<Func<TestEntity, bool>> filter = x => (x.CreationTime >= beforeDT) && (x.CreationTime < afterDT); if (FormatSettings.ODataVersion < 4) { Assert.Equal("CreationTime ge datetime'2013-01-01T00:00:00Z' and CreationTime lt datetime'2014-02-02T00:00:00Z'", ODataExpression.FromLinqExpression(filter).AsString(_session)); } else { Assert.Equal("CreationTime ge 2013-01-01T00:00:00Z and CreationTime lt 2014-02-02T00:00:00Z", ODataExpression.FromLinqExpression(filter).AsString(_session)); } } [Fact] public void ExpressionBuilder() { Expression<Predicate<TestEntity>> condition1 = x => x.ProductName == "Chai"; Expression<Func<TestEntity, bool>> condition2 = x => x.ProductID == 1; var filter = new ODataExpression(condition1); filter = filter || new ODataExpression(condition2); Assert.Equal("ProductName eq 'Chai' or ProductID eq 1", filter.AsString(_session)); } [Fact] public void ExpressionBuilderGeneric() { var filter = new ODataExpression<TestEntity>(x => x.ProductName == "Chai"); filter = filter || new ODataExpression<TestEntity>(x => x.ProductID == 1); Assert.Equal("ProductName eq 'Chai' or ProductID eq 1", filter.AsString(_session)); } [Fact] public void ExpressionBuilderGrouping() { Expression<Predicate<TestEntity>> condition1 = x => x.ProductName == "Chai"; Expression<Func<TestEntity, bool>> condition2 = x => x.ProductID == 1; Expression<Predicate<TestEntity>> condition3 = x => x.ProductName == "Kaffe"; Expression<Func<TestEntity, bool>> condition4 = x => x.ProductID == 2; var filter1 = new ODataExpression(condition1) || new ODataExpression(condition2); var filter2 = new ODataExpression(condition3) || new ODataExpression(condition4); var filter = filter1 && filter2; Assert.Equal("(ProductName eq 'Chai' or ProductID eq 1) and (ProductName eq 'Kaffe' or ProductID eq 2)", filter.AsString(_session)); } [Fact] public void FilterEqualityToMappedPropertyOfOtherEntity() { var otherEntity = new TestEntity { MappedNameUsingDataMemberAttribute = "Other Name" }; Expression<Func<TestEntity, bool>> filter = x => x.MappedNameUsingDataMemberAttribute == otherEntity.MappedNameUsingDataMemberAttribute; Assert.Equal("Name eq 'Other Name'", ODataExpression.FromLinqExpression(filter).AsString(_session)); otherEntity = new TestEntity { MappedNameUsingJsonPropertyAttribute = "Other Name" }; filter = x => x.MappedNameUsingJsonPropertyAttribute == otherEntity.MappedNameUsingJsonPropertyAttribute; Assert.Equal("Name eq 'Other Name'", ODataExpression.FromLinqExpression(filter).AsString(_session)); } } }
// Source: https://github.com/ajdotnet/AJ.Console using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Resources; namespace AJ.Console { /// <summary> /// <para> /// Baseclass for console applications. /// Supports the following features: /// </para> /// <list type="bullet"> /// <item><term>Clean and easy handling of arguments (parameters, switches)</term></item> /// <item><term>Errorhandling</term></item> /// <item><term>Standard parameter (help, etc.)</term></item> /// <item><term>Output control (Verbose)</term></item> /// <item><term>Output of logo, syntax, etc.</term></item> /// <item><term>parameter file support</term></item> /// <item><term>log file support</term></item> /// <item><term>colored output (via p/invoke)</term></item> /// <item><term>...</term></item> /// </list> /// <para> /// Usage: Derive a class and overwrite the abstract methods /// <see cref="ApplyArguments" />, /// <see cref="ApplySwitch" />, and /// <see cref="Process" />. /// Add a *.resx-file (name=name of your derived class /// containing messages (Help, Logo etc.) /// </para> /// <para> /// The applications main-method should look like this: /// </para> /// <code> /// [STAThread] /// static int Main(string[] args) /// { /// MyApp app= new MyApp(); /// return app.Run(args); /// } /// </code> /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")] public abstract class ConsoleApp { /////////////////////////////////////////////////////////////////////////////// #region interface /// <summary> /// This method will be called with the application arguments, /// i.e. the parameters preceeding switches. e.g. /// <c>cl.exe file1.txt file2.txt /p a b /c</c> /// will call this method with {"file1.txt", "file2.txt"} /// </summary> /// <param name="values">The values.</param> protected abstract void ApplyArguments(string[] values); /// <summary> /// <para> /// This method will be called for every switch, i.e. parameters beginning with a slash. /// </para> /// <para> /// Parameters following a switch will be treated as arguments to that switch. /// e.g.: <c>cl.exe file1.txt file2.txt /p a b /c</c> /// will call this method with /// <c>"/p", {"a", "b"}</c> /// and again with /// <c>"/c", {}</c>. /// </para> /// </summary> /// <param name="name">name of the switch (including the slash</param> /// <param name="values">arguments of the switch</param> protected abstract void ApplySwitch(string name, string[] values); /// <summary> /// Called to start the actuall processing. This method is only /// called if no help has been requested and no error was raised during /// the argument parsing phase /// </summary> protected abstract void Process(); #endregion /////////////////////////////////////////////////////////////////////////////// #region singleton implementation static ConsoleApp _current = null; /// <summary> /// c'tor checks if this class is the first (and thus only) singleton /// </summary> protected ConsoleApp() { Debug.Assert(_current == null); _current = this; this.CurrentShowLevel = ShowLevel.Normal; } /// <summary> /// Singleton instance /// </summary> static public ConsoleApp Current { get { return _current; } } #endregion /////////////////////////////////////////////////////////////////////////////// #region properties & members Parameter _arguments = null; List<Parameter> _switches = null; ResourceManager _rmThis = null; ResourceManager _rmFallback = null; bool _helpWanted = false; bool _logoHasBeenShown = false; bool _showLogo = true; string _logFileName = null; StreamWriter _logFileStream = null; /// <value> /// The current show level. /// </value> public ShowLevel CurrentShowLevel { get; set; } /// <value> /// The application return value. /// </value> public byte ReturnValue { get; set; } /// <value> /// Gets the 'Syntax' message from the resources /// </value> public string SyntaxMessage { get { return GetString(ResKey.Syntax); } } /// <value> /// gets the 'System' parameters (part of the syntax) from the resources /// </value> public string SystemParametersMessage { get { return GetString(ResKey.SystemParameters); } } /// <value> /// gets the 'Logo' message from the resources /// </value> public string LogoMessage { get { return GetString(ResKey.Logo); } } /// <value> /// gets the 'Error' message from the resources (default feedback, will be complemented with exception message). /// </value> public string ErrorMessage { get { return GetString(ResKey.Error); } } /// <value> /// gets the 'Help' message from the resources /// </value> public string HelpMessage { get { return GetString(ResKey.Help); } } #endregion /////////////////////////////////////////////////////////////////////////////// #region messages /// <summary> /// print Logo-Text (once) /// </summary> protected virtual void PrintLogoText() { if (_logoHasBeenShown) return; _logoHasBeenShown = true; if (_showLogo) this.WriteLine(ShowLevel.Important, LogoMessage); } /// <summary> /// print syntax (including system parameters) /// </summary> protected virtual void PrintSyntaxText() { this.WriteLine(ShowLevel.Normal, SyntaxMessage); this.WriteLine(ShowLevel.Normal, SystemParametersMessage); } /// <summary> /// print logo and help, syntax, and help text /// </summary> protected virtual void PrintHelpText() { PrintLogoText(); PrintSyntaxText(); WriteLine(ShowLevel.Normal, HelpMessage); } /// <summary> /// helper to get a ressource string /// including fallback /// </summary> /// <param name="name">The name.</param> /// <returns></returns> protected string GetString(string name) { try { string ret = _rmThis.GetString(name); if (ret != null) return ret; } catch (MissingManifestResourceException) { } return _rmFallback.GetString(name); } #endregion /////////////////////////////////////////////////////////////////////////////// #region parameter parsing /// <summary> /// parse command line parsen /// </summary> /// <param name="args">actual command line arguments</param> void ParseCommandLine(string[] args) { _switches = new List<Parameter>(); var currentParam = new Parameter(); for (int i = 0; i < args.Length; ++i) ParseParam(args[i], ref currentParam); AddParsedParam(ref currentParam); } /// <summary> /// evaluates the single parameter (including @parameterfile and !logfile) /// </summary> /// <param name="arg">The argument.</param> /// <param name="currentParam">The current parameter.</param> void ParseParam(string arg, ref Parameter currentParam) { arg = arg.Trim(); if (arg.Length == 0) { // might happen in parameter files } else if (arg[0] == '@') { // parameter file support: xy.exe @params.txt InsertParamsFromFile(arg.Substring(1)); } else if (arg[0] == '!') { // logfile name xy.exe !logfile.txt _logFileName = arg.Substring(1); } if (arg[0] != '/') { // next argument currentParam.Values.Add(arg); } else { // next switch AddParsedParam(ref currentParam); currentParam = new Parameter(); currentParam.Name = arg; } } /// <summary> /// take last arguments or switch /// </summary> void AddParsedParam(ref Parameter currentParam) { if (currentParam == null) return; if (string.IsNullOrEmpty(currentParam.Name)) { System.Diagnostics.Debug.Assert(_arguments == null); _arguments = currentParam; } else { _switches.Add(currentParam); } currentParam = null; } /// <summary> /// read textfile lines as arguments /// </summary> /// <param name="paramfile">The paramfile.</param> /// <exception cref="AJ.Console.ConsoleException"></exception> void InsertParamsFromFile(string paramfile) { try { var currentParam = new Parameter(); var contents = File.ReadAllLines(paramfile); foreach (var line in contents) ParseParam(line, ref currentParam); AddParsedParam(ref currentParam); } catch (Exception ex) { throw new ConsoleException(string.Format(CultureInfo.CurrentCulture, GetString(ResEx.CouldNotReadParameterFile), paramfile), ex); } } #endregion /////////////////////////////////////////////////////////////////////////////// #region argument and switch handling /// <summary> /// get all arguments /// </summary> /// <returns> /// all arguments /// </returns> public string[] GetArguments() { if (_arguments == null) return new string[] { }; return _arguments.Values.ToArray(); } /// <summary> /// get switch by name: "/d file1 file2" returns {"file1", "file2"} for switch "/d" /// </summary> /// <param name="name">switch name</param> /// <returns> /// arguments for the switch /// </returns> public string[] GetSwitch(string name) { var sw = _switches.Where(s => s.Name == name).FirstOrDefault(); if (sw == null) return new string[] { }; return sw.Values.ToArray(); } /// <summary> /// check if switch has been provided (for boolean switches) /// </summary> /// <param name="name">The name.</param> /// <param name="ignoreCase">if set to <c>true</c> it ignores the case.</param> /// <returns></returns> public bool HasSwitch(string name, bool ignoreCase = true) { return _switches .Where(s => string.Compare(s.Name, name, ignoreCase ? StringComparison.InvariantCultureIgnoreCase : StringComparison.InvariantCulture) == 0) .Any(); } /// <summary> /// apply all switches /// </summary> protected virtual void ApplySwitches() { foreach (var p in _switches) { if (!p.IsApplied) ApplySwitch(p.Name, p.Values.ToArray()); p.IsApplied = true; } } /// <summary> /// handle special switches (help, output control, ...) /// </summary> protected virtual void ApplySpecialSwitches() { foreach (var p in _switches) { if (!p.IsApplied && ApplySpecialSwitch(p.Name, p.Values.ToArray())) p.IsApplied = true; } } /// <summary> /// handle special switches (help, output control, ...) /// </summary> /// <param name="name">The name.</param> /// <param name="values">The values.</param> /// <returns></returns> protected virtual bool ApplySpecialSwitch(string name, string[] values) { switch (name) { case "/?": case "/h": case "/help": _helpWanted = true; return true; case "/v": case "/verbose": this.CurrentShowLevel = ShowLevel.Verbose; return true; case "/q": case "/quiet": this.CurrentShowLevel = ShowLevel.Warning; return true; case "/nologo": _showLogo = false; return true; } return false; } /// <summary> /// Helper: checks if the array length is in a given range, /// throws an exception if not. /// to be used in <see cref="ApplyArguments" /> and <see cref="ApplySwitch" />. /// </summary> /// <param name="test">The test.</param> /// <param name="min">The minimum.</param> /// <param name="max">The maximum.</param> /// <param name="name">The name of the parameter.</param> /// <exception cref="AJ.Console.ConsoleException"> /// </exception> public void EnsureLength(string[] test, int min, int max, string name) { if (name == null) name = "arguments"; if (test == null) throw new ConsoleException(GetString(ResEx.InvalidArgumentsNull), name); if (test.Length < min) throw new ConsoleException(GetString(ResEx.InvalidArgumentsMin), name, min); if (test.Length > max) throw new ConsoleException(GetString(ResEx.InvalidArgumentsMax), name, max); } /// <summary> /// Helper: throws an exception for an unknown switch /// to be used in <see cref="ApplySwitch" />. /// </summary> /// <param name="name">The name.</param> /// <exception cref="AJ.Console.ConsoleException"></exception> public void ThrowUnknownSwitch(string name) { throw new ConsoleException(GetString(ResEx.UnknownSwitch), name); } /// <summary> /// Helper: throws an exception for invalid arguments /// to be used in <see cref="ApplyArguments" /> . /// </summary> /// <param name="message">The message.</param> /// <exception cref="AJ.Console.ConsoleException"></exception> public void ThrowInvalidArguments(string message) { throw new ConsoleException(GetString(ResEx.InvalidArguments), message); } #endregion /////////////////////////////////////////////////////////////////////////////// #region running /// <summary> /// Helper: call run with command line arguments. /// </summary> /// <returns></returns> protected int Run() { return Run(Environment.GetCommandLineArgs()); } /// <summary> /// application workflow: /// <list type="bullet"> /// <item><term><see cref="Init" />: override for initialization</term></item> /// <item><term><see cref="ParseCommandLine" />: command line parsing (internal)</term></item> /// <item><term><see cref="OpenLogFile" />: open log file (internal)</term></item> /// <item><term><see cref="ApplySpecialSwitches" />: handle special switches (override if necessary)</term></item> /// <item><term><see cref="ApplyArguments" />: abstract</term></item> /// <item><term><see cref="ApplySwitches" />: abstract</term></item> /// <item><term><see cref="Process" />: abstract</term></item> /// <item><term><see cref="CleanUp" />: override for cleanup</term></item> /// </list> /// In case orf exceptions <see cref="ConsoleException" /> will be /// printed with message only, other exceptions including stacktrace.<br /> /// </summary> /// <param name="args">The arguments.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "last chance exception handler")] protected virtual int Run(string[] args) { try { Init(); ParseCommandLine(args); OpenLogFile(); ApplySpecialSwitches(); if (_helpWanted) { PrintHelpText(); ReturnValue = SpecialReturnValue.HelpRequested; } else { PrintLogoText(); ApplyArguments(GetArguments()); ApplySwitches(); Process(); } } catch (ConsoleException ex) { PrintLogoText(); PrintExceptionHierarchy(ex.InnerException); if (!string.IsNullOrEmpty(ex.Message)) WriteLine(ShowLevel.Error, ex.Message); WriteLine(ShowLevel.Warning, ErrorMessage); ReturnValue = SpecialReturnValue.HandledException; } catch (Exception ex) { PrintLogoText(); WriteLine(ShowLevel.Error, "Exception: " + ex.ToString()); ReturnValue = SpecialReturnValue.UnHandledException; } finally { CleanUp(); Terminating(); } return ReturnValue; } /// <summary> /// helper to print exceptions (including inner exceptions) /// </summary> /// <param name="ex">The ex.</param> public void PrintExceptionHierarchy(Exception ex) { if (ex == null) return; if (ex.InnerException != null) PrintExceptionHierarchy(ex.InnerException); WriteLine(ShowLevel.Error, "Exception: " + ex.GetType().FullName); WriteLine(ShowLevel.Error, " Message: " + ex.Message); } /// <summary> /// initialization /// </summary> /// <exception cref="System.Exception">resource file missing: + this.GetType().FullName</exception> protected virtual void Init() { try { if (_rmThis == null) _rmThis = new ResourceManager(this.GetType()); if (_rmFallback == null) _rmFallback = new ResourceManager(typeof(ConsoleApp)); // make sure resources are available _rmThis.GetString("Logo"); _rmFallback.GetString("Logo"); } catch (Exception ex) { throw new InvalidProgramException("resource file missing: " + this.GetType().FullName, ex); } } /// <summary> /// cleanup /// </summary> protected virtual void CleanUp() { _rmThis = null; _rmFallback = null; CloseLogFile(); } /// <summary> /// init logfile /// </summary> /// <exception cref="AJ.Console.ConsoleException"></exception> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] void OpenLogFile() { if (string.IsNullOrEmpty(_logFileName)) return; try { Stream strm = new FileStream(_logFileName, FileMode.Append, FileAccess.Write, FileShare.Read); _logFileStream = new StreamWriter(strm); _logFileStream.WriteLine("### LOG START : " + DateTime.Now.ToString() + " ###"); } catch (Exception ex) { throw new ConsoleException(string.Format(CultureInfo.CurrentCulture, GetString(ResEx.LogfileCouldNotBeOpened), _logFileName), ex); } } /// <summary> /// close logfile /// </summary> void CloseLogFile() { if (_logFileStream == null) return; _logFileStream.WriteLine("### LOG END : " + DateTime.Now.ToString() + " ###"); _logFileStream.Close(); } /// <summary> /// if being debugged, wait before the window closes /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Console.Write(System.String)")] [Conditional("DEBUG")] void Terminating() { if (!System.Diagnostics.Debugger.IsAttached) return; System.Console.WriteLine(); Win32.SetConsoleTextColor(Win32.StdHandle.Output, Color.Blue, Color.White); System.Console.Write("Terminated with return value " + ReturnValue.ToString(CultureInfo.InvariantCulture) + ". <Press Return>"); Win32.SetConsoleTextColor(Win32.StdHandle.Output, Color.White, Color.Red); System.Console.Read(); System.Console.Write("Terminating..."); } #endregion /////////////////////////////////////////////////////////////////////////////// #region output /// <summary> /// print normal line /// </summary> /// <param name="line">The line.</param> public void WriteLine(string line) { if (ShowLevel.Normal < this.CurrentShowLevel) return; ColorWriteLine(ShowLevel.Normal, line); } /// <summary> /// print line depending on level /// </summary> /// <param name="show">The show.</param> /// <param name="line">The line.</param> public void WriteLine(ShowLevel show, string line) { if (show < this.CurrentShowLevel) return; ColorWriteLine(show, line); } /// <summary> /// print line depending on level /// </summary> /// <param name="show">The show.</param> /// <param name="foreground">The foreground.</param> /// <param name="background">The background.</param> /// <param name="line">The line.</param> public void WriteLine(ShowLevel show, Color foreground, Color background, string line) { if (show < this.CurrentShowLevel) return; ColorWriteLine(show, foreground, background, line); } /// <summary> /// Colors the write line. /// </summary> /// <param name="show">The show.</param> /// <param name="foregroud">The foregroud.</param> /// <param name="background">The background.</param> /// <param name="line">The line.</param> void ColorWriteLine(ShowLevel show, Color foregroud, Color background, string line) { if (line == null) return; bool stderr = (show >= ShowLevel.Error); Win32.StdHandle h = stderr ? Win32.StdHandle.Error : Win32.StdHandle.Output; Color backgroundOld; Color foregroundOld; Win32.GetConsoleTextColor(h, out foregroundOld, out backgroundOld); Win32.SetConsoleTextColor(h, foregroud, background); MonoWriteLine(show, line); Win32.SetConsoleTextColor(h, foregroundOld, backgroundOld); } void ColorWriteLine(ShowLevel show, string line) { if (line == null) return; bool stderr = (show >= ShowLevel.Error); Win32.StdHandle h = stderr ? Win32.StdHandle.Error : Win32.StdHandle.Output; Color background; Color foreground; Win32.GetConsoleTextColor(h, out foreground, out background); switch (show) { case ShowLevel.Verbose: Win32.SetConsoleTextColor(h, Color.Gray, background); break; case ShowLevel.Normal: Win32.SetConsoleTextColor(h, Color.White, background); break; case ShowLevel.Important: Win32.SetConsoleTextColor(h, Color.Yellow, background); break; case ShowLevel.Warning: Win32.SetConsoleTextColor(h, Color.Teal, background); break; case ShowLevel.Error: Win32.SetConsoleTextColor(h, Color.Red, background); break; } MonoWriteLine(show, line); Win32.SetConsoleTextColor(h, foreground, background); } void MonoWriteLine(ShowLevel show, string line) { if (line == null) return; if (show >= ShowLevel.Error) System.Console.Error.WriteLine(line); else System.Console.Out.WriteLine(line); if (_logFileStream != null) _logFileStream.WriteLine("[" + show + "] " + line); } #endregion } }
#if NET20 || NET35 #pragma warning disable 0420 // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ConcurrentQueue.cs // // <OWNER>Microsoft</OWNER> // // A lock-free, concurrent queue primitive, and its associated debugger view type. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Threading; namespace System.Collections.Concurrent { /// <summary> /// Represents a thread-safe first-in, first-out collection of objects. /// </summary> /// <typeparam name="T">Specifies the type of elements in the queue.</typeparam> /// <remarks> /// All public and protected members of <see cref="ConcurrentQueue{T}"/> are thread-safe and may be used /// concurrently from multiple threads. /// </remarks> [ComVisible(false)] [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(SystemCollectionsConcurrent_ProducerConsumerCollectionDebugView<>))] [HostProtection(Synchronization = true, ExternalThreading = true)] [Serializable] internal class ConcurrentQueue<T> : IProducerConsumerCollection<T>//, IReadOnlyCollection<T> { //fields of ConcurrentQueue [NonSerialized] private volatile Segment m_head; [NonSerialized] private volatile Segment m_tail; private T[] m_serializationArray; // Used for custom serialization. private const int SEGMENT_SIZE = 32; //number of snapshot takers, GetEnumerator(), ToList() and ToArray() operations take snapshot. [NonSerialized] internal volatile int m_numSnapshotTakers = 0; /// <summary> /// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/> class. /// </summary> public ConcurrentQueue() { m_head = m_tail = new Segment(0, this); } /// <summary> /// Initializes the contents of the queue from an existing collection. /// </summary> /// <param name="collection">A collection from which to copy elements.</param> private void InitializeFromCollection(IEnumerable<T> collection) { Segment localTail = new Segment(0, this);//use this local variable to avoid the extra volatile read/write. this is safe because it is only called from ctor m_head = localTail; int index = 0; foreach (T element in collection) { // Contract.Assert(index >= 0 && index < SEGMENT_SIZE); localTail.UnsafeAdd(element); index++; if (index >= SEGMENT_SIZE) { localTail = localTail.UnsafeGrow(); index = 0; } } m_tail = localTail; } /// <summary> /// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/> /// class that contains elements copied from the specified collection /// </summary> /// <param name="collection">The collection whose elements are copied to the new <see /// cref="ConcurrentQueue{T}"/>.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="collection"/> argument is /// null.</exception> public ConcurrentQueue(IEnumerable<T> collection) { if (collection == null) { throw new ArgumentNullException("collection"); } InitializeFromCollection(collection); } /// <summary> /// Get the data array to be serialized /// </summary> [OnSerializing] private void OnSerializing(StreamingContext context) { // save the data into the serialization array to be saved m_serializationArray = ToArray(); } /// <summary> /// Construct the queue from a previously seiralized one /// </summary> [OnDeserialized] private void OnDeserialized(StreamingContext context) { // Contract.Assert(m_serializationArray != null); InitializeFromCollection(m_serializationArray); m_serializationArray = null; } /// <summary> /// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see /// cref="T:System.Array"/>, starting at a particular /// <see cref="T:System.Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the /// destination of the elements copied from the /// <see cref="T:System.Collections.Concurrent.ConcurrentBag"/>. The <see /// cref="T:System.Array">Array</see> must have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying /// begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in /// Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than /// zero.</exception> /// <exception cref="ArgumentException"> /// <paramref name="array"/> is multidimensional. -or- /// <paramref name="array"/> does not have zero-based indexing. -or- /// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/> /// -or- The number of elements in the source <see cref="T:System.Collections.ICollection"/> is /// greater than the available space from <paramref name="index"/> to the end of the destination /// <paramref name="array"/>. -or- The type of the source <see /// cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the /// destination <paramref name="array"/>. /// </exception> void ICollection.CopyTo(Array array, int index) { // Validate arguments. if (array == null) { throw new ArgumentNullException("array"); } // We must be careful not to corrupt the array, so we will first accumulate an // internal list of elements that we will then copy to the array. This requires // some extra allocation, but is necessary since we don't know up front whether // the array is sufficiently large to hold the stack's contents. ((ICollection)ToList()).CopyTo(array, index); } /// <summary> /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is /// synchronized with the SyncRoot. /// </summary> /// <value>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized /// with the SyncRoot; otherwise, false. For <see cref="ConcurrentQueue{T}"/>, this property always /// returns false.</value> bool ICollection.IsSynchronized { // Gets a value indicating whether access to this collection is synchronized. Always returns // false. The reason is subtle. While access is in face thread safe, it's not the case that // locking on the SyncRoot would have prevented concurrent pushes and pops, as this property // would typically indicate; that's because we internally use CAS operations vs. true locks. get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see /// cref="T:System.Collections.ICollection"/>. This property is not supported. /// </summary> /// <exception cref="T:System.NotSupportedException">The SyncRoot property is not supported.</exception> object ICollection.SyncRoot { get { throw new NotSupportedException("ConcurrentCollection SyncRoot Not Supported"); } } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns>An <see cref="T:System.Collections.IEnumerator"/> that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<T>)this).GetEnumerator(); } /// <summary> /// Attempts to add an object to the <see /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. /// </summary> /// <param name="item">The object to add to the <see /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. The value can be a null /// reference (Nothing in Visual Basic) for reference types. /// </param> /// <returns>true if the object was added successfully; otherwise, false.</returns> /// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will always add the object to the /// end of the <see cref="ConcurrentQueue{T}"/> /// and return true.</remarks> bool IProducerConsumerCollection<T>.TryAdd(T item) { Enqueue(item); return true; } /// <summary> /// Attempts to remove and return an object from the <see /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. /// </summary> /// <param name="item"> /// When this method returns, if the operation was successful, <paramref name="item"/> contains the /// object removed. If no object was available to be removed, the value is unspecified. /// </param> /// <returns>true if an element was removed and returned succesfully; otherwise, false.</returns> /// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will attempt to remove the object /// from the beginning of the <see cref="ConcurrentQueue{T}"/>. /// </remarks> bool IProducerConsumerCollection<T>.TryTake(out T item) { return TryDequeue(out item); } /// <summary> /// Gets a value that indicates whether the <see cref="ConcurrentQueue{T}"/> is empty. /// </summary> /// <value>true if the <see cref="ConcurrentQueue{T}"/> is empty; otherwise, false.</value> /// <remarks> /// For determining whether the collection contains any items, use of this property is recommended /// rather than retrieving the number of items from the <see cref="Count"/> property and comparing it /// to 0. However, as this collection is intended to be accessed concurrently, it may be the case /// that another thread will modify the collection after <see cref="IsEmpty"/> returns, thus invalidating /// the result. /// </remarks> public bool IsEmpty { get { Segment head = m_head; if (!head.IsEmpty) //fast route 1: //if current head is not empty, then queue is not empty return false; else if (head.Next == null) //fast route 2: //if current head is empty and it's the last segment //then queue is empty return true; else //slow route: //current head is empty and it is NOT the last segment, //it means another thread is growing new segment { SpinWait spin = new SpinWait(); while (head.IsEmpty) { if (head.Next == null) return true; spin.SpinOnce(); head = m_head; } return false; } } } /// <summary> /// Copies the elements stored in the <see cref="ConcurrentQueue{T}"/> to a new array. /// </summary> /// <returns>A new array containing a snapshot of elements copied from the <see /// cref="ConcurrentQueue{T}"/>.</returns> public T[] ToArray() { return ToList().ToArray(); } /// <summary> /// Copies the <see cref="ConcurrentQueue{T}"/> elements to a new <see /// cref="T:System.Collections.Generic.List{T}"/>. /// </summary> /// <returns>A new <see cref="T:System.Collections.Generic.List{T}"/> containing a snapshot of /// elements copied from the <see cref="ConcurrentQueue{T}"/>.</returns> private List<T> ToList() { // Increments the number of active snapshot takers. This increment must happen before the snapshot is // taken. At the same time, Decrement must happen after list copying is over. Only in this way, can it // eliminate race condition when Segment.TryRemove() checks whether m_numSnapshotTakers == 0. Interlocked.Increment(ref m_numSnapshotTakers); List<T> list = new List<T>(); try { //store head and tail positions in buffer, Segment head, tail; int headLow, tailHigh; GetHeadTailPositions(out head, out tail, out headLow, out tailHigh); if (head == tail) { head.AddToList(list, headLow, tailHigh); } else { head.AddToList(list, headLow, SEGMENT_SIZE - 1); Segment curr = head.Next; while (curr != tail) { curr.AddToList(list, 0, SEGMENT_SIZE - 1); curr = curr.Next; } //Add tail segment tail.AddToList(list, 0, tailHigh); } } finally { // This Decrement must happen after copying is over. Interlocked.Decrement(ref m_numSnapshotTakers); } return list; } /// <summary> /// Store the position of the current head and tail positions. /// </summary> /// <param name="head">return the head segment</param> /// <param name="tail">return the tail segment</param> /// <param name="headLow">return the head offset, value range [0, SEGMENT_SIZE]</param> /// <param name="tailHigh">return the tail offset, value range [-1, SEGMENT_SIZE-1]</param> private void GetHeadTailPositions(out Segment head, out Segment tail, out int headLow, out int tailHigh) { head = m_head; tail = m_tail; headLow = head.Low; tailHigh = tail.High; SpinWait spin = new SpinWait(); //we loop until the observed values are stable and sensible. //This ensures that any update order by other methods can be tolerated. while ( //if head and tail changed, retry head != m_head || tail != m_tail //if low and high pointers, retry || headLow != head.Low || tailHigh != tail.High //if head jumps ahead of tail because of concurrent grow and dequeue, retry || head.m_index > tail.m_index) { spin.SpinOnce(); head = m_head; tail = m_tail; headLow = head.Low; tailHigh = tail.High; } } /// <summary> /// Gets the number of elements contained in the <see cref="ConcurrentQueue{T}"/>. /// </summary> /// <value>The number of elements contained in the <see cref="ConcurrentQueue{T}"/>.</value> /// <remarks> /// For determining whether the collection contains any items, use of the <see cref="IsEmpty"/> /// property is recommended rather than retrieving the number of items from the <see cref="Count"/> /// property and comparing it to 0. /// </remarks> public int Count { get { //store head and tail positions in buffer, Segment head, tail; int headLow, tailHigh; GetHeadTailPositions(out head, out tail, out headLow, out tailHigh); if (head == tail) { return tailHigh - headLow + 1; } //head segment int count = SEGMENT_SIZE - headLow; //middle segment(s), if any, are full. //We don't deal with overflow to be consistent with the behavior of generic types in CLR. count += SEGMENT_SIZE * ((int)(tail.m_index - head.m_index - 1)); //tail segment count += tailHigh + 1; return count; } } /// <summary> /// Copies the <see cref="ConcurrentQueue{T}"/> elements to an existing one-dimensional <see /// cref="T:System.Array">Array</see>, starting at the specified array index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the /// destination of the elements copied from the /// <see cref="ConcurrentQueue{T}"/>. The <see cref="T:System.Array">Array</see> must have zero-based /// indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying /// begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in /// Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than /// zero.</exception> /// <exception cref="ArgumentException"><paramref name="index"/> is equal to or greater than the /// length of the <paramref name="array"/> /// -or- The number of elements in the source <see cref="ConcurrentQueue{T}"/> is greater than the /// available space from <paramref name="index"/> to the end of the destination <paramref /// name="array"/>. /// </exception> public void CopyTo(T[] array, int index) { if (array == null) { throw new ArgumentNullException("array"); } // We must be careful not to corrupt the array, so we will first accumulate an // internal list of elements that we will then copy to the array. This requires // some extra allocation, but is necessary since we don't know up front whether // the array is sufficiently large to hold the stack's contents. ToList().CopyTo(array, index); } /// <summary> /// Returns an enumerator that iterates through the <see /// cref="ConcurrentQueue{T}"/>. /// </summary> /// <returns>An enumerator for the contents of the <see /// cref="ConcurrentQueue{T}"/>.</returns> /// <remarks> /// The enumeration represents a moment-in-time snapshot of the contents /// of the queue. It does not reflect any updates to the collection after /// GetEnumerator was called. The enumerator is safe to use /// concurrently with reads from and writes to the queue. /// </remarks> public IEnumerator<T> GetEnumerator() { // Increments the number of active snapshot takers. This increment must happen before the snapshot is // taken. At the same time, Decrement must happen after the enumeration is over. Only in this way, can it // eliminate race condition when Segment.TryRemove() checks whether m_numSnapshotTakers == 0. Interlocked.Increment(ref m_numSnapshotTakers); // Takes a snapshot of the queue. // A design flaw here: if a Thread.Abort() happens, we cannot decrement m_numSnapshotTakers. But we cannot // wrap the following with a try/finally block, otherwise the decrement will happen before the yield return // statements in the GetEnumerator (head, tail, headLow, tailHigh) method. Segment head, tail; int headLow, tailHigh; GetHeadTailPositions(out head, out tail, out headLow, out tailHigh); //If we put yield-return here, the iterator will be lazily evaluated. As a result a snapshot of // the queue is not taken when GetEnumerator is initialized but when MoveNext() is first called. // This is inconsistent with existing generic collections. In order to prevent it, we capture the // value of m_head in a buffer and call out to a helper method. //The old way of doing this was to return the ToList().GetEnumerator(), but ToList() was an // unnecessary perfomance hit. return GetEnumerator(head, tail, headLow, tailHigh); } /// <summary> /// Helper method of GetEnumerator to seperate out yield return statement, and prevent lazy evaluation. /// </summary> private IEnumerator<T> GetEnumerator(Segment head, Segment tail, int headLow, int tailHigh) { try { SpinWait spin = new SpinWait(); if (head == tail) { for (int i = headLow; i <= tailHigh; i++) { // If the position is reserved by an Enqueue operation, but the value is not written into, // spin until the value is available. spin.Reset(); while (!head.m_state[i].m_value) { spin.SpinOnce(); } yield return head.m_array[i]; } } else { //iterate on head segment for (int i = headLow; i < SEGMENT_SIZE; i++) { // If the position is reserved by an Enqueue operation, but the value is not written into, // spin until the value is available. spin.Reset(); while (!head.m_state[i].m_value) { spin.SpinOnce(); } yield return head.m_array[i]; } //iterate on middle segments Segment curr = head.Next; while (curr != tail) { for (int i = 0; i < SEGMENT_SIZE; i++) { // If the position is reserved by an Enqueue operation, but the value is not written into, // spin until the value is available. spin.Reset(); while (!curr.m_state[i].m_value) { spin.SpinOnce(); } yield return curr.m_array[i]; } curr = curr.Next; } //iterate on tail segment for (int i = 0; i <= tailHigh; i++) { // If the position is reserved by an Enqueue operation, but the value is not written into, // spin until the value is available. spin.Reset(); while (!tail.m_state[i].m_value) { spin.SpinOnce(); } yield return tail.m_array[i]; } } } finally { // This Decrement must happen after the enumeration is over. Interlocked.Decrement(ref m_numSnapshotTakers); } } /// <summary> /// Adds an object to the end of the <see cref="ConcurrentQueue{T}"/>. /// </summary> /// <param name="item">The object to add to the end of the <see /// cref="ConcurrentQueue{T}"/>. The value can be a null reference /// (Nothing in Visual Basic) for reference types. /// </param> public void Enqueue(T item) { SpinWait spin = new SpinWait(); while (true) { Segment tail = m_tail; if (tail.TryAppend(item)) return; spin.SpinOnce(); } } /// <summary> /// Attempts to remove and return the object at the beginning of the <see /// cref="ConcurrentQueue{T}"/>. /// </summary> /// <param name="result"> /// When this method returns, if the operation was successful, <paramref name="result"/> contains the /// object removed. If no object was available to be removed, the value is unspecified. /// </param> /// <returns>true if an element was removed and returned from the beggining of the <see /// cref="ConcurrentQueue{T}"/> /// succesfully; otherwise, false.</returns> public bool TryDequeue(out T result) { while (!IsEmpty) { Segment head = m_head; if (head.TryRemove(out result)) return true; //since method IsEmpty spins, we don't need to spin in the while loop } result = default(T); return false; } /// <summary> /// Attempts to return an object from the beginning of the <see cref="ConcurrentQueue{T}"/> /// without removing it. /// </summary> /// <param name="result">When this method returns, <paramref name="result"/> contains an object from /// the beginning of the <see cref="T:System.Collections.Concurrent.ConccurrentQueue{T}"/> or an /// unspecified value if the operation failed.</param> /// <returns>true if and object was returned successfully; otherwise, false.</returns> public bool TryPeek(out T result) { Interlocked.Increment(ref m_numSnapshotTakers); while (!IsEmpty) { Segment head = m_head; if (head.TryPeek(out result)) { Interlocked.Decrement(ref m_numSnapshotTakers); return true; } //since method IsEmpty spins, we don't need to spin in the while loop } result = default(T); Interlocked.Decrement(ref m_numSnapshotTakers); return false; } /// <summary> /// private class for ConcurrentQueue. /// a queue is a linked list of small arrays, each node is called a segment. /// A segment contains an array, a pointer to the next segment, and m_low, m_high indices recording /// the first and last valid elements of the array. /// </summary> private class Segment { //we define two volatile arrays: m_array and m_state. Note that the accesses to the array items //do not get volatile treatment. But we don't need to worry about loading adjacent elements or //store/load on adjacent elements would suffer reordering. // - Two stores: these are at risk, but CLRv2 memory model guarantees store-release hence we are safe. // - Two loads: because one item from two volatile arrays are accessed, the loads of the array references // are sufficient to prevent reordering of the loads of the elements. internal volatile T[] m_array; // For each entry in m_array, the corresponding entry in m_state indicates whether this position contains // a valid value. m_state is initially all false. internal volatile VolatileBool[] m_state; //pointer to the next segment. null if the current segment is the last segment private volatile Segment m_next; //We use this zero based index to track how many segments have been created for the queue, and //to compute how many active segments are there currently. // * The number of currently active segments is : m_tail.m_index - m_head.m_index + 1; // * m_index is incremented with every Segment.Grow operation. We use Int64 type, and we can safely // assume that it never overflows. To overflow, we need to do 2^63 increments, even at a rate of 4 // billion (2^32) increments per second, it takes 2^31 seconds, which is about 64 years. internal readonly long m_index; //indices of where the first and last valid values // - m_low points to the position of the next element to pop from this segment, range [0, infinity) // m_low >= SEGMENT_SIZE implies the segment is disposable // - m_high points to the position of the latest pushed element, range [-1, infinity) // m_high == -1 implies the segment is new and empty // m_high >= SEGMENT_SIZE-1 means this segment is ready to grow. // and the thread who sets m_high to SEGMENT_SIZE-1 is responsible to grow the segment // - Math.Min(m_low, SEGMENT_SIZE) > Math.Min(m_high, SEGMENT_SIZE-1) implies segment is empty // - initially m_low =0 and m_high=-1; private volatile int m_low; private volatile int m_high; private volatile ConcurrentQueue<T> m_source; /// <summary> /// Create and initialize a segment with the specified index. /// </summary> internal Segment(long index, ConcurrentQueue<T> source) { m_array = new T[SEGMENT_SIZE]; m_state = new VolatileBool[SEGMENT_SIZE]; //all initialized to false m_high = -1; // Contract.Assert(index >= 0); m_index = index; m_source = source; } /// <summary> /// return the next segment /// </summary> internal Segment Next { get { return m_next; } } /// <summary> /// return true if the current segment is empty (doesn't have any element available to dequeue, /// false otherwise /// </summary> internal bool IsEmpty { get { return (Low > High); } } /// <summary> /// Add an element to the tail of the current segment /// exclusively called by ConcurrentQueue.InitializedFromCollection /// InitializeFromCollection is responsible to guaratee that there is no index overflow, /// and there is no contention /// </summary> /// <param name="value"></param> internal void UnsafeAdd(T value) { // Contract.Assert(m_high < SEGMENT_SIZE - 1); m_high++; m_array[m_high] = value; m_state[m_high].m_value = true; } /// <summary> /// Create a new segment and append to the current one /// Does not update the m_tail pointer /// exclusively called by ConcurrentQueue.InitializedFromCollection /// InitializeFromCollection is responsible to guaratee that there is no index overflow, /// and there is no contention /// </summary> /// <returns>the reference to the new Segment</returns> internal Segment UnsafeGrow() { // Contract.Assert(m_high >= SEGMENT_SIZE - 1); Segment newSegment = new Segment(m_index + 1, m_source); //m_index is Int64, we don't need to worry about overflow m_next = newSegment; return newSegment; } /// <summary> /// Create a new segment and append to the current one /// Update the m_tail pointer /// This method is called when there is no contention /// </summary> internal void Grow() { //no CAS is needed, since there is no contention (other threads are blocked, busy waiting) Segment newSegment = new Segment(m_index + 1, m_source); //m_index is Int64, we don't need to worry about overflow m_next = newSegment; // Contract.Assert(m_source.m_tail == this); m_source.m_tail = m_next; } /// <summary> /// Try to append an element at the end of this segment. /// </summary> /// <param name="value">the element to append</param> /// <returns>true if the element is appended, false if the current segment is full</returns> /// <remarks>if appending the specified element succeeds, and after which the segment is full, /// then grow the segment</remarks> internal bool TryAppend(T value) { //quickly check if m_high is already over the boundary, if so, bail out if (m_high >= SEGMENT_SIZE - 1) { return false; } //Now we will use a CAS to increment m_high, and store the result in newhigh. //Depending on how many free spots left in this segment and how many threads are doing this Increment //at this time, the returning "newhigh" can be // 1) < SEGMENT_SIZE - 1 : we took a spot in this segment, and not the last one, just insert the value // 2) == SEGMENT_SIZE - 1 : we took the last spot, insert the value AND grow the segment // 3) > SEGMENT_SIZE - 1 : we failed to reserve a spot in this segment, we return false to // Queue.Enqueue method, telling it to try again in the next segment. int newhigh = SEGMENT_SIZE; //initial value set to be over the boundary //We need do Interlocked.Increment and value/state update in a finally block to ensure that they run //without interuption. This is to prevent anything from happening between them, and another dequeue //thread maybe spinning forever to wait for m_state[] to be true; try { } finally { newhigh = Interlocked.Increment(ref m_high); if (newhigh <= SEGMENT_SIZE - 1) { m_array[newhigh] = value; m_state[newhigh].m_value = true; } //if this thread takes up the last slot in the segment, then this thread is responsible //to grow a new segment. Calling Grow must be in the finally block too for reliability reason: //if thread abort during Grow, other threads will be left busy spinning forever. if (newhigh == SEGMENT_SIZE - 1) { Grow(); } } //if newhigh <= SEGMENT_SIZE-1, it means the current thread successfully takes up a spot return newhigh <= SEGMENT_SIZE - 1; } /// <summary> /// try to remove an element from the head of current segment /// </summary> /// <param name="result">The result.</param> /// <returns>return false only if the current segment is empty</returns> internal bool TryRemove(out T result) { SpinWait spin = new SpinWait(); int lowLocal = Low, highLocal = High; while (lowLocal <= highLocal) { //try to update m_low if (Interlocked.CompareExchange(ref m_low, lowLocal + 1, lowLocal) == lowLocal) { //if the specified value is not available (this spot is taken by a push operation, // but the value is not written into yet), then spin SpinWait spinLocal = new SpinWait(); while (!m_state[lowLocal].m_value) { spinLocal.SpinOnce(); } result = m_array[lowLocal]; // If there is no other thread taking snapshot (GetEnumerator(), ToList(), etc), reset the deleted entry to null. // It is ok if after this conditional check m_numSnapshotTakers becomes > 0, because new snapshots won't include // the deleted entry at m_array[lowLocal]. if (m_source.m_numSnapshotTakers <= 0) { m_array[lowLocal] = default(T); //release the reference to the object. } //if the current thread sets m_low to SEGMENT_SIZE, which means the current segment becomes //disposable, then this thread is responsible to dispose this segment, and reset m_head if (lowLocal + 1 >= SEGMENT_SIZE) { // Invariant: we only dispose the current m_head, not any other segment // In usual situation, disposing a segment is simply seting m_head to m_head.m_next // But there is one special case, where m_head and m_tail points to the same and ONLY //segment of the queue: Another thread A is doing Enqueue and finds that it needs to grow, //while the *current* thread is doing *this* Dequeue operation, and finds that it needs to //dispose the current (and ONLY) segment. Then we need to wait till thread A finishes its //Grow operation, this is the reason of having the following while loop spinLocal = new SpinWait(); while (m_next == null) { spinLocal.SpinOnce(); } // Contract.Assert(m_source.m_head == this); m_source.m_head = m_next; } return true; } else { //CAS failed due to contention: spin briefly and retry spin.SpinOnce(); lowLocal = Low; highLocal = High; } }//end of while result = default(T); return false; } /// <summary> /// try to peek the current segment /// </summary> /// <param name="result">holds the return value of the element at the head position, /// value set to default(T) if there is no such an element</param> /// <returns>true if there are elements in the current segment, false otherwise</returns> internal bool TryPeek(out T result) { result = default(T); int lowLocal = Low; if (lowLocal > High) return false; SpinWait spin = new SpinWait(); while (!m_state[lowLocal].m_value) { spin.SpinOnce(); } result = m_array[lowLocal]; return true; } /// <summary> /// Adds part or all of the current segment into a List. /// </summary> /// <param name="list">the list to which to add</param> /// <param name="start">the start position</param> /// <param name="end">the end position</param> internal void AddToList(List<T> list, int start, int end) { for (int i = start; i <= end; i++) { SpinWait spin = new SpinWait(); while (!m_state[i].m_value) { spin.SpinOnce(); } list.Add(m_array[i]); } } /// <summary> /// return the position of the head of the current segment /// Value range [0, SEGMENT_SIZE], if it's SEGMENT_SIZE, it means this segment is exhausted and thus empty /// </summary> internal int Low { get { return Math.Min(m_low, SEGMENT_SIZE); } } /// <summary> /// return the logical position of the tail of the current segment /// Value range [-1, SEGMENT_SIZE-1]. When it's -1, it means this is a new segment and has no elemnet yet /// </summary> internal int High { get { //if m_high > SEGMENT_SIZE, it means it's out of range, we should return //SEGMENT_SIZE-1 as the logical position return Math.Min(m_high, SEGMENT_SIZE - 1); } } } }//end of class Segment /// <summary> /// A wrapper struct for volatile bool, please note the copy of the struct it self will not be volatile /// for example this statement will not include in volatilness operation volatileBool1 = volatileBool2 the jit will copy the struct and will ignore the volatile /// </summary> struct VolatileBool { public VolatileBool(bool value) { m_value = value; } public volatile bool m_value; } } #endif
using System; using System.Globalization; using System.Linq; using ToolKit.Validation; namespace ToolKit.OData { /// <summary> /// OData supports various kinds of query options for querying data. There are several kinds of /// basic predicates and built-in functions for a filter, including logical operators and /// arithmetic operators. This class will help you go through the common scenarios for these /// query options. /// </summary> public class ODataFilter { private string _filter; /// <summary> /// Initializes a new instance of the <see cref="ODataFilter" /> class. /// </summary> public ODataFilter() => _filter = string.Empty; /// <summary> /// Initializes a new instance of the <see cref="ODataFilter" /> class. /// </summary> /// <param name="filter">The OData filter string.</param> public ODataFilter(string filter) => _filter = filter; /// <summary> /// Add to this filter an Logical And expression. /// </summary> /// <param name="filter">An OData filter.</param> /// <returns>This OData filter.</returns> public ODataFilter And(ODataFilter filter) { Check.NotNull(filter, nameof(filter)); _filter = $"({_filter}) and ({filter})"; return this; } /// <summary> /// Add to this filter an expression where the value is equal the two field's content. /// </summary> /// <param name="field1">The name of the first property.</param> /// <param name="field2">The name of the second property.</param> /// <param name="value">The value.</param> /// <returns>This OData filter.</returns> public ODataFilter Concat(string field1, string field2, string value) => AppendFilter($"concat({field1}, {field2}) eq '{value}'"); /// <summary> /// Add to this filter an expression where the value is contained in the field's content. /// </summary> /// <param name="field">The name of the property.</param> /// <param name="value">The value.</param> /// <returns>This OData filter.</returns> public ODataFilter Contains(string field, string value) => AppendFilter($"contains({field},'{value}')"); /// <summary> /// Add to this filter an expression where the value ends the field's content. /// </summary> /// <param name="field">The name of the property.</param> /// <param name="value">The value.</param> /// <returns>This OData filter.</returns> public ODataFilter EndsWith(string field, string value) => AppendFilter($"endswith({field},'{value}')"); /// <summary> /// Add to this filter an expression where the field is equal to the value. /// </summary> /// <param name="field">The name of the property.</param> /// <param name="value">The value.</param> /// <returns>This OData filter.</returns> public ODataFilter EqualTo(string field, int value) => AddCommonExpression(field, "eq", value.ToString(CultureInfo.InvariantCulture)); /// <summary> /// Add to this filter an expression where the field is equal to the value. /// </summary> /// <param name="field">The name of the property.</param> /// <param name="value">The value.</param> /// <returns>This OData filter.</returns> public ODataFilter EqualTo(string field, string value) => AddCommonExpression(field, "eq", value); /// <summary> /// Add to this filter an expression where the field is greater than the value. /// </summary> /// <param name="field">The name of the property.</param> /// <param name="value">The value.</param> /// <returns>This OData filter.</returns> public ODataFilter GreaterThan(string field, int value) => AddCommonExpression(field, "gt", value.ToString(CultureInfo.InvariantCulture)); /// <summary> /// Add to this filter an expression where the field is greater than or equal to the value. /// </summary> /// <param name="field">The name of the property.</param> /// <param name="value">The value.</param> /// <returns>This OData filter.</returns> public ODataFilter GreaterThanOrEqual(string field, int value) => AddCommonExpression(field, "ge", value.ToString(CultureInfo.InvariantCulture)); /// <summary> /// Add to this filter an expression where the value starts the field's content. /// </summary> /// <param name="field">The name of the property.</param> /// <param name="value">The value.</param> /// <param name="index">The index of the value in the contents of the field.</param> /// <returns>This OData filter.</returns> public ODataFilter IndexOf(string field, string value, int index) => AppendFilter($"indexof({field},'{value}') eq {index}"); /// <summary> /// Add to this filter an expression where the field is less than the value. /// </summary> /// <param name="field">The name of the property.</param> /// <param name="value">The value.</param> /// <returns>This OData filter.</returns> public ODataFilter LessThan(string field, int value) => AddCommonExpression(field, "lt", value.ToString(CultureInfo.InvariantCulture)); /// <summary> /// Add to this filter an expression where the field is less than or equal to the value. /// </summary> /// <param name="field">The name of the property.</param> /// <param name="value">The value.</param> /// <returns>This OData filter.</returns> public ODataFilter LessThanOrEqual(string field, int value) => AddCommonExpression(field, "le", value.ToString(CultureInfo.InvariantCulture)); /// <summary> /// Negates this filter. /// </summary> /// <returns>This OData filter.</returns> public ODataFilter Not() { _filter = $"not ({_filter})"; return this; } /// <summary> /// Add to this filter an expression where the field is not equal to the value. /// </summary> /// <param name="field">The name of the property.</param> /// <param name="value">The value.</param> /// <returns>This OData filter.</returns> public ODataFilter NotEqualTo(string field, int value) => AddCommonExpression(field, "ne", value.ToString(CultureInfo.InvariantCulture)); /// <summary> /// Add to this filter an expression where the field is not equal to the value. /// </summary> /// <param name="field">The name of the property.</param> /// <param name="value">The value.</param> /// <returns>This OData filter.</returns> public ODataFilter NotEqualTo(string field, string value) => AddCommonExpression(field, "ne", value); /// <summary> /// Add to this filter an Logical Or expression. /// </summary> /// <param name="filter">An OData filter.</param> /// <returns>This OData filter.</returns> public ODataFilter Or(ODataFilter filter) { Check.NotNull(filter, nameof(filter)); _filter = $"({_filter}) or ({filter})"; return this; } /// <summary> /// Add to this filter an expression where the value is equal the field's content as lower case. /// </summary> /// <param name="field">The name of the property.</param> /// <param name="value">The value.</param> /// <returns>This OData filter.</returns> public ODataFilter StartsWith(string field, string value) => AppendFilter($"startswith({field},'{value}')"); /// <summary> /// Add to this filter an expression where the value is a substring in the field's content. /// </summary> /// <param name="field">The name of the property.</param> /// <param name="value">The value.</param> /// <returns>This OData filter.</returns> public ODataFilter Substring(string field, string value) => AppendFilter($"substringof('{value}', {field}) eq true"); /// <summary> /// Add to this filter an expression where the value is equal the field's content as lower case. /// </summary> /// <param name="field">The name of the property.</param> /// <param name="value">The value.</param> /// <returns>This OData filter.</returns> public ODataFilter ToLower(string field, string value) => AppendFilter($"tolower({field}) eq '{value?.ToLower(CultureInfo.CurrentCulture)}'"); /// <summary> /// Returns a string that represents the filter. /// </summary> /// <returns>A string that represents the filter.</returns> public override string ToString() => _filter; /// <summary> /// Add to this filter an expression where the value is equal the field's content as upper case. /// </summary> /// <param name="field">The name of the property.</param> /// <param name="value">The value.</param> /// <returns>This OData filter.</returns> public ODataFilter ToUpper(string field, string value) => AppendFilter($"toupper({field}) eq '{value?.ToUpper(CultureInfo.CurrentCulture)}'"); /// <summary> /// Add to this filter an expression where the value is equal the field's content trimmed. /// </summary> /// <param name="field">The name of the property.</param> /// <param name="value">The value.</param> /// <returns>This OData filter.</returns> public ODataFilter Trim(string field, string value) => AppendFilter($"trim({field}) eq '{value}'"); private ODataFilter AddCommonExpression(string field, string operation, string value) { if (!value.All(char.IsNumber)) { value = $"'{value}'"; } return AppendFilter($"{field} {operation} {value}"); } private ODataFilter AppendFilter(string filter) { if (string.IsNullOrWhiteSpace(_filter)) { _filter = filter; } else { _filter = $"({_filter}) and ({filter})"; } return this; } } }
using System; using Server; using Server.Gumps; using Server.Network; using Server.Accounting; using Server.Engines.VeteranRewards; using Server.Multis; using Server.Mobiles; namespace Server.Items { public class SoulStone : Item, ISecurable { public override int LabelNumber { get { return 1030899; } } // soulstone private int m_ActiveItemID; private int m_InactiveItemID; private SecureLevel m_Level; [CommandProperty( AccessLevel.GameMaster )] public SecureLevel Level { get{ return m_Level; } set{ m_Level = value; } } [CommandProperty( AccessLevel.GameMaster )] public virtual int ActiveItemID { get { return m_ActiveItemID; } set { m_ActiveItemID = value; if( !IsEmpty ) this.ItemID = m_ActiveItemID; } } [CommandProperty( AccessLevel.GameMaster )] public virtual int InactiveItemID { get { return m_InactiveItemID; } set { m_InactiveItemID = value; if( IsEmpty ) this.ItemID = m_InactiveItemID; } } private string m_Account, m_LastUserName; private DateTime m_NextUse; // TODO: unused, it's here not to break serialize/deserialize private SkillName m_Skill; private double m_SkillValue; [CommandProperty( AccessLevel.GameMaster )] public string Account { get{ return m_Account; } set{ m_Account = value; } } [CommandProperty( AccessLevel.GameMaster )] public string LastUserName { get{ return m_LastUserName; } set{ m_LastUserName = value; InvalidateProperties(); } } [CommandProperty( AccessLevel.GameMaster )] public SkillName Skill { get{ return m_Skill; } set{ m_Skill = value; InvalidateProperties(); } } [CommandProperty( AccessLevel.GameMaster )] public double SkillValue { get{ return m_SkillValue; } set { m_SkillValue = value; if ( !IsEmpty ) this.ItemID = m_ActiveItemID; else this.ItemID = m_InactiveItemID; InvalidateProperties(); } } [CommandProperty( AccessLevel.GameMaster )] public bool IsEmpty { get{ return m_SkillValue <= 0.0; } } [Constructable] public SoulStone() : this( null ) { } [Constructable] public SoulStone( string account ) : this( account, 0x2A93, 0x2A94 ) { } public SoulStone( string account, int itemID ) : this( account, itemID, itemID ) { } public SoulStone( string account, int inactiveItemID, int activeItemID ) : base( inactiveItemID ) { Light = LightType.Circle300; LootType = LootType.Blessed; m_InactiveItemID = inactiveItemID; m_ActiveItemID = activeItemID; m_Account = account; } public override void GetProperties(ObjectPropertyList list) { base.GetProperties(list); if (!IsEmpty) list.Add(1070721, "#{0}\t{1:0.0}", AosSkillBonuses.GetLabel(Skill), SkillValue); // Skill stored: ~1_skillname~ ~2_skillamount~ string name = this.LastUserName; if (name == null) name = String.Format("#{0}", 1074235); // Unknown list.Add(1041602, "{0}", name); // Owner: ~1_val~ } private static bool CheckCombat( Mobile m, TimeSpan time ) { for ( int i = 0; i < m.Aggressed.Count; ++i ) { AggressorInfo info = m.Aggressed[i]; if ( DateTime.Now - info.LastCombatTime < time ) return true; } return false; } protected virtual bool CheckUse( Mobile from ) { DateTime now = DateTime.Now; PlayerMobile pm = from as PlayerMobile; if ( this.Deleted || !this.IsAccessibleTo( from ) ) { return false; } else if ( from.Map != this.Map || !from.InRange( GetWorldLocation(), 2 ) ) { from.LocalOverheadMessage( MessageType.Regular, 0x3B2, 1019045 ); // I can't reach that. return false; } else if ( this.Account != null && ( !(from.Account is Account) || from.Account.Username != this.Account ) ) { from.SendLocalizedMessage( 1070714 ); // This is an Account Bound Soulstone, and your character is not bound to it. You cannot use this Soulstone. return false; } else if ( CheckCombat( from, TimeSpan.FromMinutes( 2.0 ) ) ) { from.SendLocalizedMessage( 1070727 ); // You must wait two minutes after engaging in combat before you can use a Soulstone. return false; } else if ( from.Criminal ) { from.SendLocalizedMessage( 1070728 ); // You must wait two minutes after committing a criminal act before you can use a Soulstone. return false; } else if ( from.Region.GetLogoutDelay( from ) > TimeSpan.Zero ) { from.SendLocalizedMessage( 1070729 ); // In order to use your Soulstone, you must be in a safe log-out location. return false; } else if ( !from.Alive ) { from.SendLocalizedMessage( 1070730 ); // You may not use a Soulstone while your character is dead. return false; } else if ( Factions.Sigil.ExistsOn( from ) ) { from.SendLocalizedMessage( 1070731 ); // You may not use a Soulstone while your character has a faction town sigil. return false; } else if ( from.Spell != null && from.Spell.IsCasting ) { from.SendLocalizedMessage( 1070733 ); // You may not use a Soulstone while your character is casting a spell. return false; } else if ( from.Poisoned ) { from.SendLocalizedMessage( 1070734 ); // You may not use a Soulstone while your character is poisoned. return false; } else if ( from.Paralyzed ) { from.SendLocalizedMessage( 1070735 ); // You may not use a Soulstone while your character is paralyzed. return false; } #region Scroll of Alacrity if ( pm.AcceleratedStart > DateTime.Now ) { from.SendLocalizedMessage(1078115); // You may not use a soulstone while your character is under the effects of a Scroll of Alacrity. return false; } #endregion else { return true; } } public override void OnDoubleClick( Mobile from ) { if ( !CheckUse( from ) ) return; from.CloseGump( typeof( SelectSkillGump ) ); from.CloseGump( typeof( ConfirmSkillGump ) ); from.CloseGump( typeof( ConfirmTransferGump ) ); from.CloseGump( typeof( ConfirmRemovalGump ) ); from.CloseGump( typeof( ErrorGump ) ); if ( this.IsEmpty ) from.SendGump( new SelectSkillGump( this, from ) ); else from.SendGump( new ConfirmTransferGump( this, from ) ); } private class SelectSkillGump : Gump { private SoulStone m_Stone; public SelectSkillGump( SoulStone stone, Mobile from ) : base( 50, 50 ) { m_Stone = stone; AddPage( 0 ); AddBackground( 0, 0, 520, 440, 0x13BE ); AddImageTiled( 10, 10, 500, 20, 0xA40 ); AddImageTiled( 10, 40, 500, 360, 0xA40 ); AddImageTiled( 10, 410, 500, 20, 0xA40 ); AddAlphaRegion( 10, 10, 500, 420 ); AddHtmlLocalized( 10, 12, 500, 20, 1061087, 0x7FFF, false, false ); // Which skill do you wish to transfer to the Soulstone? AddButton( 10, 410, 0xFB1, 0xFB2, 0, GumpButtonType.Reply, 0 ); AddHtmlLocalized( 45, 412, 450, 20, 1060051, 0x7FFF, false, false ); // CANCEL for ( int i = 0, n = 0; i < from.Skills.Length; i++ ) { Skill skill = from.Skills[i]; if ( skill.Base > 0.0 ) { int p = n % 30; if ( p == 0 ) { int page = n / 30; if ( page > 0 ) { AddButton( 260, 380, 0xFA5, 0xFA6, 0, GumpButtonType.Page, page + 1 ); AddHtmlLocalized( 305, 382, 200, 20, 1011066, 0x7FFF, false, false ); // Next page } AddPage( page + 1 ); if ( page > 0 ) { AddButton( 10, 380, 0xFAE, 0xFAF, 0, GumpButtonType.Page, page ); AddHtmlLocalized( 55, 382, 200, 20, 1011067, 0x7FFF, false, false ); // Previous page } } int x = ( p % 2 == 0 ) ? 10 : 260; int y = ( p / 2 ) * 20 + 40; AddButton( x, y, 0xFA5, 0xFA6, i + 1, GumpButtonType.Reply, 0 ); AddHtmlLocalized(x + 45, y + 2, 200, 20, AosSkillBonuses.GetLabel(skill.SkillName), 0x7FFF, false, false); n++; } } } public override void OnResponse( NetState sender, RelayInfo info ) { if ( info.ButtonID == 0 || !m_Stone.IsEmpty ) return; Mobile from = sender.Mobile; int iSkill = info.ButtonID - 1; if ( iSkill < 0 || iSkill >= from.Skills.Length ) return; Skill skill = from.Skills[iSkill]; if ( skill.Base <= 0.0 ) return; if ( !m_Stone.CheckUse( from ) ) return; from.SendGump( new ConfirmSkillGump( m_Stone, skill ) ); } } private class ConfirmSkillGump : Gump { private SoulStone m_Stone; private Skill m_Skill; public ConfirmSkillGump( SoulStone stone, Skill skill ) : base( 50, 50 ) { m_Stone = stone; m_Skill = skill; AddBackground( 0, 0, 520, 440, 0x13BE ); AddImageTiled( 10, 10, 500, 20, 0xA40 ); AddImageTiled( 10, 40, 500, 360, 0xA40 ); AddImageTiled( 10, 410, 500, 20, 0xA40 ); AddAlphaRegion( 10, 10, 500, 420 ); AddHtmlLocalized( 10, 12, 500, 20, 1070709, 0x7FFF, false, false ); // <CENTER>Confirm Soulstone Transfer</CENTER> /* <CENTER>Soulstone</CENTER><BR> * You are using a Soulstone. This powerful artifact allows you to remove skill points * from your character and store them in the stone for later retrieval. In order to use * the stone, you must make sure your Skill Lock for the indicated skill is pointed downward. * Click the "Skills" button on your Paperdoll to access the Skill List, and double-check * your skill lock.<BR><BR> * * Once you activate the stone, all skill points in the indicated skill will be removed from * your character. These skill points can later be retrieved. IMPORTANT: When retrieving * skill points from a Soulstone, the Soulstone WILL REPLACE any existing skill points * already on your character!<BR><BR> * * This is an Account Bound Soulstone. Skill pointsstored inside can be retrieved by any * character on the same account as the character who placed them into the stone. */ AddHtmlLocalized( 10, 42, 500, 110, 1061067, 0x7FFF, false, true ); AddHtmlLocalized( 10, 200, 390, 20, 1062297, 0x7FFF, false, false ); // Skill Chosen: AddHtmlLocalized(210, 200, 390, 20, AosSkillBonuses.GetLabel(skill.SkillName), 0x7FFF, false, false); AddHtmlLocalized( 10, 220, 390, 20, 1062298, 0x7FFF, false, false ); // Current Value: AddLabel( 210, 220, 0x481, skill.Base.ToString( "0.0" ) ); AddHtmlLocalized( 10, 240, 390, 20, 1062299, 0x7FFF, false, false ); // Current Cap: AddLabel( 210, 240, 0x481, skill.Cap.ToString( "0.0" ) ); AddHtmlLocalized( 10, 260, 390, 20, 1062300, 0x7FFF, false, false ); // New Value: AddLabel( 210, 260, 0x481, "0.0" ); AddButton( 10, 360, 0xFA5, 0xFA6, 2, GumpButtonType.Reply, 0 ); AddHtmlLocalized( 45, 362, 450, 20, 1070720, 0x7FFF, false, false ); // Activate the stone. I am ready to transfer the skill points to it. AddButton( 10, 380, 0xFA5, 0xFA6, 1, GumpButtonType.Reply, 0 ); AddHtmlLocalized( 45, 382, 450, 20, 1062279, 0x7FFF, false, false ); // No, let me make another selection. AddButton( 10, 410, 0xFB1, 0xFB2, 0, GumpButtonType.Reply, 0 ); AddHtmlLocalized( 45, 412, 450, 20, 1060051, 0x7FFF, false, false ); // CANCEL } public override void OnResponse( NetState sender, RelayInfo info ) { if ( info.ButtonID == 0 || !m_Stone.IsEmpty ) return; Mobile from = sender.Mobile; if ( !m_Stone.CheckUse( from ) ) return; if ( info.ButtonID == 1 ) // Is asking for another selection { from.SendGump( new SelectSkillGump( m_Stone, from ) ); return; } if ( m_Skill.Base <= 0.0 ) return; if ( m_Skill.Lock != SkillLock.Down ) { // <CENTER>Unable to Transfer Selected Skill to Soulstone</CENTER> /* You cannot transfer the selected skill to the Soulstone at this time. The selected * skill may be locked or set to raise in your skill menu. Click on "Skills" in your * paperdoll menu to check your raise/locked/lower settings and your total skills. * Make any needed adjustments, then click "Continue". If you do not wish to transfer * the selected skill at this time, click "Cancel". */ from.SendGump( new ErrorGump( m_Stone, 1070710, 1070711 ) ); return; } m_Stone.Skill = m_Skill.SkillName; m_Stone.SkillValue = m_Skill.Base; m_Skill.Base = 0.0; from.SendLocalizedMessage( 1070712 ); // You have successfully transferred your skill points into the Soulstone. m_Stone.LastUserName = from.Name; Effects.SendLocationParticles( EffectItem.Create( from.Location, from.Map, EffectItem.DefaultDuration ), 0, 0, 0, 0, 0, 5060, 0 ); Effects.PlaySound( from.Location, from.Map, 0x243 ); Effects.SendMovingParticles( new Entity( Server.Serial.Zero, new Point3D( from.X - 6, from.Y - 6, from.Z + 15 ), from.Map ), from, 0x36D4, 7, 0, false, true, 0x497, 0, 9502, 1, 0, (EffectLayer)255, 0x100 ); Effects.SendTargetParticles( from, 0x375A, 35, 90, 0x00, 0x00, 9502, (EffectLayer)255, 0x100 ); } } private class ConfirmTransferGump : Gump { private SoulStone m_Stone; public ConfirmTransferGump( SoulStone stone, Mobile from ) : base( 50, 50 ) { m_Stone = stone; AddBackground( 0, 0, 520, 440, 0x13BE ); AddImageTiled( 10, 10, 500, 20, 0xA40 ); AddImageTiled( 10, 40, 500, 360, 0xA40 ); AddImageTiled( 10, 410, 500, 20, 0xA40 ); AddAlphaRegion( 10, 10, 500, 420 ); AddHtmlLocalized( 10, 12, 500, 20, 1070709, 0x7FFF, false, false ); // <CENTER>Confirm Soulstone Transfer</CENTER> /* <CENTER>Soulstone</CENTER><BR> * You are using a Soulstone. This powerful artifact allows you to remove skill points * from your character and store them in the stone for later retrieval. In order to use * the stone, you must make sure your Skill Lock for the indicated skill is pointed downward. * Click the "Skills" button on your Paperdoll to access the Skill List, and double-check * your skill lock.<BR><BR> * * Once you activate the stone, all skill points in the indicated skill will be removed from * your character. These skill points can later be retrieved. IMPORTANT: When retrieving * skill points from a Soulstone, the Soulstone WILL REPLACE any existing skill points * already on your character!<BR><BR> * * This is an Account Bound Soulstone. Skill pointsstored inside can be retrieved by any * character on the same account as the character who placed them into the stone. */ AddHtmlLocalized( 10, 42, 500, 110, 1061067, 0x7FFF, false, true ); AddHtmlLocalized( 10, 200, 390, 20, 1070718, 0x7FFF, false, false ); // Skill Stored: AddHtmlLocalized( 210, 200, 390, 20, 1044060 + (int)stone.Skill, 0x7FFF, false, false ); Skill fromSkill = from.Skills[stone.Skill]; AddHtmlLocalized( 10, 220, 390, 20, 1062298, 0x7FFF, false, false ); // Current Value: AddLabel( 210, 220, 0x481, fromSkill.Base.ToString( "0.0" ) ); AddHtmlLocalized( 10, 240, 390, 20, 1062299, 0x7FFF, false, false ); // Current Cap: AddLabel( 210, 240, 0x481, fromSkill.Cap.ToString( "0.0" ) ); AddHtmlLocalized( 10, 260, 390, 20, 1062300, 0x7FFF, false, false ); // New Value: AddLabel( 210, 260, 0x481, stone.SkillValue.ToString( "0.0" ) ); AddButton( 10, 360, 0xFA5, 0xFA6, 2, GumpButtonType.Reply, 0 ); AddHtmlLocalized( 45, 362, 450, 20, 1070719, 0x7FFF, false, false ); // Activate the stone. I am ready to retrieve the skill points from it. AddButton( 10, 380, 0xFA5, 0xFA6, 1, GumpButtonType.Reply, 0 ); AddHtmlLocalized( 45, 382, 450, 20, 1070723, 0x7FFF, false, false ); // Remove all skill points from this stone and DO NOT absorb them. AddButton( 10, 410, 0xFB1, 0xFB2, 0, GumpButtonType.Reply, 0 ); AddHtmlLocalized( 45, 412, 450, 20, 1060051, 0x7FFF, false, false ); // CANCEL } public override void OnResponse( NetState sender, RelayInfo info ) { if ( info.ButtonID == 0 || m_Stone.IsEmpty ) return; Mobile from = sender.Mobile; if ( !m_Stone.CheckUse( from ) ) return; if ( info.ButtonID == 1 ) // Remove skill points { from.SendGump( new ConfirmRemovalGump( m_Stone ) ); return; } SkillName skill = m_Stone.Skill; double skillValue = m_Stone.SkillValue; Skill fromSkill = from.Skills[m_Stone.Skill]; /* If we have, say, 88.4 in our skill and the stone holds 100, we need * 11.6 free points. Also, if we're below our skillcap by, say, 8.2 points, * we only need 11.6 - 8.2 = 3.4 points. */ int requiredAmount = (int)(skillValue * 10) - fromSkill.BaseFixedPoint - (from.SkillsCap - from.SkillsTotal); bool cannotAbsorb = false; if ( fromSkill.Lock != SkillLock.Up ) { cannotAbsorb = true; } else if ( requiredAmount > 0 ) { int available = 0; for ( int i = 0; i < from.Skills.Length; ++i ) { if ( from.Skills[i].Lock != SkillLock.Down ) continue; available += from.Skills[i].BaseFixedPoint; } if ( requiredAmount > available ) cannotAbsorb = true; } if ( cannotAbsorb ) { // <CENTER>Unable to Absorb Selected Skill from Soulstone</CENTER> /* You cannot absorb the selected skill from the Soulstone at this time. The selected * skill may be locked or set to lower in your skill menu. You may also be at your * total skill cap. Click on "Skills" in your paperdoll menu to check your * raise/locked/lower settings and your total skills. Make any needed adjustments, * then click "Continue". If you do not wish to transfer the selected skill at this * time, click "Cancel". */ from.SendGump( new ErrorGump( m_Stone, 1070717, 1070716 ) ); return; } if ( skillValue > fromSkill.Cap ) { // <CENTER>Unable to Absorb Selected Skill from Soulstone</CENTER> /* The amount of skill stored in this stone exceeds your individual skill cap for * that skill. In order to retrieve the skill points stored in this stone, you must * obtain a Power Scroll of the appropriate type and level in order to increase your * skill cap. You cannot currently retrieve the skill points stored in this stone. */ from.SendGump( new ErrorGump( m_Stone, 1070717, 1070715 ) ); return; } if ( fromSkill.Base >= skillValue ) { // <CENTER>Unable to Absorb Selected Skill from Soulstone</CENTER> /* You cannot transfer the selected skill to the Soulstone at this time. The selected * skill has a skill level higher than what is stored in the Soulstone. */ // Wrong message?! from.SendGump( new ErrorGump( m_Stone, 1070717, 1070802 ) ); return; } #region Scroll of ALacrity PlayerMobile pm = from as PlayerMobile; if (pm.AcceleratedStart > DateTime.Now) { // <CENTER>Unable to Absorb Selected Skill from Soulstone</CENTER> /*You may not use a soulstone while your character is under the effects of a Scroll of Alacrity.*/ // Wrong message?! from.SendGump(new ErrorGump(m_Stone, 1070717, 1078115)); return; } #endregion if ( requiredAmount > 0 ) { for ( int i = 0; i < from.Skills.Length; ++i ) { if ( from.Skills[i].Lock != SkillLock.Down ) continue; if ( requiredAmount >= from.Skills[i].BaseFixedPoint ) { requiredAmount -= from.Skills[i].BaseFixedPoint; from.Skills[i].Base = 0.0; } else { from.Skills[i].BaseFixedPoint -= requiredAmount; break; } } } fromSkill.Base = skillValue; m_Stone.SkillValue = 0.0; from.SendLocalizedMessage( 1070713 ); // You have successfully absorbed the Soulstone's skill points. m_Stone.LastUserName = from.Name; Effects.SendLocationParticles( EffectItem.Create( from.Location, from.Map, EffectItem.DefaultDuration ), 0, 0, 0, 0, 0, 5060, 0 ); Effects.PlaySound( from.Location, from.Map, 0x243 ); Effects.SendMovingParticles( new Entity( Server.Serial.Zero, new Point3D( from.X - 6, from.Y - 6, from.Z + 15 ), from.Map ), from, 0x36D4, 7, 0, false, true, 0x497, 0, 9502, 1, 0, (EffectLayer)255, 0x100 ); Effects.SendTargetParticles( from, 0x375A, 35, 90, 0x00, 0x00, 9502, (EffectLayer)255, 0x100 ); if( m_Stone is SoulstoneFragment ) { SoulstoneFragment frag = m_Stone as SoulstoneFragment; if( --frag.UsesRemaining <= 0 ) from.SendLocalizedMessage( 1070974 ); // You have used up your soulstone fragment. } } } private class ConfirmRemovalGump : Gump { private SoulStone m_Stone; public ConfirmRemovalGump( SoulStone stone ) : base( 50, 50 ) { m_Stone = stone; AddBackground( 0, 0, 520, 440, 0x13BE ); AddImageTiled( 10, 10, 500, 20, 0xA40 ); AddImageTiled( 10, 40, 500, 360, 0xA40 ); AddImageTiled( 10, 410, 500, 20, 0xA40 ); AddAlphaRegion( 10, 10, 500, 420 ); AddHtmlLocalized( 10, 12, 500, 20, 1070725, 0x7FFF, false, false ); // <CENTER>Confirm Soulstone Skill Removal</CENTER> /* WARNING!<BR><BR> * * You are about to permanently remove all skill points stored in this Soulstone. * You WILL NOT absorb these skill points. They will be DELETED.<BR><BR> * * Are you sure you wish to do this? If not, press the Cancel button. */ AddHtmlLocalized( 10, 42, 500, 110, 1070724, 0x7FFF, false, true ); AddButton( 10, 380, 0xFA5, 0xFA6, 1, GumpButtonType.Reply, 0 ); AddHtmlLocalized( 45, 382, 450, 20, 1052072, 0x7FFF, false, false ); // Continue AddButton( 10, 410, 0xFB1, 0xFB2, 0, GumpButtonType.Reply, 0 ); AddHtmlLocalized( 45, 412, 450, 20, 1060051, 0x7FFF, false, false ); // CANCEL } public override void OnResponse( NetState sender, RelayInfo info ) { if ( info.ButtonID == 0 || m_Stone.IsEmpty ) return; Mobile from = sender.Mobile; if ( !m_Stone.CheckUse( from ) ) return; m_Stone.SkillValue = 0.0; from.SendLocalizedMessage( 1070726 ); // You have successfully deleted the Soulstone's skill points. } } private class ErrorGump : Gump { private SoulStone m_Stone; public ErrorGump( SoulStone stone, int title, int message ) : base( 50, 50 ) { m_Stone = stone; AddBackground( 0, 0, 520, 440, 0x13BE ); AddImageTiled( 10, 10, 500, 20, 0xA40 ); AddImageTiled( 10, 40, 500, 360, 0xA40 ); AddImageTiled( 10, 410, 500, 20, 0xA40 ); AddAlphaRegion( 10, 10, 500, 420 ); AddHtmlLocalized( 10, 12, 500, 20, title, 0x7FFF, false, false ); AddHtmlLocalized( 10, 42, 500, 110, message, 0x7FFF, false, true ); AddButton( 10, 380, 0xFA5, 0xFA6, 1, GumpButtonType.Reply, 0 ); AddHtmlLocalized( 45, 382, 450, 20, 1052072, 0x7FFF, false, false ); // Continue AddButton( 10, 410, 0xFB1, 0xFB2, 0, GumpButtonType.Reply, 0 ); AddHtmlLocalized( 45, 412, 450, 20, 1060051, 0x7FFF, false, false ); // CANCEL } public override void OnResponse( NetState sender, RelayInfo info ) { if ( info.ButtonID == 0 ) return; Mobile from = sender.Mobile; if ( !m_Stone.CheckUse( from ) ) return; if ( m_Stone.IsEmpty ) from.SendGump( new SelectSkillGump( m_Stone, from ) ); else from.SendGump( new ConfirmTransferGump( m_Stone, from ) ); } } public SoulStone( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 3 ); // version //version 3 writer.Write( (string) m_LastUserName ); //version 2 writer.Write( (int)m_Level ); writer.Write( m_ActiveItemID ); writer.Write( m_InactiveItemID ); writer.Write( (string) m_Account ); writer.Write( (DateTime) m_NextUse ); //TODO: delete it in a harmless way writer.WriteEncodedInt( (int) m_Skill ); writer.Write( (double) m_SkillValue ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); switch( version ) { case 3: { m_LastUserName = reader.ReadString(); goto case 2; } case 2: { m_Level = (SecureLevel)reader.ReadInt(); goto case 1; } case 1: { m_ActiveItemID = reader.ReadInt(); m_InactiveItemID = reader.ReadInt(); goto case 0; } case 0: { m_Account = reader.ReadString(); m_NextUse = reader.ReadDateTime(); //TODO: delete it in a harmless way m_Skill = (SkillName)reader.ReadEncodedInt(); m_SkillValue = reader.ReadDouble(); break; } } if( version == 0 ) { m_ActiveItemID = 0x2A94; m_InactiveItemID = 0x2A93; } } } public class SoulstoneFragment : SoulStone, IUsesRemaining { private int m_UsesRemaining; public override int LabelNumber { get { return 1071000; } } // soulstone fragment [Constructable] public SoulstoneFragment() : this( 5, null ) { } [Constructable] public SoulstoneFragment( int usesRemaining ) : this( usesRemaining, null ) { } [Constructable] public SoulstoneFragment( string account ) : this( 5, account ) { } [Constructable] public SoulstoneFragment( int usesRemaining, string account ) : base( account, Utility.Random( 0x2AA1, 9 ) ) { m_UsesRemaining = usesRemaining; } public override void GetProperties( ObjectPropertyList list ) { base.GetProperties( list ); list.Add( 1060584, m_UsesRemaining.ToString() ); // uses remaining: ~1_val~ } [CommandProperty( AccessLevel.GameMaster )] public int UsesRemaining { get { return m_UsesRemaining; } set { m_UsesRemaining = value; InvalidateProperties(); } } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 2 ); // version writer.WriteEncodedInt( m_UsesRemaining ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); m_UsesRemaining = reader.ReadEncodedInt(); if( version <= 1 ) { if( ItemID == 0x2A93 || ItemID == 0x2A94 ) { ActiveItemID = Utility.Random( 0x2AA1, 9 ); } else { ActiveItemID = ItemID; } InactiveItemID = ActiveItemID; } if ( version == 0 && Weight == 1 ) Weight = -1; } public SoulstoneFragment( Serial serial ) : base( serial ) { } protected override bool CheckUse( Mobile from ) { bool canUse = base.CheckUse( from ); if( canUse ) { if( m_UsesRemaining <= 0 ) { from.SendLocalizedMessage( 1070975 ); // That soulstone fragment has no more uses. return false; } } return canUse; } public bool ShowUsesRemaining{ get{ return true; } set{} } } [Flipable] public class BlueSoulstone : SoulStone { [Constructable] public BlueSoulstone() : this( null ) { } [Constructable] public BlueSoulstone( string account ) : base( account, 0x2ADC, 0x2ADD ) { } public BlueSoulstone( Serial serial ) : base( serial ) { } public void Flip() { switch( ItemID ) { case 0x2ADC: ItemID = 0x2AEC; break; case 0x2ADD: ItemID = 0x2AED; break; case 0x2AEC: ItemID = 0x2ADC; break; case 0x2AED: ItemID = 0x2ADD; break; } } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } public class RedSoulstone : SoulStone, IRewardItem { [Constructable] public RedSoulstone() : this( null ) { } [Constructable] public RedSoulstone( string account ) : base( account, 0x32F3, 0x32F4 ) { } public RedSoulstone( Serial serial ) : base( serial ) { } private bool m_IsRewardItem; [CommandProperty( AccessLevel.GameMaster )] public bool IsRewardItem { get{ return m_IsRewardItem; } set{ m_IsRewardItem = value; InvalidateProperties(); } } public override void GetProperties( ObjectPropertyList list ) { base.GetProperties( list ); if ( m_IsRewardItem ) list.Add( 1076217 ); // 1st Year Veteran Reward } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)1 ); // version writer.Write( (bool) m_IsRewardItem ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); switch ( version ) { case 1: { m_IsRewardItem = reader.ReadBool(); break; } } } } }
using UnityEngine; using System.Collections.Generic; public class GeometryBuffer { readonly List<ObjectData> Objects; public List<Vector3> Vertices; public List<Vector2> Uvs; public List<Vector3> Normals; public int UnnamedGroupIndex = 1; // naming index for unnamed group. like "Unnamed-1" ObjectData current; class ObjectData { public string Name; public List<GroupData> Groups; public List<FaceIndices> AllFaces; public int NormalCount; public ObjectData() { Groups = new List<GroupData>(); AllFaces = new List<FaceIndices>(); NormalCount = 0; } } GroupData curgr; class GroupData { public string Name; public string MaterialName; public List<FaceIndices> Faces; public GroupData() { Faces = new List<FaceIndices>(); } public bool IsEmpty { get { return Faces.Count == 0; } } } public GeometryBuffer() { Objects = new List<ObjectData>(); var d = new ObjectData(); d.Name = "default"; Objects.Add(d); current = d; var g = new GroupData(); g.Name = "default"; d.Groups.Add(g); curgr = g; Vertices = new List<Vector3>(); Uvs = new List<Vector2>(); Normals = new List<Vector3>(); } public void PushObject(string name) { Debug.Log("Adding new object " + name + ". Current is empty: " + IsEmpty); if (IsEmpty) Objects.Remove(current); // Object Data var n = new ObjectData(); n.Name = name; Objects.Add(n); // Group Data var g = new GroupData(); g.Name = "default"; n.Groups.Add(g); curgr = g; current = n; } public void PushGroup(string name) { if (curgr.IsEmpty) current.Groups.Remove(curgr); var g = new GroupData(); if (name == null) { name = "Unnamed-" + UnnamedGroupIndex; UnnamedGroupIndex++; } g.Name = name; current.Groups.Add(g); curgr = g; } public void PushMaterialName(string name) { // Debug.Log("Pushing new material " + name + " with curgr.empty =" + curgr.IsEmpty); if (!curgr.IsEmpty) PushGroup(name); if (curgr.Name == "default") curgr.Name = name; curgr.MaterialName = name; } public void PushVertex(Vector3 v) { Vertices.Add(v); } public void PushUV(Vector2 v) { Uvs.Add(v); } public void PushNormal(Vector3 v) { Normals.Add(v); } public void PushFace(FaceIndices f) { curgr.Faces.Add(f); current.AllFaces.Add(f); if (f.Vn >= 0) { current.NormalCount++; } } public void Trace() { Debug.Log("OBJ has " + Objects.Count + " object(s)"); Debug.Log("OBJ has " + Vertices.Count + " vertice(s)"); Debug.Log("OBJ has " + Uvs.Count + " uv(s)"); Debug.Log("OBJ has " + Normals.Count + " normal(s)"); foreach(ObjectData od in Objects) { Debug.Log(od.Name + " has " + od.Groups.Count + " group(s)"); foreach(GroupData gd in od.Groups) { Debug.Log(od.Name + "/" + gd.Name + " has " + gd.Faces.Count + " faces(s)"); } } } public int NumberOfObjects { get { return Objects.Count; } } public bool IsEmpty { get { return Vertices.Count == 0; } } public bool HasUVs { get { return Uvs.Count > 0; } } public bool HasNormals { get { return Normals.Count > 0; } } // Max Vertices Limit for a given Mesh. public static int MaxVerticesLimit = 64999; public void PopulateMeshes(GameObject[] gs, Dictionary<string, Material> mats) { // Check is valid file. if (gs.Length != NumberOfObjects) { Debug.LogError ("Failed - OBJ File may be corrupt"); return; } // Debug.Log("PopulateMeshes GameObjects count:" + gs.Length); for (int i = 0; i < gs.Length; i++) { ObjectData od = Objects[i]; bool objectHasNormals = (HasNormals && od.NormalCount > 0); if (od.Name != "default") gs[i].name = od.Name; // Debug.Log("PopulateMeshes object name: " + od.Name); var tvertices = new Vector3[od.AllFaces.Count]; var tuvs = new Vector2[od.AllFaces.Count]; var tnormals = new Vector3[od.AllFaces.Count]; int k = 0; foreach(FaceIndices fi in od.AllFaces) { if (k >= MaxVerticesLimit) { Debug.LogWarning("Maximum vertex number for a mesh exceeded for object: " + gs[i].name); break; } tvertices[k] = Vertices[fi.Vi]; if(HasUVs) tuvs[k] = Uvs[fi.Vu]; if(HasNormals && fi.Vn >= 0) tnormals[k] = Normals[fi.Vn]; k++; } Mesh m = (gs[i].GetComponent(typeof(MeshFilter)) as MeshFilter).mesh; m.vertices = tvertices; if(HasUVs) m.uv = tuvs; if(objectHasNormals) m.normals = tnormals; if(od.Groups.Count == 1) { // Debug.Log("PopulateMeshes only one group: " + od.Groups[0].Name); GroupData gd = od.Groups[0]; string matName = gd.MaterialName ?? "default"; if (mats.ContainsKey(matName)) { gs[i].GetComponent<Renderer>().material = mats[matName]; // Debug.Log("PopulateMeshes mat: " + matName + " set."); } else { Debug.LogWarning("PopulateMeshes mat: " + matName + " not found."); } var triangles = new int[gd.Faces.Count]; for(int j = 0; j < triangles.Length; j++) triangles[j] = j; m.triangles = triangles; } else { int gl = od.Groups.Count; var materials = new Material[gl]; m.subMeshCount = gl; int c = 0; Debug.Log("PopulateMeshes group count: " + gl); for(int j = 0; j < gl; j++) { string matName = od.Groups [j].MaterialName ?? "default"; if (mats.ContainsKey(matName)) { materials[j] = mats[matName]; Debug.Log("PopulateMeshes mat: " + matName + " set."); } else { Debug.LogWarning("PopulateMeshes mat: " + matName + " not found."); } var triangles = new int[od.Groups[j].Faces.Count]; int l = od.Groups[j].Faces.Count + c; int s = 0; for(; c < l; c++, s++) triangles[s] = c; m.SetTriangles(triangles, j); } gs[i].GetComponent<Renderer>().materials = materials; } if (!objectHasNormals) { m.RecalculateNormals(); } } } }
using System; using Csla; using SelfLoadSoftDelete.DataAccess; using SelfLoadSoftDelete.DataAccess.ERCLevel; namespace SelfLoadSoftDelete.Business.ERCLevel { /// <summary> /// H09_Region_ReChild (editable child object).<br/> /// This is a generated base class of <see cref="H09_Region_ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="H08_Region"/> collection. /// </remarks> [Serializable] public partial class H09_Region_ReChild : BusinessBase<H09_Region_ReChild> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Region_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Region_Child_NameProperty = RegisterProperty<string>(p => p.Region_Child_Name, "Cities Child Name"); /// <summary> /// Gets or sets the Cities Child Name. /// </summary> /// <value>The Cities Child Name.</value> public string Region_Child_Name { get { return GetProperty(Region_Child_NameProperty); } set { SetProperty(Region_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="H09_Region_ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="H09_Region_ReChild"/> object.</returns> internal static H09_Region_ReChild NewH09_Region_ReChild() { return DataPortal.CreateChild<H09_Region_ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="H09_Region_ReChild"/> object, based on given parameters. /// </summary> /// <param name="region_ID2">The Region_ID2 parameter of the H09_Region_ReChild to fetch.</param> /// <returns>A reference to the fetched <see cref="H09_Region_ReChild"/> object.</returns> internal static H09_Region_ReChild GetH09_Region_ReChild(int region_ID2) { return DataPortal.FetchChild<H09_Region_ReChild>(region_ID2); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="H09_Region_ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public H09_Region_ReChild() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="H09_Region_ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="H09_Region_ReChild"/> object from the database, based on given criteria. /// </summary> /// <param name="region_ID2">The Region ID2.</param> protected void Child_Fetch(int region_ID2) { var args = new DataPortalHookArgs(region_ID2); OnFetchPre(args); using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var dal = dalManager.GetProvider<IH09_Region_ReChildDal>(); var data = dal.Fetch(region_ID2); Fetch(data); } OnFetchPost(args); // check all object rules and property rules BusinessRules.CheckRules(); } /// <summary> /// Loads a <see cref="H09_Region_ReChild"/> object from the given <see cref="H09_Region_ReChildDto"/>. /// </summary> /// <param name="data">The H09_Region_ReChildDto to use.</param> private void Fetch(H09_Region_ReChildDto data) { // Value properties LoadProperty(Region_Child_NameProperty, data.Region_Child_Name); var args = new DataPortalHookArgs(data); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="H09_Region_ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(H08_Region parent) { var dto = new H09_Region_ReChildDto(); dto.Parent_Region_ID = parent.Region_ID; dto.Region_Child_Name = Region_Child_Name; using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(dto); OnInsertPre(args); var dal = dalManager.GetProvider<IH09_Region_ReChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Insert(dto); args = new DataPortalHookArgs(resultDto); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="H09_Region_ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(H08_Region parent) { if (!IsDirty) return; var dto = new H09_Region_ReChildDto(); dto.Parent_Region_ID = parent.Region_ID; dto.Region_Child_Name = Region_Child_Name; using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(dto); OnUpdatePre(args); var dal = dalManager.GetProvider<IH09_Region_ReChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Update(dto); args = new DataPortalHookArgs(resultDto); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="H09_Region_ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(H08_Region parent) { using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<IH09_Region_ReChildDal>(); using (BypassPropertyChecks) { dal.Delete(parent.Region_ID); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <peter@majorsilence.com> This file is part of the fyiReporting RDL project. 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. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.ComponentModel; // need this for the properties metadata using System.Drawing.Design; using System.Globalization; using System.Windows.Forms; using System.Windows.Forms.Design; namespace fyiReporting.RdlDesign { /// <summary> /// PropertyAction - /// </summary> [TypeConverter(typeof(PropertyAppearanceConverter))] [Editor(typeof(PropertyAppearanceUIEditor), typeof(UITypeEditor))] internal class PropertyAppearance : IReportItem { PropertyReportItem pri; string[] _subitems; string[] _names; internal PropertyAppearance(PropertyReportItem ri) { pri = ri; _names = null; _subitems = new string[] { "Style", "" }; } internal PropertyAppearance(PropertyReportItem ri, params string[] names) { pri = ri; _names = names; // now build the array used to get/set values if (names != null) { _subitems = new string[names.Length + 2]; int i = 0; foreach (string s in names) _subitems[i++] = s; _subitems[i++] = "Style"; } else _subitems = new string[] { "Style", "" }; } internal string[] Names { get { return _names; } } [RefreshProperties(RefreshProperties.Repaint)] [LocalizedDisplayName("Appearance_FontFamily")] [LocalizedDescription("Appearance_FontFamily")] public PropertyExpr FontFamily { get { return new PropertyExpr(GetStyleValue("FontFamily", "Arial")); } set { SetStyleValue("FontFamily", value.Expression); } } [RefreshProperties(RefreshProperties.Repaint)] [LocalizedDisplayName("Appearance_FontSize")] [LocalizedDescription("Appearance_FontSize")] public PropertyExpr FontSize { get { return new PropertyExpr(GetStyleValue("FontSize", "10pt")); } set { if (!pri.IsExpression(value.Expression)) DesignerUtility.ValidateSize(value.Expression, true, false); SetStyleValue("FontSize", value.Expression); } } [TypeConverter(typeof(FontStyleConverter))] [LocalizedDisplayName("Appearance_FontStyle")] [LocalizedDescription("Appearance_FontStyle")] public string FontStyle { get { return GetStyleValue("FontStyle", "Normal"); } set { SetStyleValue("FontStyle", value); } } [TypeConverter(typeof(FontWeightConverter))] [LocalizedDisplayName("Appearance_FontWeight")] [LocalizedDescription("Appearance_FontWeight")] public string FontWeight { get { return GetStyleValue("FontWeight", "Normal"); } set { SetStyleValue("FontWeight", value); } } [TypeConverter(typeof(ColorConverter))] [LocalizedDisplayName("Appearance_Color")] [LocalizedDescription("Appearance_Color")] public string Color { get { return GetStyleValue("Color", "black"); } set { SetStyleValue("Color", value); } } [TypeConverter(typeof(TextDecorationConverter))] [LocalizedDisplayName("Appearance_TextDecoration")] [LocalizedDescription("Appearance_TextDecoration")] public string TextDecoration { get { return GetStyleValue("TextDecoration", "None"); } set { SetStyleValue("TextDecoration", value); } } [TypeConverter(typeof(TextAlignConverter))] [LocalizedDisplayName("Appearance_TextAlign")] [LocalizedDescription("Appearance_TextAlign")] public string TextAlign { get { return GetStyleValue("TextAlign", "General"); } set { SetStyleValue("TextAlign", value); } } [TypeConverter(typeof(VerticalAlignConverter))] [LocalizedDisplayName("Appearance_VerticalAlign")] [LocalizedDescription("Appearance_VerticalAlign")] public string VerticalAlign { get { return GetStyleValue("VerticalAlign", "Top"); } set { SetStyleValue("VerticalAlign", value); } } [TypeConverter(typeof(DirectionConverter))] [LocalizedDisplayName("Appearance_Direction")] [LocalizedDescription("Appearance_Direction")] public string Direction { get { return GetStyleValue("Direction", "LTR"); } set { SetStyleValue("Direction", value); } } [TypeConverter(typeof(WritingModeConverter))] [LocalizedDisplayName("Appearance_WritingMode")] [LocalizedDescription("Appearance_WritingMode")] public string WritingMode { get { return GetStyleValue("WritingMode", "lr-tb"); } set { SetStyleValue("WritingMode", value); } } [TypeConverter(typeof(FormatConverter))] [LocalizedDisplayName("Appearance_Format")] [LocalizedDescription("Appearance_Format")] public string Format { get { return GetStyleValue("Format", ""); } set { SetStyleValue("Format", value); } } public override string ToString() { string f = GetStyleValue("FontFamily", "Arial"); string s = GetStyleValue("FontSize", "10pt"); string c = GetStyleValue("Color", "Black"); return string.Format("{0}, {1}, {2}", f,s,c); } private string GetStyleValue(string l1, string def) { _subitems[_subitems.Length - 1] = l1; return pri.GetWithList(def, _subitems); } private void SetStyleValue(string l1, string val) { _subitems[_subitems.Length - 1] = l1; pri.SetWithList(val, _subitems); } #region IReportItem Members public PropertyReportItem GetPRI() { return pri; } #endregion } internal class PropertyAppearanceConverter : ExpandableObjectConverter { public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(PropertyAppearance)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string) && value is PropertyAppearance) { PropertyAppearance pf = value as PropertyAppearance; return pf.ToString(); } return base.ConvertTo(context, culture, value, destinationType); } } internal class PropertyAppearanceUIEditor : UITypeEditor { internal PropertyAppearanceUIEditor() { } public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { if ((context == null) || (provider == null)) return base.EditValue(context, provider, value); // Access the Property Browser's UI display service IWindowsFormsEditorService editorService = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (editorService == null) return base.EditValue(context, provider, value); // Create an instance of the UI editor form IReportItem iri = context.Instance as IReportItem; if (iri == null) return base.EditValue(context, provider, value); PropertyReportItem pre = iri.GetPRI(); PropertyAppearance pf = value as PropertyAppearance; if (pf == null) return base.EditValue(context, provider, value); using (SingleCtlDialog scd = new SingleCtlDialog(pre.DesignCtl, pre.Draw, pre.Nodes, SingleCtlTypeEnum.FontCtl, pf.Names)) { // Display the UI editor dialog if (editorService.ShowDialog(scd) == DialogResult.OK) { // Return the new property value from the UI editor form return new PropertyAppearance(pre, pf.Names); } } return base.EditValue(context, provider, value); } } #region FontStyle internal class FontStyleConverter : StringConverter { static readonly string[] StyleList = new string[] {"Normal","Italic"}; public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; // allow user to also edit the color directly } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(StyleList); } } #endregion #region FontWeight internal class FontWeightConverter : StringConverter { static readonly string[] WeightList = new string[] { "Lighter", "Normal","Bold", "Bolder", "100", "200", "300", "400", "500", "600", "700", "800", "900"}; public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; // allow user to also edit the color directly } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(WeightList); } } #endregion #region TextDecoration internal class TextDecorationConverter : StringConverter { static readonly string[] TDList = new string[] { "Underline", "Overline", "LineThrough", "None"}; public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; // allow user to also edit directly } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(TDList); } } #endregion #region TextAlign internal class TextAlignConverter : StringConverter { static readonly string[] TAList = new string[] { "Left", "Center", "Right", "General" }; public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; // allow user to also edit directly } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(TAList); } } #endregion #region VerticalAlign internal class VerticalAlignConverter : StringConverter { static readonly string[] VAList = new string[] { "Top", "Middle", "Bottom" }; public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; // allow user to also edit directly } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(VAList); } } #endregion #region Direction internal class DirectionConverter : StringConverter { static readonly string[] DirList = new string[] { "LTR", "RTL" }; public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; // allow user to also edit directly } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(DirList); } } #endregion #region WritingMode internal class WritingModeConverter : StringConverter { static readonly string[] WMList = new string[] { "lr-tb", "tb-rl", "tb-lr" }; public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; // allow user to also edit directly } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(WMList); } } #endregion #region Format internal class FormatConverter : StringConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; // allow user to also edit directly } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(StaticLists.FormatList); } } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests { public class CastTests : EnumerableTests { [Fact] public void CastIntToLongThrows() { var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 } where x > int.MinValue select x; var rst = q.Cast<long>(); Assert.Throws<InvalidCastException>(() => { foreach (var t in rst) ; }); } [Fact] public void CastByteToUShortThrows() { var q = from x in new byte[] { 0, 255, 127, 128, 1, 33, 99 } select x; var rst = q.Cast<ushort>(); Assert.Throws<InvalidCastException>(() => { foreach (var t in rst) ; }); } [Fact] public void EmptySource() { object[] source = { }; Assert.Empty(source.Cast<int>()); } [Fact] public void NullableIntFromAppropriateObjects() { int? i = 10; object[] source = { -4, 1, 2, 3, 9, i }; int?[] expected = { -4, 1, 2, 3, 9, i }; Assert.Equal(expected, source.Cast<int?>()); } [Fact] public void NullableIntFromAppropriateObjectsRunOnce() { int? i = 10; object[] source = { -4, 1, 2, 3, 9, i }; int?[] expected = { -4, 1, 2, 3, 9, i }; Assert.Equal(expected, source.RunOnce().Cast<int?>()); } [Fact] public void LongFromNullableIntInObjectsThrows() { int? i = 10; object[] source = { -4, 1, 2, 3, 9, i }; IEnumerable<long> cast = source.Cast<long>(); Assert.Throws<InvalidCastException>(() => cast.ToList()); } [Fact] public void LongFromNullableIntInObjectsIncludingNullThrows() { int? i = 10; object[] source = { -4, 1, 2, 3, 9, null, i }; IEnumerable<long?> cast = source.Cast<long?>(); Assert.Throws<InvalidCastException>(() => cast.ToList()); } [Fact] public void NullableIntFromAppropriateObjectsIncludingNull() { int? i = 10; object[] source = { -4, 1, 2, 3, 9, null, i }; int?[] expected = { -4, 1, 2, 3, 9, null, i }; Assert.Equal(expected, source.Cast<int?>()); } [Fact] public void ThrowOnUncastableItem() { object[] source = { -4, 1, 2, 3, 9, "45" }; int[] expectedBeginning = { -4, 1, 2, 3, 9 }; IEnumerable<int> cast = source.Cast<int>(); Assert.Throws<InvalidCastException>(() => cast.ToList()); Assert.Equal(expectedBeginning, cast.Take(5)); Assert.Throws<InvalidCastException>(() => cast.ElementAt(5)); } [Fact] public void ThrowCastingIntToDouble() { int[] source = new int[] { -4, 1, 2, 9 }; IEnumerable<double> cast = source.Cast<double>(); Assert.Throws<InvalidCastException>(() => cast.ToList()); } private static void TestCastThrow<T>(object o) { byte? i = 10; object[] source = { -1, 0, o, i }; IEnumerable<T> cast = source.Cast<T>(); Assert.Throws<InvalidCastException>(() => cast.ToList()); } [Fact] public void ThrowOnHeterogenousSource() { TestCastThrow<long?>(null); TestCastThrow<long>(9L); } [Fact] public void CastToString() { object[] source = { "Test1", "4.5", null, "Test2" }; string[] expected = { "Test1", "4.5", null, "Test2" }; Assert.Equal(expected, source.Cast<string>()); } [Fact] public void CastToStringRunOnce() { object[] source = { "Test1", "4.5", null, "Test2" }; string[] expected = { "Test1", "4.5", null, "Test2" }; Assert.Equal(expected, source.RunOnce().Cast<string>()); } [Fact] public void ArrayConversionThrows() { Assert.Throws<InvalidCastException>(() => new[] { -4 }.Cast<long>().ToList()); } [Fact] public void FirstElementInvalidForCast() { object[] source = { "Test", 3, 5, 10 }; IEnumerable<int> cast = source.Cast<int>(); Assert.Throws<InvalidCastException>(() => cast.ToList()); } [Fact] public void LastElementInvalidForCast() { object[] source = { -5, 9, 0, 5, 9, "Test" }; IEnumerable<int> cast = source.Cast<int>(); Assert.Throws<InvalidCastException>(() => cast.ToList()); } [Fact] public void NullableIntFromNullsAndInts() { object[] source = { 3, null, 5, -4, 0, null, 9 }; int?[] expected = { 3, null, 5, -4, 0, null, 9 }; Assert.Equal(expected, source.Cast<int?>()); } [Fact] public void ThrowCastingIntToLong() { int[] source = new int[] { -4, 1, 2, 3, 9 }; IEnumerable<long> cast = source.Cast<long>(); Assert.Throws<InvalidCastException>(() => cast.ToList()); } [Fact] public void ThrowCastingIntToNullableLong() { int[] source = new int[] { -4, 1, 2, 3, 9 }; IEnumerable<long?> cast = source.Cast<long?>(); Assert.Throws<InvalidCastException>(() => cast.ToList()); } [Fact] public void ThrowCastingNullableIntToLong() { int?[] source = new int?[] { -4, 1, 2, 3, 9 }; IEnumerable<long> cast = source.Cast<long>(); Assert.Throws<InvalidCastException>(() => cast.ToList()); } [Fact] public void ThrowCastingNullableIntToNullableLong() { int?[] source = new int?[] { -4, 1, 2, 3, 9, null }; IEnumerable<long?> cast = source.Cast<long?>(); Assert.Throws<InvalidCastException>(() => cast.ToList()); } [Fact] public void CastingNullToNonnullableIsNullReferenceException() { int?[] source = new int?[] { -4, 1, null, 3 }; IEnumerable<int> cast = source.Cast<int>(); Assert.Throws<NullReferenceException>(() => cast.ToList()); } [Fact] public void NullSource() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<object>)null).Cast<string>()); } [Fact] public void ForcedToEnumeratorDoesntEnumerate() { var iterator = new object[0].Where(i => i != null).Cast<string>(); // Don't insist on this behaviour, but check it's correct if it happens var en = iterator as IEnumerator<string>; Assert.False(en != null && en.MoveNext()); } } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; namespace SharpDX.XAudio2 { public partial class XAudio2 { private EngineCallbackImpl engineCallbackImpl; private IntPtr engineShadowPtr; ///// <summary>Constant None.</summary> private static Guid CLSID_XAudio27 = new Guid("5a508685-a254-4fba-9b82-9a24b00306af"); ///// <summary>Constant None.</summary> private static Guid CLSID_XAudio27_Debug = new Guid("db05ea35-0329-4d4b-a53a-6dead03d3852"); ///// <summary>Constant None.</summary> private static Guid IID_IXAudio2 = new Guid("8bcf1f58-9fe7-4583-8ac6-e2adc465c8bb"); /// <summary> /// Called by XAudio2 just before an audio processing pass begins. /// </summary> public event EventHandler ProcessingPassStart; /// <summary> /// Called by XAudio2 just after an audio processing pass ends. /// </summary> public event EventHandler ProcessingPassEnd; /// <summary> /// Called if a critical system error occurs that requires XAudio2 to be closed down and restarted. /// </summary> public event EventHandler<ErrorEventArgs> CriticalError; /// <summary> /// Initializes a new instance of the <see cref="XAudio2"/> class. /// </summary> public XAudio2() : this(XAudio2Version.Default) { } /// <summary> /// Initializes a new instance of the <see cref="XAudio2"/> class. /// </summary> public XAudio2(XAudio2Version version) : this(XAudio2Flags.None, ProcessorSpecifier.DefaultProcessor, version) { } /// <summary> /// Initializes a new instance of the <see cref="XAudio2" /> class. /// </summary> /// <param name="flags">Specify a Debug or Normal XAudio2 instance.</param> /// <param name="processorSpecifier">The processor specifier.</param> /// <param name="version">The version to use (auto, 2.7 or 2.8).</param> /// <exception cref="System.InvalidOperationException">XAudio2 version [ + version + ] is not installed</exception> public XAudio2(XAudio2Flags flags, ProcessorSpecifier processorSpecifier, XAudio2Version version = XAudio2Version.Default) : base(IntPtr.Zero) { #if DESKTOP_APP Guid clsid = ((int)flags == 1) ? CLSID_XAudio27_Debug : CLSID_XAudio27; if ((version == XAudio2Version.Default || version == XAudio2Version.Version27) && Utilities.TryCreateComInstance(clsid, Utilities.CLSCTX.ClsctxInprocServer, IID_IXAudio2, this)) { SetupVtblFor27(); // Initialize XAudio2 Initialize(0, processorSpecifier); Version = XAudio2Version.Version27; } else #endif if (version == XAudio2Version.Default || version == XAudio2Version.Version28) { XAudio2Functions.XAudio2Create(this, 0, (int)processorSpecifier); Version = XAudio2Version.Version28; } else { throw new InvalidOperationException("XAudio2 version [" + version + "] is not installed"); } // Register engine callback engineCallbackImpl = new EngineCallbackImpl(this); engineShadowPtr = EngineShadow.ToIntPtr(engineCallbackImpl); RegisterForCallbacks_(engineShadowPtr); } /// <summary> /// Gets the version of this XAudio2 instance, once a <see cref="XAudio2"/> device has been instanciated. /// </summary> /// <value>The version.</value> public static XAudio2Version Version { get; private set; } // --------------------------------------------------------------------------------- // Start handling 2.7 version here // --------------------------------------------------------------------------------- /// <summary> /// Setups the VTBL for XAudio 2.7. The 2.7 verions had 3 methods starting at VTBL[3]: /// - GetDeviceCount /// - GetDeviceDetails /// - Initialize /// </summary> private void SetupVtblFor27() { RegisterForCallbacks___vtbl_index += 3; UnregisterForCallbacks___vtbl_index += 3; CreateSourceVoice___vtbl_index += 3; CreateSubmixVoice__vtbl_index += 3; CreateMasteringVoice__vtbl_index += 3; StartEngine__vtbl_index += 3; StopEngine__vtbl_index += 3; CommitChanges__vtbl_index += 3; GetPerformanceData__vtbl_index += 3; SetDebugConfiguration__vtbl_index += 3; } private void CheckVersion27() { if (Version != XAudio2Version.Version27) { throw new InvalidOperationException("This method is only valid on the XAudio 2.7 version [Current is: " + Version + "]"); } } /// <summary> /// No documentation. /// </summary> /// <!-- No matching elements were found for the following include tag --><include file=".\..\Documentation\CodeComments.xml" path="/comments/comment[@id='IXAudio2::GetDeviceCount']/*" /> /// <unmanaged>GetDeviceCount</unmanaged> /// <unmanaged-short>GetDeviceCount</unmanaged-short> /// <unmanaged>HRESULT IXAudio2::GetDeviceCount([Out] unsigned int* pCount)</unmanaged> public int DeviceCount { get { CheckVersion27(); int result; this.GetDeviceCount(out result); return result; } } /// <summary> /// No documentation. /// </summary> /// <param name="countRef">No documentation.</param> /// <returns>No documentation.</returns> /// <!-- No matching elements were found for the following include tag --><include file=".\..\Documentation\CodeComments.xml" path="/comments/comment[@id='IXAudio2::GetDeviceCount']/*" /> /// <unmanaged>HRESULT IXAudio2::GetDeviceCount([Out] unsigned int* pCount)</unmanaged> /// <unmanaged-short>IXAudio2::GetDeviceCount</unmanaged-short> private unsafe void GetDeviceCount(out int countRef) { Result result; fixed (void* ptr = &countRef) { result = LocalInterop.Calliint(this._nativePointer, ptr, *(*(void***)this._nativePointer + 3)); } result.CheckError(); } internal unsafe void CreateMasteringVoice27(MasteringVoice masteringVoiceOut, int inputChannels, int inputSampleRate, int flags, int deviceIndex, EffectChain? effectChainRef) { IntPtr zero = IntPtr.Zero; EffectChain value; if (effectChainRef.HasValue) { value = effectChainRef.Value; } Result result = LocalInterop.Calliint(this._nativePointer, (void*)&zero, inputChannels, inputSampleRate, flags, deviceIndex, effectChainRef.HasValue ? ((void*)(&value)) : ((void*)IntPtr.Zero), *(*(void***)this._nativePointer + 10)); masteringVoiceOut.NativePointer = zero; result.CheckError(); } /// <summary> /// Returns information about an audio output device. /// </summary> /// <param name="index">[in] Index of the device to be queried. This value must be less than the count returned by <see cref="SharpDX.XAudio2.XAudio2.GetDeviceCount"/>. </param> /// <returns>On success, pointer to an <see cref="SharpDX.XAudio2.DeviceDetails"/> structure that is returned. </returns> /// <unmanaged>HRESULT IXAudio2::GetDeviceDetails([None] UINT32 Index,[Out] XAUDIO2_DEVICE_DETAILS* pDeviceDetails)</unmanaged> public SharpDX.XAudio2.DeviceDetails GetDeviceDetails(int index) { CheckVersion27(); DeviceDetails details; GetDeviceDetails(index, out details); return details; } private unsafe void GetDeviceDetails(int index, out DeviceDetails deviceDetailsRef) { DeviceDetails.__Native _Native = default(DeviceDetails.__Native); Result result = LocalInterop.Calliint(this._nativePointer, index, &_Native, *(*(void***)this._nativePointer + 4)); deviceDetailsRef = default(DeviceDetails); deviceDetailsRef.__MarshalFrom(ref _Native); result.CheckError(); } private unsafe void Initialize(int flags, ProcessorSpecifier xAudio2Processor) { var result = (Result)LocalInterop.Calliint(this._nativePointer, (int)flags, (int)xAudio2Processor, *(*(void***)this._nativePointer + 5)); result.CheckError(); } // --------------------------------------------------------------------------------- // End handling 2.7 version here // --------------------------------------------------------------------------------- /// <summary> /// Calculate a decibel from a volume. /// </summary> /// <param name="volume">The volume.</param> /// <returns>a dB value</returns> public static float AmplitudeRatioToDecibels(float volume) { if (volume == 0f) return float.MinValue; return (float)(Math.Log10(volume) * 20); } /// <summary> /// Calculate radians from a cutoffs frequency. /// </summary> /// <param name="cutoffFrequency">The cutoff frequency.</param> /// <param name="sampleRate">The sample rate.</param> /// <returns>radian</returns> public static float CutoffFrequencyToRadians(float cutoffFrequency, int sampleRate) { if (((int)cutoffFrequency * 6.0) >= sampleRate) return 1f; return (float)(Math.Sin(cutoffFrequency*Math.PI/sampleRate)*2); } /// <summary> /// Calculate a cutoff frequency from a radian. /// </summary> /// <param name="radians">The radians.</param> /// <param name="sampleRate">The sample rate.</param> /// <returns>cutoff frequency</returns> public static float RadiansToCutoffFrequency(float radians, float sampleRate) { return (float)((Math.Asin(radians * 0.5) * sampleRate) / Math.PI); } /// <summary> /// Calculate a volume from a decibel /// </summary> /// <param name="decibels">a dB value</param> /// <returns>an amplitude value</returns> public static float DecibelsToAmplitudeRatio(float decibels) { return (float)Math.Pow(10, decibels / 20); } /// <summary> /// Calculate semitones from a Frequency ratio /// </summary> /// <param name="frequencyRatio">The frequency ratio.</param> /// <returns>semitones</returns> public static float FrequencyRatioToSemitones(float frequencyRatio) { return (float)(Math.Log10(frequencyRatio) * 12 * Math.PI); } /// <summary> /// Calculate frequency from semitones. /// </summary> /// <param name="semitones">The semitones.</param> /// <returns>the frequency</returns> public static float SemitonesToFrequencyRatio(float semitones) { return (float)Math.Pow(2, semitones / 12); } /// <summary> /// Atomically applies a set of operations for all pending operations. /// </summary> /// <unmanaged>HRESULT IXAudio2::CommitChanges([None] UINT32 OperationSet)</unmanaged> public void CommitChanges() { this.CommitChanges(0); } protected override void Dispose(bool disposing) { if (engineShadowPtr != IntPtr.Zero) UnregisterForCallbacks_(engineShadowPtr); if (disposing) { if (engineCallbackImpl != null) engineCallbackImpl.Dispose(); } base.Dispose(disposing); } private class EngineCallbackImpl : CallbackBase, EngineCallback { XAudio2 XAudio2 { get; set; } public EngineCallbackImpl(XAudio2 xAudio2) { XAudio2 = xAudio2; } public void OnProcessingPassStart() { EventHandler handler = XAudio2.ProcessingPassStart; if (handler != null) handler(this, EventArgs.Empty); } public void OnProcessingPassEnd() { EventHandler handler = XAudio2.ProcessingPassEnd; if (handler != null) handler(this, EventArgs.Empty); } public void OnCriticalError(Result error) { EventHandler<ErrorEventArgs> handler = XAudio2.CriticalError; if (handler != null) handler(this, new ErrorEventArgs(error)); } IDisposable ICallbackable.Shadow { get; set; } } } }
using Microsoft.Extensions.DependencyInjection; using Orleans; using Orleans.Configuration; using Orleans.Providers; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Storage; using Orleans.TestingHost; using System; using System.Collections.Generic; using System.Threading.Tasks; using TesterInternal; using UnitTests.GrainInterfaces; using Xunit; using Xunit.Abstractions; using static Orleans.Storage.DynamoDBGrainStorage; using Orleans.Hosting; namespace AWSUtils.Tests.StorageTests { [TestCategory("Persistence"), TestCategory("AWS"), TestCategory("DynamoDb")] public class PersistenceGrainTests_AWSDynamoDBStore : Base_PersistenceGrainTests_AWSStore, IClassFixture<PersistenceGrainTests_AWSDynamoDBStore.Fixture> { private static readonly string DataConnectionString = $"Service={AWSTestConstants.Service}"; public class Fixture : TestExtensions.BaseTestClusterFixture { protected override void ConfigureTestCluster(TestClusterBuilder builder) { if (AWSTestConstants.IsDynamoDbAvailable) { Guid serviceId = Guid.NewGuid(); string dataConnectionString = DataConnectionString; builder.Options.InitialSilosCount = 4; builder.ConfigureLegacyConfiguration(legacy => { legacy.ClusterConfiguration.Globals.ServiceId = serviceId; legacy.ClusterConfiguration.Globals.DataConnectionString = dataConnectionString; legacy.ClusterConfiguration.Globals.MaxResendCount = 0; legacy.ClusterConfiguration.Globals.RegisterStorageProvider<UnitTests.StorageTests.MockStorageProvider>("test1"); legacy.ClusterConfiguration.Globals.RegisterStorageProvider<UnitTests.StorageTests.MockStorageProvider>("test2", new Dictionary<string, string> { { "Config1", "1" }, { "Config2", "2" } }); legacy.ClusterConfiguration.Globals.RegisterStorageProvider<UnitTests.StorageTests.ErrorInjectionStorageProvider>("ErrorInjector"); legacy.ClusterConfiguration.Globals.RegisterStorageProvider<UnitTests.StorageTests.MockStorageProvider>("lowercase"); // FIXME: How to configure the TestClusterBuilder to use the new extensions? //legacy.ClusterConfiguration.Globals.RegisterStorageProvider<DynamoDBGrainStorage>("DDBStore", // new Dictionary<string, string> {{"DeleteStateOnClear", "true"}, {"DataConnectionString", dataConnectionString}}); //legacy.ClusterConfiguration.Globals.RegisterStorageProvider<DynamoDBGrainStorage>("DDBStore1", // new Dictionary<string, string> {{"DataConnectionString", dataConnectionString}}); //legacy.ClusterConfiguration.Globals.RegisterStorageProvider<DynamoDBGrainStorage>("DDBStore2", // new Dictionary<string, string> {{"DataConnectionString", dataConnectionString}}); //legacy.ClusterConfiguration.Globals.RegisterStorageProvider<DynamoDBGrainStorage>("DDBStore3", // new Dictionary<string, string> {{"DataConnectionString", dataConnectionString}}); }); builder.AddSiloBuilderConfigurator<SiloBuilderConfigurator>(); } } public class SiloBuilderConfigurator : ISiloBuilderConfigurator { public void Configure(ISiloHostBuilder hostBuilder) { hostBuilder.AddMemoryGrainStorage("MemoryStore"); } } } public PersistenceGrainTests_AWSDynamoDBStore(ITestOutputHelper output, Fixture fixture) : base(output, fixture) { if (!AWSTestConstants.IsDynamoDbAvailable) { output.WriteLine("Unable to connect to AWS DynamoDB simulator"); throw new SkipException("Unable to connect to AWS DynamoDB simulator"); } } [SkippableFact, TestCategory("Functional")] public async Task Grain_AWSDynamoDBStore_Delete() { await base.Grain_AWSStore_Delete(); } [SkippableFact, TestCategory("Functional")] public async Task Grain_AWSDynamoDBStore_Read() { await base.Grain_AWSStore_Read(); } [SkippableFact, TestCategory("Functional")] public async Task Grain_GuidKey_AWSDynamoDBStore_Read_Write() { await base.Grain_GuidKey_AWSStore_Read_Write(); } [SkippableFact, TestCategory("Functional")] public async Task Grain_LongKey_AWSDynamoDBStore_Read_Write() { await base.Grain_LongKey_AWSStore_Read_Write(); } [SkippableFact, TestCategory("Functional")] public async Task Grain_LongKeyExtended_AWSDynamoDBStore_Read_Write() { await base.Grain_LongKeyExtended_AWSStore_Read_Write(); } [SkippableFact, TestCategory("Functional")] public async Task Grain_GuidKeyExtended_AWSDynamoDBStore_Read_Write() { await base.Grain_GuidKeyExtended_AWSStore_Read_Write(); } [SkippableFact, TestCategory("Functional")] public async Task Grain_Generic_AWSDynamoDBStore_Read_Write() { await base.Grain_Generic_AWSStore_Read_Write(); } [SkippableFact, TestCategory("Functional")] public async Task Grain_Generic_AWSDynamoDBStore_DiffTypes() { await base.Grain_Generic_AWSStore_DiffTypes(); } [SkippableFact, TestCategory("Functional")] public async Task Grain_AWSDynamoDBStore_SiloRestart() { await base.Grain_AWSStore_SiloRestart(); } [SkippableFact, TestCategory("CorePerf"), TestCategory("Performance"), TestCategory("Stress")] public void Persistence_Perf_Activate_AWSDynamoDBStore() { base.Persistence_Perf_Activate(); } [SkippableFact, TestCategory("CorePerf"), TestCategory("Performance"), TestCategory("Stress")] public void Persistence_Perf_Write_AWSDynamoDBStore() { base.Persistence_Perf_Write(); } [SkippableFact, TestCategory("CorePerf"), TestCategory("Performance"), TestCategory("Stress")] public void Persistence_Perf_Write_Reread_AWSDynamoDBStore() { base.Persistence_Perf_Write_Reread(); } [SkippableFact, TestCategory("Functional")] public Task Persistence_Silo_StorageProvider_AWSDynamoDBStore() { return base.Persistence_Silo_StorageProvider_AWS(typeof(DynamoDBGrainStorage)); } [SkippableFact, TestCategory("Functional")] public async Task AWSDynamoDBStore_ConvertToFromStorageFormat_GrainReference() { // NOTE: This test requires Silo to be running & Client init so that grain references can be resolved before serialization. Guid id = Guid.NewGuid(); IUser grain = this.HostedCluster.GrainFactory.GetGrain<IUser>(id); var initialState = new GrainStateContainingGrainReferences { Grain = grain }; var entity = new GrainStateRecord(); var storage = await InitDynamoDBTableStorageProvider( this.HostedCluster.ServiceProvider.GetRequiredService<IProviderRuntime>(), "TestTable"); storage.ConvertToStorageFormat(initialState, entity); var convertedState = new GrainStateContainingGrainReferences(); convertedState = (GrainStateContainingGrainReferences)storage.ConvertFromStorageFormat(entity); Assert.NotNull(convertedState); // Converted state Assert.Equal(initialState.Grain, convertedState.Grain); // "Grain" } [SkippableFact, TestCategory("Functional")] public async Task AWSDynamoDBStore_ConvertToFromStorageFormat_GrainReference_List() { // NOTE: This test requires Silo to be running & Client init so that grain references can be resolved before serialization. Guid[] ids = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; IUser[] grains = new IUser[3]; grains[0] = this.HostedCluster.GrainFactory.GetGrain<IUser>(ids[0]); grains[1] = this.HostedCluster.GrainFactory.GetGrain<IUser>(ids[1]); grains[2] = this.HostedCluster.GrainFactory.GetGrain<IUser>(ids[2]); var initialState = new GrainStateContainingGrainReferences(); foreach (var g in grains) { initialState.GrainList.Add(g); initialState.GrainDict.Add(g.GetPrimaryKey().ToString(), g); } var entity = new GrainStateRecord(); var storage = await InitDynamoDBTableStorageProvider( this.HostedCluster.ServiceProvider.GetRequiredService<IProviderRuntime>(), "TestTable"); storage.ConvertToStorageFormat(initialState, entity); var convertedState = (GrainStateContainingGrainReferences)storage.ConvertFromStorageFormat(entity); Assert.NotNull(convertedState); Assert.Equal(initialState.GrainList.Count, convertedState.GrainList.Count); // "GrainList size" Assert.Equal(initialState.GrainDict.Count, convertedState.GrainDict.Count); // "GrainDict size" for (int i = 0; i < grains.Length; i++) { string iStr = ids[i].ToString(); Assert.Equal(initialState.GrainList[i], convertedState.GrainList[i]); // "GrainList #{0}", i Assert.Equal(initialState.GrainDict[iStr], convertedState.GrainDict[iStr]); // "GrainDict #{0}", i } Assert.Equal(initialState.Grain, convertedState.Grain); // "Grain" } private async Task<DynamoDBGrainStorage> InitDynamoDBTableStorageProvider(IProviderRuntime runtime, string storageName) { var options = new DynamoDBStorageOptions(); options.Service = AWSTestConstants.Service; DynamoDBGrainStorage store = ActivatorUtilities.CreateInstance<DynamoDBGrainStorage>(runtime.ServiceProvider, options); SiloLifecycle lifecycle = ActivatorUtilities.CreateInstance<SiloLifecycle>(runtime.ServiceProvider); store.Participate(lifecycle); await lifecycle.OnStart(); return store; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute.Automation { [Cmdlet("Set", "AzureRmImageOsDisk", SupportsShouldProcess = true)] [OutputType(typeof(PSImage))] public partial class SetAzureRmImageOsDiskCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet { [Parameter( Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public PSImage Image { get; set; } [Parameter( Mandatory = false, Position = 1, ValueFromPipelineByPropertyName = true)] public OperatingSystemTypes? OsType { get; set; } [Parameter( Mandatory = false, Position = 2, ValueFromPipelineByPropertyName = true)] public OperatingSystemStateTypes? OsState { get; set; } [Parameter( Mandatory = false, Position = 3, ValueFromPipelineByPropertyName = true)] public string BlobUri { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public CachingTypes? Caching { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public int? DiskSizeGB { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public StorageAccountTypes? StorageAccountType { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string SnapshotId { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string ManagedDiskId { get; set; } protected override void ProcessRecord() { if (ShouldProcess("Image", "Set")) { Run(); } } private void Run() { if (this.OsType.HasValue) { // StorageProfile if (this.Image.StorageProfile == null) { this.Image.StorageProfile = new Microsoft.Azure.Management.Compute.Models.ImageStorageProfile(); } // OsDisk if (this.Image.StorageProfile.OsDisk == null) { this.Image.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.ImageOSDisk(); } this.Image.StorageProfile.OsDisk.OsType = this.OsType.Value; } if (this.OsState.HasValue) { // StorageProfile if (this.Image.StorageProfile == null) { this.Image.StorageProfile = new Microsoft.Azure.Management.Compute.Models.ImageStorageProfile(); } // OsDisk if (this.Image.StorageProfile.OsDisk == null) { this.Image.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.ImageOSDisk(); } this.Image.StorageProfile.OsDisk.OsState = this.OsState.Value; } if (this.BlobUri != null) { // StorageProfile if (this.Image.StorageProfile == null) { this.Image.StorageProfile = new Microsoft.Azure.Management.Compute.Models.ImageStorageProfile(); } // OsDisk if (this.Image.StorageProfile.OsDisk == null) { this.Image.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.ImageOSDisk(); } this.Image.StorageProfile.OsDisk.BlobUri = this.BlobUri; } if (this.Caching != null) { // StorageProfile if (this.Image.StorageProfile == null) { this.Image.StorageProfile = new Microsoft.Azure.Management.Compute.Models.ImageStorageProfile(); } // OsDisk if (this.Image.StorageProfile.OsDisk == null) { this.Image.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.ImageOSDisk(); } this.Image.StorageProfile.OsDisk.Caching = this.Caching; } if (this.DiskSizeGB != null) { // StorageProfile if (this.Image.StorageProfile == null) { this.Image.StorageProfile = new Microsoft.Azure.Management.Compute.Models.ImageStorageProfile(); } // OsDisk if (this.Image.StorageProfile.OsDisk == null) { this.Image.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.ImageOSDisk(); } this.Image.StorageProfile.OsDisk.DiskSizeGB = this.DiskSizeGB; } if (this.StorageAccountType != null) { // StorageProfile if (this.Image.StorageProfile == null) { this.Image.StorageProfile = new Microsoft.Azure.Management.Compute.Models.ImageStorageProfile(); } // OsDisk if (this.Image.StorageProfile.OsDisk == null) { this.Image.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.ImageOSDisk(); } this.Image.StorageProfile.OsDisk.StorageAccountType = this.StorageAccountType; } if (this.SnapshotId != null) { // StorageProfile if (this.Image.StorageProfile == null) { this.Image.StorageProfile = new Microsoft.Azure.Management.Compute.Models.ImageStorageProfile(); } // OsDisk if (this.Image.StorageProfile.OsDisk == null) { this.Image.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.ImageOSDisk(); } // Snapshot if (this.Image.StorageProfile.OsDisk.Snapshot == null) { this.Image.StorageProfile.OsDisk.Snapshot = new Microsoft.Azure.Management.Compute.Models.SubResource(); } this.Image.StorageProfile.OsDisk.Snapshot.Id = this.SnapshotId; } if (this.ManagedDiskId != null) { // StorageProfile if (this.Image.StorageProfile == null) { this.Image.StorageProfile = new Microsoft.Azure.Management.Compute.Models.ImageStorageProfile(); } // OsDisk if (this.Image.StorageProfile.OsDisk == null) { this.Image.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.ImageOSDisk(); } // ManagedDisk if (this.Image.StorageProfile.OsDisk.ManagedDisk == null) { this.Image.StorageProfile.OsDisk.ManagedDisk = new Microsoft.Azure.Management.Compute.Models.SubResource(); } this.Image.StorageProfile.OsDisk.ManagedDisk.Id = this.ManagedDiskId; } WriteObject(this.Image); } } }
/* 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.Phone.Controls; using System; using System.Collections.Generic; using System.IO; using System.IO.IsolatedStorage; using System.Linq; using System.Net; using System.Runtime.Serialization; using System.Windows; using System.Security; using System.Diagnostics; using System.Threading.Tasks; using WPCordovaClassLib.Cordova.JSON; using System.Reflection; namespace WPCordovaClassLib.Cordova.Commands { public class FileTransfer : BaseCommand { public class DownloadRequestState { // This class stores the State of the request. public HttpWebRequest request; public TransferOptions options; public bool isCancelled; public DownloadRequestState() { request = null; options = null; isCancelled = false; } } public class TransferOptions { /// File path to upload OR File path to download to public string FilePath { get; set; } public string Url { get; set; } /// Flag to recognize if we should trust every host (only in debug environments) public bool TrustAllHosts { get; set; } public string Id { get; set; } public string Headers { get; set; } public string CallbackId { get; set; } public bool ChunkedMode { get; set; } /// Server address public string Server { get; set; } /// File key public string FileKey { get; set; } /// File name on the server public string FileName { get; set; } /// File Mime type public string MimeType { get; set; } /// Additional options public string Params { get; set; } public string Method { get; set; } public TransferOptions() { FileKey = "file"; FileName = "image.jpg"; MimeType = "image/jpeg"; } } /// <summary> /// Boundary symbol /// </summary> private string Boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); // Error codes public const int FileNotFoundError = 1; public const int InvalidUrlError = 2; public const int ConnectionError = 3; public const int AbortError = 4; // not really an error, but whatevs private static Dictionary<string, DownloadRequestState> InProcDownloads = new Dictionary<string,DownloadRequestState>(); // Private instance of the main WebBrowser instance // NOTE: Any access to this object needs to occur on the UI thread via the Dispatcher private WebBrowser browser; /// <summary> /// Uploading response info /// </summary> [DataContract] public class FileUploadResult { /// <summary> /// Amount of sent bytes /// </summary> [DataMember(Name = "bytesSent")] public long BytesSent { get; set; } /// <summary> /// Server response code /// </summary> [DataMember(Name = "responseCode")] public long ResponseCode { get; set; } /// <summary> /// Server response /// </summary> [DataMember(Name = "response", EmitDefaultValue = false)] public string Response { get; set; } /// <summary> /// Creates FileUploadResult object with response values /// </summary> /// <param name="bytesSent">Amount of sent bytes</param> /// <param name="responseCode">Server response code</param> /// <param name="response">Server response</param> public FileUploadResult(long bytesSent, long responseCode, string response) { this.BytesSent = bytesSent; this.ResponseCode = responseCode; this.Response = response; } } /// <summary> /// Represents transfer error codes for callback /// </summary> [DataContract] public class FileTransferError { /// <summary> /// Error code /// </summary> [DataMember(Name = "code", IsRequired = true)] public int Code { get; set; } /// <summary> /// The source URI /// </summary> [DataMember(Name = "source", IsRequired = true)] public string Source { get; set; } /// <summary> /// The target URI /// </summary> /// [DataMember(Name = "target", IsRequired = true)] public string Target { get; set; } [DataMember(Name = "body", IsRequired = true)] public string Body { get; set; } /// <summary> /// The http status code response from the remote URI /// </summary> [DataMember(Name = "http_status", IsRequired = true)] public int HttpStatus { get; set; } /// <summary> /// Creates FileTransferError object /// </summary> /// <param name="errorCode">Error code</param> public FileTransferError(int errorCode) { this.Code = errorCode; this.Source = null; this.Target = null; this.HttpStatus = 0; this.Body = ""; } public FileTransferError(int errorCode, string source, string target, int status, string body = "") { this.Code = errorCode; this.Source = source; this.Target = target; this.HttpStatus = status; this.Body = body; } } /// <summary> /// Represents a singular progress event to be passed back to javascript /// </summary> [DataContract] public class FileTransferProgress { /// <summary> /// Is the length of the response known? /// </summary> [DataMember(Name = "lengthComputable", IsRequired = true)] public bool LengthComputable { get; set; } /// <summary> /// amount of bytes loaded /// </summary> [DataMember(Name = "loaded", IsRequired = true)] public long BytesLoaded { get; set; } /// <summary> /// Total bytes /// </summary> [DataMember(Name = "total", IsRequired = false)] public long BytesTotal { get; set; } public FileTransferProgress(long bTotal = 0, long bLoaded = 0) { LengthComputable = bTotal > 0; BytesLoaded = bLoaded; BytesTotal = bTotal; } } /// <summary> /// Represents a request header passed from Javascript to upload/download operations /// </summary> [DataContract] protected struct Header { [DataMember(Name = "name")] public string Name; [DataMember(Name = "value")] public string Value; } private static MethodInfo JsonDeserializeUsingJsonNet; public FileTransfer() { if (JsonDeserializeUsingJsonNet == null) { var method = typeof(JsonHelper).GetMethod("Deserialize", new Type[] { typeof(string), typeof(bool) }); if (method != null) { JsonDeserializeUsingJsonNet = method.MakeGenericMethod(new Type[] { typeof(Header[]) }); } } } /// Helper method to copy all relevant cookies from the WebBrowser control into a header on /// the HttpWebRequest /// </summary> /// <param name="browser">The source browser to copy the cookies from</param> /// <param name="webRequest">The destination HttpWebRequest to add the cookie header to</param> /// <returns>Nothing</returns> private async Task CopyCookiesFromWebBrowser(HttpWebRequest webRequest) { var tcs = new TaskCompletionSource<object>(); // Accessing WebBrowser needs to happen on the UI thread Deployment.Current.Dispatcher.BeginInvoke(() => { // Get the WebBrowser control if (this.browser == null) { PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame; if (frame != null) { PhoneApplicationPage page = frame.Content as PhoneApplicationPage; if (page != null) { CordovaView cView = page.FindName("CordovaView") as CordovaView; if (cView != null) { this.browser = cView.Browser; } } } } try { // Only copy the cookies if the scheme and host match (to avoid any issues with secure/insecure cookies) // NOTE: since the returned CookieCollection appears to munge the original cookie's domain value in favor of the actual Source domain, // we can't know for sure whether the cookies would be applicable to any other hosts, so best to play it safe and skip for now. if (this.browser != null && this.browser.Source.IsAbsoluteUri == true && this.browser.Source.Scheme == webRequest.RequestUri.Scheme && this.browser.Source.Host == webRequest.RequestUri.Host) { string cookieHeader = ""; string requestPath = webRequest.RequestUri.PathAndQuery; CookieCollection cookies = this.browser.GetCookies(); // Iterate over the cookies and add to the header foreach (Cookie cookie in cookies) { // Check that the path is allowed, first // NOTE: Path always seems to be empty for now, even if the cookie has a path set by the server. if (cookie.Path.Length == 0 || requestPath.IndexOf(cookie.Path, StringComparison.InvariantCultureIgnoreCase) == 0) { cookieHeader += cookie.Name + "=" + cookie.Value + "; "; } } // Finally, set the header if we found any cookies if (cookieHeader.Length > 0) { webRequest.Headers["Cookie"] = cookieHeader; } } } catch (Exception) { // Swallow the exception } // Complete the task tcs.SetResult(Type.Missing); }); await tcs.Task; } /// <summary> /// Upload options /// </summary> //private TransferOptions uploadOptions; /// <summary> /// Bytes sent /// </summary> private long bytesSent; /// <summary> /// sends a file to a server /// </summary> /// <param name="options">Upload options</param> /// exec(win, fail, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]); public void upload(string options) { options = options.Replace("{}", ""); // empty objects screw up the Deserializer string callbackId = ""; TransferOptions uploadOptions = null; HttpWebRequest webRequest = null; try { try { string[] args = JSON.JsonHelper.Deserialize<string[]>(options); uploadOptions = new TransferOptions(); uploadOptions.FilePath = args[0]; uploadOptions.Server = args[1]; uploadOptions.FileKey = args[2]; uploadOptions.FileName = args[3]; uploadOptions.MimeType = args[4]; uploadOptions.Params = args[5]; bool trustAll = false; bool.TryParse(args[6],out trustAll); uploadOptions.TrustAllHosts = trustAll; bool doChunked = false; bool.TryParse(args[7], out doChunked); uploadOptions.ChunkedMode = doChunked; //8 : Headers //9 : id //10: method uploadOptions.Headers = args[8]; uploadOptions.Id = args[9]; uploadOptions.Method = args[10]; uploadOptions.CallbackId = callbackId = args[11]; } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return; } Uri serverUri; try { serverUri = new Uri(uploadOptions.Server); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError, uploadOptions.Server, null, 0))); return; } webRequest = (HttpWebRequest)WebRequest.Create(serverUri); webRequest.ContentType = "multipart/form-data; boundary=" + Boundary; webRequest.Method = uploadOptions.Method; DownloadRequestState reqState = new DownloadRequestState(); InProcDownloads[uploadOptions.Id] = reqState; reqState.options = uploadOptions; reqState.request = webRequest; try { // Associate cookies with the request // This is an async call, so we need to await it in order to preserve proper control flow Task cookieTask = CopyCookiesFromWebBrowser(webRequest); cookieTask.Wait(); } catch (AggregateException ae) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileTransfer.ConnectionError, uploadOptions.FilePath, uploadOptions.Server, 0, ae.InnerException.Message))); return; } if (!string.IsNullOrEmpty(uploadOptions.Headers)) { Dictionary<string, string> headers = parseHeaders(uploadOptions.Headers); if (headers != null) { foreach (string key in headers.Keys) { webRequest.Headers[key] = headers[key]; } } } webRequest.BeginGetRequestStream(uploadCallback, reqState); } catch (Exception /*ex*/) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)),callbackId); } } // example : "{\"Authorization\":\"Basic Y29yZG92YV91c2VyOmNvcmRvdmFfcGFzc3dvcmQ=\"}" protected Dictionary<string,string> parseHeaders(string jsonHeaders) { try { if (FileTransfer.JsonDeserializeUsingJsonNet != null) { return ((Header[])FileTransfer.JsonDeserializeUsingJsonNet.Invoke(null, new object[] { jsonHeaders, true })) .ToDictionary(header => header.Name, header => header.Value); } else { return JsonHelper.Deserialize<Header[]>(jsonHeaders) .ToDictionary(header => header.Name, header => header.Value); } } catch (Exception) { Debug.WriteLine("Failed to parseHeaders from string :: " + jsonHeaders); } return new Dictionary<string, string>(); } public void download(string options) { TransferOptions downloadOptions = null; HttpWebRequest webRequest = null; string callbackId; try { // source, target, trustAllHosts, this._id, headers string[] optionStrings = JSON.JsonHelper.Deserialize<string[]>(options); downloadOptions = new TransferOptions(); downloadOptions.Url = optionStrings[0]; downloadOptions.FilePath = optionStrings[1]; bool trustAll = false; bool.TryParse(optionStrings[2],out trustAll); downloadOptions.TrustAllHosts = trustAll; downloadOptions.Id = optionStrings[3]; downloadOptions.Headers = optionStrings[4]; downloadOptions.CallbackId = callbackId = optionStrings[5]; } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return; } try { // is the URL a local app file? if (downloadOptions.Url.StartsWith("x-wmapp0") || downloadOptions.Url.StartsWith("file:")) { using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { string cleanUrl = downloadOptions.Url.Replace("x-wmapp0:", "").Replace("file:", "").Replace("//",""); // pre-emptively create any directories in the FilePath that do not exist string directoryName = getDirectoryName(downloadOptions.FilePath); if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName)) { isoFile.CreateDirectory(directoryName); } // just copy from one area of iso-store to another ... if (isoFile.FileExists(downloadOptions.Url)) { isoFile.CopyFile(downloadOptions.Url, downloadOptions.FilePath); } else { // need to unpack resource from the dll Uri uri = new Uri(cleanUrl, UriKind.Relative); var resource = Application.GetResourceStream(uri); if (resource != null) { // create the file destination if (!isoFile.FileExists(downloadOptions.FilePath)) { var destFile = isoFile.CreateFile(downloadOptions.FilePath); destFile.Close(); } using (FileStream fileStream = new IsolatedStorageFileStream(downloadOptions.FilePath, FileMode.Open, FileAccess.Write, isoFile)) { long totalBytes = resource.Stream.Length; int bytesRead = 0; using (BinaryReader reader = new BinaryReader(resource.Stream)) { using (BinaryWriter writer = new BinaryWriter(fileStream)) { int BUFFER_SIZE = 1024; byte[] buffer; while (true) { buffer = reader.ReadBytes(BUFFER_SIZE); // fire a progress event ? bytesRead += buffer.Length; if (buffer.Length > 0) { writer.Write(buffer); DispatchFileTransferProgress(bytesRead, totalBytes, callbackId); } else { writer.Close(); reader.Close(); fileStream.Close(); break; } } } } } } } } File.FileEntry entry = File.FileEntry.GetEntry(downloadOptions.FilePath); if (entry != null) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, File.NOT_FOUND_ERR), callbackId); } return; } else { // otherwise it is web-bound, we will actually download it //Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url); webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url); } } catch (Exception /*ex*/) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError, downloadOptions.Url, null, 0))); return; } if (downloadOptions != null && webRequest != null) { DownloadRequestState state = new DownloadRequestState(); state.options = downloadOptions; state.request = webRequest; InProcDownloads[downloadOptions.Id] = state; try { // Associate cookies with the request // This is an async call, so we need to await it in order to preserve proper control flow Task cookieTask = CopyCookiesFromWebBrowser(webRequest); cookieTask.Wait(); } catch (AggregateException ae) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileTransfer.ConnectionError, downloadOptions.Url, downloadOptions.FilePath, 0, ae.InnerException.Message))); return; } if (!string.IsNullOrEmpty(downloadOptions.Headers)) { Dictionary<string, string> headers = parseHeaders(downloadOptions.Headers); foreach (string key in headers.Keys) { webRequest.Headers[key] = headers[key]; } } try { webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state); } catch (WebException) { // eat it } // dispatch an event for progress ( 0 ) lock (state) { if (!state.isCancelled) { var plugRes = new PluginResult(PluginResult.Status.OK, new FileTransferProgress()); plugRes.KeepCallback = true; plugRes.CallbackId = callbackId; DispatchCommandResult(plugRes, callbackId); } } } } public void abort(string options) { Debug.WriteLine("Abort :: " + options); string[] optionStrings = JSON.JsonHelper.Deserialize<string[]>(options); string id = optionStrings[0]; string callbackId = optionStrings[1]; if (id != null && InProcDownloads.ContainsKey(id)) { DownloadRequestState state = InProcDownloads[id]; if (!state.isCancelled) { // prevent multiple callbacks for the same abort state.isCancelled = true; if (!state.request.HaveResponse) { state.request.Abort(); InProcDownloads.Remove(id); //callbackId = state.options.CallbackId; //state = null; DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileTransfer.AbortError)), state.options.CallbackId); } } } else { DispatchCommandResult(new PluginResult(PluginResult.Status.IO_EXCEPTION), callbackId); // TODO: is it an IO exception? } } private void DispatchFileTransferProgress(long bytesLoaded, long bytesTotal, string callbackId, bool keepCallback = true) { Debug.WriteLine("DispatchFileTransferProgress : " + callbackId); // send a progress change event FileTransferProgress progEvent = new FileTransferProgress(bytesTotal); progEvent.BytesLoaded = bytesLoaded; PluginResult plugRes = new PluginResult(PluginResult.Status.OK, progEvent); plugRes.KeepCallback = keepCallback; plugRes.CallbackId = callbackId; DispatchCommandResult(plugRes, callbackId); } /// <summary> /// /// </summary> /// <param name="asynchronousResult"></param> private void downloadCallback(IAsyncResult asynchronousResult) { DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState; HttpWebRequest request = reqState.request; string callbackId = reqState.options.CallbackId; try { HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); // send a progress change event DispatchFileTransferProgress(0, response.ContentLength, callbackId); using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { // create any directories in the path that do not exist string directoryName = getDirectoryName(reqState.options.FilePath); if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName)) { isoFile.CreateDirectory(directoryName); } // create the file if not exists if (!isoFile.FileExists(reqState.options.FilePath)) { var file = isoFile.CreateFile(reqState.options.FilePath); file.Close(); } using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.Open, FileAccess.Write, isoFile)) { long totalBytes = response.ContentLength; int bytesRead = 0; using (BinaryReader reader = new BinaryReader(response.GetResponseStream())) { using (BinaryWriter writer = new BinaryWriter(fileStream)) { int BUFFER_SIZE = 1024; byte[] buffer; while (true) { buffer = reader.ReadBytes(BUFFER_SIZE); // fire a progress event ? bytesRead += buffer.Length; if (buffer.Length > 0 && !reqState.isCancelled) { writer.Write(buffer); DispatchFileTransferProgress(bytesRead, totalBytes, callbackId); } else { writer.Close(); reader.Close(); fileStream.Close(); break; } System.Threading.Thread.Sleep(1); } } } } if (reqState.isCancelled) { isoFile.DeleteFile(reqState.options.FilePath); } } if (reqState.isCancelled) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(AbortError)), callbackId); } else { File.FileEntry entry = new File.FileEntry(reqState.options.FilePath); DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId); } } catch (IsolatedStorageException) { // Trying to write the file somewhere within the IsoStorage. DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)), callbackId); } catch (SecurityException) { // Trying to write the file somewhere not allowed. DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)), callbackId); } catch (WebException webex) { // TODO: probably need better work here to properly respond with all http status codes back to JS // Right now am jumping through hoops just to detect 404. HttpWebResponse response = (HttpWebResponse)webex.Response; if ((webex.Status == WebExceptionStatus.ProtocolError && response.StatusCode == HttpStatusCode.NotFound) || webex.Status == WebExceptionStatus.UnknownError) { // Weird MSFT detection of 404... seriously... just give us the f(*&#$@ status code as a number ffs!!! // "Numbers for HTTP status codes? Nah.... let's create our own set of enums/structs to abstract that stuff away." // FACEPALM // Or just cast it to an int, whiner ... -jm int statusCode = (int)response.StatusCode; string body = ""; using (Stream streamResponse = response.GetResponseStream()) { using (StreamReader streamReader = new StreamReader(streamResponse)) { body = streamReader.ReadToEnd(); } } FileTransferError ftError = new FileTransferError(ConnectionError, null, null, statusCode, body); DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ftError), callbackId); } else { lock (reqState) { if (!reqState.isCancelled) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)), callbackId); } else { Debug.WriteLine("It happened"); } } } } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)), callbackId); } //System.Threading.Thread.Sleep(1000); if (InProcDownloads.ContainsKey(reqState.options.Id)) { InProcDownloads.Remove(reqState.options.Id); } } /// <summary> /// Read file from Isolated Storage and sends it to server /// </summary> /// <param name="asynchronousResult"></param> private void uploadCallback(IAsyncResult asynchronousResult) { DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState; HttpWebRequest webRequest = reqState.request; string callbackId = reqState.options.CallbackId; try { using (Stream requestStream = (webRequest.EndGetRequestStream(asynchronousResult))) { string lineStart = "--"; string lineEnd = Environment.NewLine; byte[] boundaryBytes = System.Text.Encoding.UTF8.GetBytes(lineStart + Boundary + lineEnd); string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"" + lineEnd + lineEnd + "{1}" + lineEnd; if (!string.IsNullOrEmpty(reqState.options.Params)) { Dictionary<string, string> paramMap = parseHeaders(reqState.options.Params); foreach (string key in paramMap.Keys) { requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); string formItem = string.Format(formdataTemplate, key, paramMap[key]); byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(formItem); requestStream.Write(formItemBytes, 0, formItemBytes.Length); } } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoFile.FileExists(reqState.options.FilePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError, reqState.options.Server, reqState.options.FilePath, 0))); return; } byte[] endRequest = System.Text.Encoding.UTF8.GetBytes(lineEnd + lineStart + Boundary + lineStart + lineEnd); long totalBytesToSend = 0; using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.Open, isoFile)) { string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + lineEnd + "Content-Type: {2}" + lineEnd + lineEnd; string header = string.Format(headerTemplate, reqState.options.FileKey, reqState.options.FileName, reqState.options.MimeType); byte[] headerBytes = System.Text.Encoding.UTF8.GetBytes(header); byte[] buffer = new byte[4096]; int bytesRead = 0; //sent bytes needs to be reseted before new upload bytesSent = 0; totalBytesToSend = fileStream.Length; requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); requestStream.Write(headerBytes, 0, headerBytes.Length); while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { if (!reqState.isCancelled) { requestStream.Write(buffer, 0, bytesRead); bytesSent += bytesRead; DispatchFileTransferProgress(bytesSent, totalBytesToSend, callbackId); System.Threading.Thread.Sleep(1); } else { throw new Exception("UploadCancelledException"); } } } requestStream.Write(endRequest, 0, endRequest.Length); } } // webRequest webRequest.BeginGetResponse(ReadCallback, reqState); } catch (Exception /*ex*/) { if (!reqState.isCancelled) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)), callbackId); } } } /// <summary> /// Reads response into FileUploadResult /// </summary> /// <param name="asynchronousResult"></param> private void ReadCallback(IAsyncResult asynchronousResult) { DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState; try { HttpWebRequest webRequest = reqState.request; string callbackId = reqState.options.CallbackId; if (InProcDownloads.ContainsKey(reqState.options.Id)) { InProcDownloads.Remove(reqState.options.Id); } using (HttpWebResponse response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult)) { using (Stream streamResponse = response.GetResponseStream()) { using (StreamReader streamReader = new StreamReader(streamResponse)) { string responseString = streamReader.ReadToEnd(); Deployment.Current.Dispatcher.BeginInvoke(() => { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileUploadResult(bytesSent, (long)response.StatusCode, responseString))); }); } } } } catch (WebException webex) { // TODO: probably need better work here to properly respond with all http status codes back to JS // Right now am jumping through hoops just to detect 404. if ((webex.Status == WebExceptionStatus.ProtocolError && ((HttpWebResponse)webex.Response).StatusCode == HttpStatusCode.NotFound) || webex.Status == WebExceptionStatus.UnknownError) { int statusCode = (int)((HttpWebResponse)webex.Response).StatusCode; FileTransferError ftError = new FileTransferError(ConnectionError, null, null, statusCode); DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ftError), reqState.options.CallbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)), reqState.options.CallbackId); } } catch (Exception /*ex*/) { FileTransferError transferError = new FileTransferError(ConnectionError, reqState.options.Server, reqState.options.FilePath, 403); DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, transferError), reqState.options.CallbackId); } } // Gets the full path without the filename private string getDirectoryName(String filePath) { string directoryName; try { directoryName = filePath.Substring(0, filePath.LastIndexOf('/')); } catch { directoryName = ""; } return directoryName; } } }
// Copyright (c) 2010-2013 SharpDoc - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Xml; namespace SharpDoc.Model { /// <summary> /// Base class for <see cref="IModelReference"/>. /// </summary> public abstract class NModelBase : IModelReference, IEquatable<NModelBase> { private XmlNode _docNode; protected NModelBase() { SeeAlsos = new List<NSeeAlso>(); Groups = new List<string>(); } public int Index { get; set; } /// <summary> /// Gets or sets the XML generated comment ID. /// See http://msdn.microsoft.com/en-us/library/fsbx0t7x.aspx for more information. /// </summary> /// <value>The id.</value> public string Id { get; set; } /// <summary> /// Gets or sets the file id. THis is a version of the <see cref="IModelReference.Id"/> that /// can be used for filename. /// </summary> /// <value>The file id.</value> public string PageId { get; set; } /// <summary> /// Gets or sets the page title. /// </summary> /// <value> /// The page title. /// </value> public string PageTitle { get; set; } /// <summary> /// Gets or sets the name of this instance. /// </summary> /// <value>The name.</value> public string Name { get; set; } /// <summary> /// Gets or sets the full name of this instance. /// </summary> /// <value>The full name.</value> public string FullName { get; set; } /// <summary> /// Gets or sets the category. /// </summary> /// <value> /// The category. /// </value> public string Category { get; protected set; } public IModelReference Assembly { get; set; } /// <summary> /// Gets or sets the <see cref="XmlNode"/> extracted from the code comments /// for a particular member. /// </summary> /// <value>The XmlNode doc.</value> public XmlNode DocNode { get { return _docNode; } set { _docNode = value; OnDocNodeUpdate(); } } /// <summary> /// Gets or sets the description extracted from the &lt;summary&gt; tag of the <see cref="IComment.DocNode"/>. /// </summary> /// <value>The description.</value> public string Description { get; set; } /// <summary> /// Gets or sets the un managed API. /// </summary> /// <value> /// The un managed API. /// </value> public string UnManagedApi { get; set; } /// <summary> /// Gets or sets the un managed API. /// </summary> /// <value> /// The un managed API. /// </value> public string UnManagedShortApi { get; set; } /// <summary> /// Gets or sets the MSDN id. /// </summary> /// <value> /// The MSDN id. /// </value> public string MsdnId { get; set; } /// <summary> /// Gets or sets the remarks extracted from the &lt;remarks&gt; tag of the <see cref="IComment.DocNode"/>. /// </summary> /// <value>The remarks.</value> public string Remarks { get; set; } /// <summary> /// Gets or sets the web documentation page extracted from the &lt;webdoc&gt; tag of the <see cref="IComment.DocNode"/>. /// </summary> /// <value>The corresponding webDocumentation page.</value> public XmlNode WebDocPage { get; set; } /// <summary> /// Gets or sets the &lt;inheritdoc&gt; tag of the <see cref="IComment.DocNode"/>. /// </summary> /// <value>The inheritdoc xml node.</value> public XmlNode InheritDoc { get; set; } /// <summary> /// Gets or sets the topic link. /// </summary> /// <value>The topic link.</value> public NTopic TopicLink { get; set; } /// <summary> /// Gets or sets the see alsos. /// </summary> /// <value> /// The see alsos. /// </value> public List<NSeeAlso> SeeAlsos { get; set; } /// <summary> /// Gets or sets the group APIs. /// </summary> /// <value> /// The group APIs. /// </value> public List<string> Groups { get; private set; } /// <summary> /// Sets the API group. /// </summary> /// <param name="name">The name.</param> /// <param name="state">if set to <c>true</c> [state].</param> public void SetApiGroup(string name, bool state) { if (state) { if (!Groups.Contains(name)) { Groups.Add(name); } } else { Groups.Remove(name); } } /// <summary> /// Gets or sets a value indicating whether this instance is obsolete. /// </summary> /// <value> /// <c>true</c> if this instance is obsolete; otherwise, <c>false</c>. /// </value> public bool IsObsolete { get; set; } /// <summary> /// Gets or sets the obsolete message. /// </summary> /// <value> /// The obsolete message. /// </value> public string ObsoleteMessage { get; set; } /// <summary> /// Called when <see cref="DocNode"/> is updated. /// </summary> protected internal virtual void OnDocNodeUpdate() { if (DocNode != null) { Description = NDocumentApi.GetTag(DocNode, DocTag.Summary); Remarks = NDocumentApi.GetTag(DocNode, DocTag.Remarks); WebDocPage = NDocumentApi.GetXmlNode(DocNode, DocTag.WebDoc); InheritDoc = NDocumentApi.GetXmlNode(DocNode, DocTag.InheritDoc); UnManagedApi = NDocumentApi.GetTag(DocNode, "unmanaged"); UnManagedShortApi = NDocumentApi.GetTag(DocNode, "unmanaged-short"); MsdnId = NDocumentApi.GetTag(DocNode, "msdn-id"); } } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false. /// </returns> public bool Equals(NModelBase other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Equals(other.Id, Id); } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof (NModelBase)) return false; return Equals((NModelBase) obj); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { return (Id != null ? Id.GetHashCode() : 0); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(NModelBase left, NModelBase right) { return Equals(left, right); } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(NModelBase left, NModelBase right) { return !Equals(left, right); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute.Automation { public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet { protected object CreateImageCreateOrUpdateDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pImageName = new RuntimeDefinedParameter(); pImageName.Name = "ImageName"; pImageName.ParameterType = typeof(string); pImageName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true }); pImageName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ImageName", pImageName); var pParameters = new RuntimeDefinedParameter(); pParameters.Name = "Image"; pParameters.ParameterType = typeof(Image); pParameters.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = true }); pParameters.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("Image", pParameters); var pArgumentList = new RuntimeDefinedParameter(); pArgumentList.Name = "ArgumentList"; pArgumentList.ParameterType = typeof(object[]); pArgumentList.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByStaticParameters", Position = 4, Mandatory = true }); pArgumentList.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ArgumentList", pArgumentList); return dynamicParameters; } protected void ExecuteImageCreateOrUpdateMethod(object[] invokeMethodInputParameters) { string resourceGroupName = (string)ParseParameter(invokeMethodInputParameters[0]); string imageName = (string)ParseParameter(invokeMethodInputParameters[1]); Image parameters = (Image)ParseParameter(invokeMethodInputParameters[2]); var result = ImagesClient.CreateOrUpdate(resourceGroupName, imageName, parameters); WriteObject(result); } } public partial class NewAzureComputeArgumentListCmdlet : ComputeAutomationBaseCmdlet { protected PSArgument[] CreateImageCreateOrUpdateParameters() { string resourceGroupName = string.Empty; string imageName = string.Empty; Image parameters = new Image(); return ConvertFromObjectsToArguments( new string[] { "ResourceGroupName", "ImageName", "Parameters" }, new object[] { resourceGroupName, imageName, parameters }); } } [Cmdlet(VerbsCommon.New, "AzureRmImage", DefaultParameterSetName = "InvokeByDynamicParameters", SupportsShouldProcess = true)] public partial class NewAzureRmImage : InvokeAzureComputeMethodCmdlet { public override string MethodName { get; set; } protected override void ProcessRecord() { this.MethodName = "ImageCreateOrUpdate"; if (ShouldProcess(this.dynamicParameters["ResourceGroupName"].Value.ToString(), VerbsCommon.New)) { base.ProcessRecord(); } } public override object GetDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pImageName = new RuntimeDefinedParameter(); pImageName.Name = "ImageName"; pImageName.ParameterType = typeof(string); pImageName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false }); pImageName.Attributes.Add(new AliasAttribute("Name")); pImageName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ImageName", pImageName); var pParameters = new RuntimeDefinedParameter(); pParameters.Name = "Image"; pParameters.ParameterType = typeof(Image); pParameters.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = true, ValueFromPipelineByPropertyName = false, ValueFromPipeline = true }); pParameters.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("Image", pParameters); return dynamicParameters; } } [Cmdlet(VerbsData.Update, "AzureRmImage", DefaultParameterSetName = "InvokeByDynamicParameters", SupportsShouldProcess = true)] public partial class UpdateAzureRmImage : InvokeAzureComputeMethodCmdlet { public override string MethodName { get; set; } protected override void ProcessRecord() { this.MethodName = "ImageCreateOrUpdate"; if (ShouldProcess(this.dynamicParameters["ResourceGroupName"].Value.ToString(), VerbsData.Update)) { base.ProcessRecord(); } } public override object GetDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pImageName = new RuntimeDefinedParameter(); pImageName.Name = "ImageName"; pImageName.ParameterType = typeof(string); pImageName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false }); pImageName.Attributes.Add(new AliasAttribute("Name")); pImageName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ImageName", pImageName); var pParameters = new RuntimeDefinedParameter(); pParameters.Name = "Image"; pParameters.ParameterType = typeof(Image); pParameters.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = true, ValueFromPipelineByPropertyName = false, ValueFromPipeline = true }); pParameters.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("Image", pParameters); return dynamicParameters; } } }
/* * 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.IO; using System.Net; using System.Reflection; using log4net; using log4net.Config; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Console; namespace OpenSim { /// <summary> /// Starting class for the OpenSimulator Region /// </summary> public class Application { /// <summary> /// Text Console Logger /// </summary> private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Path to the main ini Configuration file /// </summary> public static string iniFilePath = ""; /// <summary> /// Save Crashes in the bin/crashes folder. Configurable with m_crashDir /// </summary> public static bool m_saveCrashDumps = false; /// <summary> /// Directory to save crash reports to. Relative to bin/ /// </summary> public static string m_crashDir = "crashes"; /// <summary> /// Instance of the OpenSim class. This could be OpenSim or OpenSimBackground depending on the configuration /// </summary> protected static OpenSimBase m_sim = null; //could move our main function into OpenSimMain and kill this class public static void Main(string[] args) { // First line, hook the appdomain to the crash reporter AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); ServicePointManager.DefaultConnectionLimit = 12; ServicePointManager.UseNagleAlgorithm = false; // Add the arguments supplied when running the application to the configuration ArgvConfigSource configSource = new ArgvConfigSource(args); // Configure Log4Net configSource.AddSwitch("Startup", "logconfig"); string logConfigFile = configSource.Configs["Startup"].GetString("logconfig", String.Empty); if (logConfigFile != String.Empty) { XmlConfigurator.Configure(new System.IO.FileInfo(logConfigFile)); m_log.InfoFormat("[OPENSIM MAIN]: configured log4net using \"{0}\" as configuration file", logConfigFile); } else { XmlConfigurator.Configure(); m_log.Info("[OPENSIM MAIN]: configured log4net using default OpenSim.exe.config"); } m_log.InfoFormat( "[OPENSIM MAIN]: System Locale is {0}", System.Threading.Thread.CurrentThread.CurrentCulture); string monoThreadsPerCpu = System.Environment.GetEnvironmentVariable("MONO_THREADS_PER_CPU"); m_log.InfoFormat( "[OPENSIM MAIN]: Environment variable MONO_THREADS_PER_CPU is {0}", monoThreadsPerCpu ?? "unset"); // Verify the Threadpool allocates or uses enough worker and IO completion threads // .NET 2.0, workerthreads default to 50 * numcores // .NET 3.0, workerthreads defaults to 250 * numcores // .NET 4.0, workerthreads are dynamic based on bitness and OS resources // Max IO Completion threads are 1000 on all 3 CLRs // // Mono 2.10.9 to at least Mono 3.1, workerthreads default to 100 * numcores, iocp threads to 4 * numcores int workerThreadsMin = 500; int workerThreadsMax = 1000; // may need further adjustment to match other CLR int iocpThreadsMin = 1000; int iocpThreadsMax = 2000; // may need further adjustment to match other CLR { int currentMinWorkerThreads, currentMinIocpThreads; System.Threading.ThreadPool.GetMinThreads(out currentMinWorkerThreads, out currentMinIocpThreads); m_log.InfoFormat( "[OPENSIM MAIN]: Runtime gave us {0} min worker threads and {1} min IOCP threads", currentMinWorkerThreads, currentMinIocpThreads); } int workerThreads, iocpThreads; System.Threading.ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads); m_log.InfoFormat("[OPENSIM MAIN]: Runtime gave us {0} max worker threads and {1} max IOCP threads", workerThreads, iocpThreads); if (workerThreads < workerThreadsMin) { workerThreads = workerThreadsMin; m_log.InfoFormat("[OPENSIM MAIN]: Bumping up max worker threads to {0}",workerThreads); } if (workerThreads > workerThreadsMax) { workerThreads = workerThreadsMax; m_log.InfoFormat("[OPENSIM MAIN]: Limiting max worker threads to {0}",workerThreads); } // Increase the number of IOCP threads available. // Mono defaults to a tragically low number (24 on 6-core / 8GB Fedora 17) if (iocpThreads < iocpThreadsMin) { iocpThreads = iocpThreadsMin; m_log.InfoFormat("[OPENSIM MAIN]: Bumping up max IOCP threads to {0}",iocpThreads); } // Make sure we don't overallocate IOCP threads and thrash system resources if ( iocpThreads > iocpThreadsMax ) { iocpThreads = iocpThreadsMax; m_log.InfoFormat("[OPENSIM MAIN]: Limiting max IOCP completion threads to {0}",iocpThreads); } // set the resulting worker and IO completion thread counts back to ThreadPool if ( System.Threading.ThreadPool.SetMaxThreads(workerThreads, iocpThreads) ) { m_log.InfoFormat( "[OPENSIM MAIN]: Threadpool set to {0} max worker threads and {1} max IOCP threads", workerThreads, iocpThreads); } else { m_log.Warn("[OPENSIM MAIN]: Threadpool reconfiguration failed, runtime defaults still in effect."); } // Check if the system is compatible with OpenSimulator. // Ensures that the minimum system requirements are met string supported = String.Empty; if (Util.IsEnvironmentSupported(ref supported)) { m_log.Info("[OPENSIM MAIN]: Environment is supported by OpenSimulator."); } else { m_log.Warn("[OPENSIM MAIN]: Environment is not supported by OpenSimulator (" + supported + ")\n"); } // Configure nIni aliases and localles Culture.SetCurrentCulture(); // Validate that the user has the most basic configuration done // If not, offer to do the most basic configuration for them warning them along the way of the importance of // reading these files. /* m_log.Info("Checking for reguired configuration...\n"); bool OpenSim_Ini = (File.Exists(Path.Combine(Util.configDir(), "OpenSim.ini"))) || (File.Exists(Path.Combine(Util.configDir(), "opensim.ini"))) || (File.Exists(Path.Combine(Util.configDir(), "openSim.ini"))) || (File.Exists(Path.Combine(Util.configDir(), "Opensim.ini"))); bool StanaloneCommon_ProperCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini")); bool StanaloneCommon_lowercased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "standalonecommon.ini")); bool GridCommon_ProperCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "GridCommon.ini")); bool GridCommon_lowerCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "gridcommon.ini")); if ((OpenSim_Ini) && ( (StanaloneCommon_ProperCased || StanaloneCommon_lowercased || GridCommon_ProperCased || GridCommon_lowerCased ))) { m_log.Info("Required Configuration Files Found\n"); } else { MainConsole.Instance = new LocalConsole("Region"); string resp = MainConsole.Instance.CmdPrompt( "\n\n*************Required Configuration files not found.*************\n\n OpenSimulator will not run without these files.\n\nRemember, these file names are Case Sensitive in Linux and Proper Cased.\n1. ./OpenSim.ini\nand\n2. ./config-include/StandaloneCommon.ini \nor\n3. ./config-include/GridCommon.ini\n\nAlso, you will want to examine these files in great detail because only the basic system will load by default. OpenSimulator can do a LOT more if you spend a little time going through these files.\n\n" + ": " + "Do you want to copy the most basic Defaults from standalone?", "yes"); if (resp == "yes") { if (!(OpenSim_Ini)) { try { File.Copy(Path.Combine(Util.configDir(), "OpenSim.ini.example"), Path.Combine(Util.configDir(), "OpenSim.ini")); } catch (UnauthorizedAccessException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, Make sure OpenSim has have the required permissions\n"); } catch (ArgumentException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, The current directory is invalid.\n"); } catch (System.IO.PathTooLongException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the Path to these files is too long.\n"); } catch (System.IO.DirectoryNotFoundException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the current directory is reporting as not found.\n"); } catch (System.IO.FileNotFoundException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n"); } catch (System.IO.IOException) { // Destination file exists already or a hard drive failure... .. so we can just drop this one //MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n"); } catch (System.NotSupportedException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, The current directory is invalid.\n"); } } if (!(StanaloneCommon_ProperCased || StanaloneCommon_lowercased)) { try { File.Copy(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini.example"), Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini")); } catch (UnauthorizedAccessException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, Make sure OpenSim has the required permissions\n"); } catch (ArgumentException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, The current directory is invalid.\n"); } catch (System.IO.PathTooLongException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the Path to these files is too long.\n"); } catch (System.IO.DirectoryNotFoundException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the current directory is reporting as not found.\n"); } catch (System.IO.FileNotFoundException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the example is not found, please make sure that the example files exist.\n"); } catch (System.IO.IOException) { // Destination file exists already or a hard drive failure... .. so we can just drop this one //MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n"); } catch (System.NotSupportedException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, The current directory is invalid.\n"); } } } MainConsole.Instance = null; } */ configSource.Alias.AddAlias("On", true); configSource.Alias.AddAlias("Off", false); configSource.Alias.AddAlias("True", true); configSource.Alias.AddAlias("False", false); configSource.Alias.AddAlias("Yes", true); configSource.Alias.AddAlias("No", false); configSource.AddSwitch("Startup", "background"); configSource.AddSwitch("Startup", "inifile"); configSource.AddSwitch("Startup", "inimaster"); configSource.AddSwitch("Startup", "inidirectory"); configSource.AddSwitch("Startup", "physics"); configSource.AddSwitch("Startup", "gui"); configSource.AddSwitch("Startup", "console"); configSource.AddSwitch("Startup", "save_crashes"); configSource.AddSwitch("Startup", "crash_dir"); configSource.AddConfig("StandAlone"); configSource.AddConfig("Network"); // Check if we're running in the background or not bool background = configSource.Configs["Startup"].GetBoolean("background", false); // Check if we're saving crashes m_saveCrashDumps = configSource.Configs["Startup"].GetBoolean("save_crashes", false); // load Crash directory config m_crashDir = configSource.Configs["Startup"].GetString("crash_dir", m_crashDir); if (background) { m_sim = new OpenSimBackground(configSource); m_sim.Startup(); } else { m_sim = new OpenSim(configSource); m_sim.Startup(); while (true) { try { // Block thread here for input MainConsole.Instance.Prompt(); } catch (Exception e) { m_log.ErrorFormat("Command error: {0}", e); } } } } private static bool _IsHandlingException = false; // Make sure we don't go recursive on ourself /// <summary> /// Global exception handler -- all unhandlet exceptions end up here :) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { if (_IsHandlingException) { return; } _IsHandlingException = true; // TODO: Add config option to allow users to turn off error reporting // TODO: Post error report (disabled for now) string msg = String.Empty; msg += "\r\n"; msg += "APPLICATION EXCEPTION DETECTED: " + e.ToString() + "\r\n"; msg += "\r\n"; msg += "Exception: " + e.ExceptionObject.ToString() + "\r\n"; Exception ex = (Exception) e.ExceptionObject; if (ex.InnerException != null) { msg += "InnerException: " + ex.InnerException.ToString() + "\r\n"; } msg += "\r\n"; msg += "Application is terminating: " + e.IsTerminating.ToString() + "\r\n"; m_log.ErrorFormat("[APPLICATION]: {0}", msg); if (m_saveCrashDumps) { // Log exception to disk try { if (!Directory.Exists(m_crashDir)) { Directory.CreateDirectory(m_crashDir); } string log = Util.GetUniqueFilename(ex.GetType() + ".txt"); using (StreamWriter m_crashLog = new StreamWriter(Path.Combine(m_crashDir, log))) { m_crashLog.WriteLine(msg); } File.Copy("OpenSim.ini", Path.Combine(m_crashDir, log + "_OpenSim.ini"), true); } catch (Exception e2) { m_log.ErrorFormat("[CRASH LOGGER CRASHED]: {0}", e2); } } _IsHandlingException = false; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Audio; using osu.Framework.Audio.Sample; using osu.Framework.Audio.Track; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Input.Events; using osu.Framework.Logging; using osu.Framework.Screens; using osu.Framework.Threading; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Input.Bindings; using osu.Game.Overlays; using osu.Game.Overlays.Mods; using osu.Game.Rulesets; using osu.Game.Rulesets.Mods; using osu.Game.Screens.Backgrounds; using osu.Game.Screens.Edit; using osu.Game.Screens.Menu; using osu.Game.Screens.Play; using osu.Game.Screens.Select.Options; using osu.Game.Skinning; using osuTK; using osuTK.Graphics; using osuTK.Input; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using osu.Framework.Graphics.Sprites; using osu.Framework.Input.Bindings; using osu.Game.Scoring; namespace osu.Game.Screens.Select { public abstract class SongSelect : OsuScreen, IKeyBindingHandler<GlobalAction> { public static readonly Vector2 WEDGED_CONTAINER_SIZE = new Vector2(0.5f, 245); protected const float BACKGROUND_BLUR = 20; private const float left_area_padding = 20; public readonly FilterControl FilterControl; protected virtual bool ShowFooter => true; /// <summary> /// Can be null if <see cref="ShowFooter"/> is false. /// </summary> protected readonly BeatmapOptionsOverlay BeatmapOptions; /// <summary> /// Can be null if <see cref="ShowFooter"/> is false. /// </summary> protected readonly Footer Footer; /// <summary> /// Contains any panel which is triggered by a footer button. /// Helps keep them located beneath the footer itself. /// </summary> protected readonly Container FooterPanels; protected override BackgroundScreen CreateBackground() { var background = new BackgroundScreenBeatmap(); return background; } protected readonly BeatmapCarousel Carousel; private readonly BeatmapInfoWedge beatmapInfoWedge; private DialogOverlay dialogOverlay; private BeatmapManager beatmaps; protected readonly ModSelectOverlay ModSelect; protected SampleChannel SampleConfirm; private SampleChannel sampleChangeDifficulty; private SampleChannel sampleChangeBeatmap; protected readonly BeatmapDetailArea BeatmapDetails; private readonly Bindable<RulesetInfo> decoupledRuleset = new Bindable<RulesetInfo>(); [Resolved(canBeNull: true)] private MusicController music { get; set; } [Cached] [Cached(Type = typeof(IBindable<IReadOnlyList<Mod>>))] private readonly Bindable<IReadOnlyList<Mod>> mods = new Bindable<IReadOnlyList<Mod>>(Array.Empty<Mod>()); // Bound to the game's mods, but is not reset on exiting protected SongSelect() { AddRangeInternal(new Drawable[] { new ParallaxContainer { Masking = true, ParallaxAmount = 0.005f, RelativeSizeAxes = Axes.Both, Children = new[] { new WedgeBackground { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Right = -150 }, Size = new Vector2(WEDGED_CONTAINER_SIZE.X, 1), } } }, new Container { Origin = Anchor.BottomLeft, Anchor = Anchor.BottomLeft, RelativeSizeAxes = Axes.Both, Size = new Vector2(WEDGED_CONTAINER_SIZE.X, 1), Padding = new MarginPadding { Bottom = Footer.HEIGHT, Top = WEDGED_CONTAINER_SIZE.Y + left_area_padding, Left = left_area_padding, Right = left_area_padding * 2, }, Child = BeatmapDetails = new BeatmapDetailArea { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Top = 10, Right = 5 }, } }, new Container { RelativeSizeAxes = Axes.Both, Masking = true, Anchor = Anchor.Centre, Origin = Anchor.Centre, Width = 2, //avoid horizontal masking so the panels don't clip when screen stack is pushed. Child = new Container { RelativeSizeAxes = Axes.Both, Anchor = Anchor.Centre, Origin = Anchor.Centre, Width = 0.5f, Children = new Drawable[] { new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Top = FilterControl.HEIGHT, Bottom = Footer.HEIGHT }, Child = Carousel = new BeatmapCarousel { RelativeSizeAxes = Axes.Both, Size = new Vector2(1 - WEDGED_CONTAINER_SIZE.X, 1), Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, SelectionChanged = updateSelectedBeatmap, BeatmapSetsChanged = carouselBeatmapsLoaded, }, }, FilterControl = new FilterControl { RelativeSizeAxes = Axes.X, Height = FilterControl.HEIGHT, FilterChanged = c => Carousel.Filter(c), Background = { Width = 2 }, }, } }, }, beatmapInfoWedge = new BeatmapInfoWedge { Size = WEDGED_CONTAINER_SIZE, RelativeSizeAxes = Axes.X, Margin = new MarginPadding { Top = left_area_padding, Right = left_area_padding, }, }, new ResetScrollContainer(() => Carousel.ScrollToSelected()) { RelativeSizeAxes = Axes.Y, Width = 250, } }); if (ShowFooter) { AddRangeInternal(new[] { FooterPanels = new Container { Anchor = Anchor.BottomLeft, Origin = Anchor.BottomLeft, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Margin = new MarginPadding { Bottom = Footer.HEIGHT }, Children = new Drawable[] { BeatmapOptions = new BeatmapOptionsOverlay(), ModSelect = new ModSelectOverlay { RelativeSizeAxes = Axes.X, Origin = Anchor.BottomCentre, Anchor = Anchor.BottomCentre, } } }, Footer = new Footer() }); } BeatmapDetails.Leaderboard.ScoreSelected += score => this.Push(new SoloResults(score)); } [BackgroundDependencyLoader(true)] private void load(BeatmapManager beatmaps, AudioManager audio, DialogOverlay dialog, OsuColour colours, SkinManager skins, ScoreManager scores) { if (Footer != null) { Footer.AddButton(new FooterButtonMods { Current = mods }, ModSelect); Footer.AddButton(new FooterButtonRandom { Action = triggerRandom }); Footer.AddButton(new FooterButtonOptions(), BeatmapOptions); BeatmapOptions.AddButton(@"Remove", @"from unplayed", FontAwesome.Regular.TimesCircle, colours.Purple, null, Key.Number1); BeatmapOptions.AddButton(@"Clear", @"local scores", FontAwesome.Solid.Eraser, colours.Purple, () => clearScores(Beatmap.Value.BeatmapInfo), Key.Number2); BeatmapOptions.AddButton(@"Delete", @"all difficulties", FontAwesome.Solid.Trash, colours.Pink, () => delete(Beatmap.Value.BeatmapSetInfo), Key.Number3); } if (this.beatmaps == null) this.beatmaps = beatmaps; this.beatmaps.ItemAdded += onBeatmapSetAdded; this.beatmaps.ItemRemoved += onBeatmapSetRemoved; this.beatmaps.BeatmapHidden += onBeatmapHidden; this.beatmaps.BeatmapRestored += onBeatmapRestored; dialogOverlay = dialog; sampleChangeDifficulty = audio.Samples.Get(@"SongSelect/select-difficulty"); sampleChangeBeatmap = audio.Samples.Get(@"SongSelect/select-expand"); SampleConfirm = audio.Samples.Get(@"SongSelect/confirm-selection"); if (dialogOverlay != null) { Schedule(() => { // if we have no beatmaps but osu-stable is found, let's prompt the user to import. if (!beatmaps.GetAllUsableBeatmapSetsEnumerable().Any() && beatmaps.StableInstallationAvailable) dialogOverlay.Push(new ImportFromStablePopup(() => { Task.Run(beatmaps.ImportFromStableAsync).ContinueWith(_ => scores.ImportFromStableAsync(), TaskContinuationOptions.OnlyOnRanToCompletion); Task.Run(skins.ImportFromStableAsync); })); }); } } protected override void LoadComplete() { base.LoadComplete(); mods.BindTo(Mods); } private DependencyContainer dependencies; protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) { dependencies = new DependencyContainer(base.CreateChildDependencies(parent)); dependencies.CacheAs(this); dependencies.CacheAs(decoupledRuleset); dependencies.CacheAs<IBindable<RulesetInfo>>(decoupledRuleset); return dependencies; } public void Edit(BeatmapInfo beatmap = null) { Beatmap.Value = beatmaps.GetWorkingBeatmap(beatmap ?? beatmapNoDebounce); this.Push(new Editor()); } /// <summary> /// Call to make a selection and perform the default action for this SongSelect. /// </summary> /// <param name="beatmap">An optional beatmap to override the current carousel selection.</param> /// <param name="performStartAction">Whether to trigger <see cref="OnStart"/>.</param> public void FinaliseSelection(BeatmapInfo beatmap = null, bool performStartAction = true) { // This is very important as we have not yet bound to screen-level bindables before the carousel load is completed. if (!Carousel.BeatmapSetsLoaded) return; // if we have a pending filter operation, we want to run it now. // it could change selection (ie. if the ruleset has been changed). Carousel.FlushPendingFilterOperations(); // avoid attempting to continue before a selection has been obtained. // this could happen via a user interaction while the carousel is still in a loading state. if (Carousel.SelectedBeatmap == null) return; if (beatmap != null) Carousel.SelectBeatmap(beatmap); if (selectionChangedDebounce?.Completed == false) { selectionChangedDebounce.RunTask(); selectionChangedDebounce.Cancel(); // cancel the already scheduled task. selectionChangedDebounce = null; } if (performStartAction) OnStart(); } /// <summary> /// Called when a selection is made. /// </summary> /// <returns>If a resultant action occurred that takes the user away from SongSelect.</returns> protected abstract bool OnStart(); private ScheduledDelegate selectionChangedDebounce; private void workingBeatmapChanged(ValueChangedEvent<WorkingBeatmap> e) { if (e.NewValue is DummyWorkingBeatmap) return; if (this.IsCurrentScreen() && !Carousel.SelectBeatmap(e.NewValue?.BeatmapInfo, false)) // If selecting new beatmap without bypassing filters failed, there's possibly a ruleset mismatch if (e.NewValue?.BeatmapInfo?.Ruleset != null && !e.NewValue.BeatmapInfo.Ruleset.Equals(decoupledRuleset.Value)) { Ruleset.Value = e.NewValue.BeatmapInfo.Ruleset; Carousel.SelectBeatmap(e.NewValue.BeatmapInfo); } } // We need to keep track of the last selected beatmap ignoring debounce to play the correct selection sounds. private BeatmapInfo beatmapNoDebounce; private RulesetInfo rulesetNoDebounce; private void updateSelectedBeatmap(BeatmapInfo beatmap) { if (beatmap?.Equals(beatmapNoDebounce) == true) return; beatmapNoDebounce = beatmap; performUpdateSelected(); } private void updateSelectedRuleset(RulesetInfo ruleset) { if (ruleset?.Equals(rulesetNoDebounce) == true) return; rulesetNoDebounce = ruleset; performUpdateSelected(); } /// <summary> /// selection has been changed as the result of a user interaction. /// </summary> private void performUpdateSelected() { var beatmap = beatmapNoDebounce; var ruleset = rulesetNoDebounce; selectionChangedDebounce?.Cancel(); if (beatmap == null) run(); else selectionChangedDebounce = Scheduler.AddDelayed(run, 200); void run() { Logger.Log($"updating selection with beatmap:{beatmap?.ID.ToString() ?? "null"} ruleset:{ruleset?.ID.ToString() ?? "null"}"); if (ruleset?.Equals(decoupledRuleset.Value) == false) { Logger.Log($"ruleset changed from \"{decoupledRuleset.Value}\" to \"{ruleset}\""); mods.Value = Array.Empty<Mod>(); decoupledRuleset.Value = ruleset; // force a filter before attempting to change the beatmap. // we may still be in the wrong ruleset as there is a debounce delay on ruleset changes. Carousel.Filter(null, false); // Filtering only completes after the carousel runs Update. // If we also have a pending beatmap change we should delay it one frame. selectionChangedDebounce = Schedule(run); return; } // We may be arriving here due to another component changing the bindable Beatmap. // In these cases, the other component has already loaded the beatmap, so we don't need to do so again. if (!Equals(beatmap, Beatmap.Value.BeatmapInfo)) { Logger.Log($"beatmap changed from \"{Beatmap.Value.BeatmapInfo}\" to \"{beatmap}\""); WorkingBeatmap previous = Beatmap.Value; Beatmap.Value = beatmaps.GetWorkingBeatmap(beatmap, previous); if (beatmap != null) { if (beatmap.BeatmapSetInfoID == beatmapNoDebounce?.BeatmapSetInfoID) sampleChangeDifficulty.Play(); else sampleChangeBeatmap.Play(); } } if (this.IsCurrentScreen()) ensurePlayingSelected(); UpdateBeatmap(Beatmap.Value); } } private void triggerRandom() { if (GetContainingInputManager().CurrentState.Keyboard.ShiftPressed) Carousel.SelectPreviousRandom(); else Carousel.SelectNextRandom(); } public override void OnEntering(IScreen last) { base.OnEntering(last); this.FadeInFromZero(250); FilterControl.Activate(); } private const double logo_transition = 250; protected override void LogoArriving(OsuLogo logo, bool resuming) { base.LogoArriving(logo, resuming); Vector2 position = new Vector2(0.95f, 0.96f); if (logo.Alpha > 0.8f) { logo.MoveTo(position, 500, Easing.OutQuint); } else { logo.Hide(); logo.ScaleTo(0.2f); logo.MoveTo(position); } logo.FadeIn(logo_transition, Easing.OutQuint); logo.ScaleTo(0.4f, logo_transition, Easing.OutQuint); logo.Action = () => { FinaliseSelection(); return false; }; } protected override void LogoExiting(OsuLogo logo) { base.LogoExiting(logo); logo.ScaleTo(0.2f, logo_transition / 2, Easing.Out); logo.FadeOut(logo_transition / 2, Easing.Out); } public override void OnResuming(IScreen last) { BeatmapDetails.Leaderboard.RefreshScores(); Beatmap.Value.Track.Looping = true; music?.ResetTrackAdjustments(); if (Beatmap != null && !Beatmap.Value.BeatmapSetInfo.DeletePending) { UpdateBeatmap(Beatmap.Value); ensurePlayingSelected(); } base.OnResuming(last); this.FadeIn(250); this.ScaleTo(1, 250, Easing.OutSine); FilterControl.Activate(); } public override void OnSuspending(IScreen next) { ModSelect.Hide(); BeatmapOptions.Hide(); this.ScaleTo(1.1f, 250, Easing.InSine); this.FadeOut(250); FilterControl.Deactivate(); base.OnSuspending(next); } public override bool OnExiting(IScreen next) { if (ModSelect.State.Value == Visibility.Visible) { ModSelect.Hide(); return true; } if (base.OnExiting(next)) return true; beatmapInfoWedge.Hide(); this.FadeOut(100); FilterControl.Deactivate(); if (Beatmap.Value.Track != null) Beatmap.Value.Track.Looping = false; mods.UnbindAll(); Mods.Value = Array.Empty<Mod>(); return false; } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); decoupledRuleset.UnbindAll(); if (beatmaps != null) { beatmaps.ItemAdded -= onBeatmapSetAdded; beatmaps.ItemRemoved -= onBeatmapSetRemoved; beatmaps.BeatmapHidden -= onBeatmapHidden; beatmaps.BeatmapRestored -= onBeatmapRestored; } } /// <summary> /// Allow components in SongSelect to update their loaded beatmap details. /// This is a debounced call (unlike directly binding to WorkingBeatmap.ValueChanged). /// </summary> /// <param name="beatmap">The working beatmap.</param> protected virtual void UpdateBeatmap(WorkingBeatmap beatmap) { Logger.Log($"working beatmap updated to {beatmap}"); if (Background is BackgroundScreenBeatmap backgroundModeBeatmap) { backgroundModeBeatmap.Beatmap = beatmap; backgroundModeBeatmap.BlurAmount.Value = BACKGROUND_BLUR; backgroundModeBeatmap.FadeColour(Color4.White, 250); } beatmapInfoWedge.Beatmap = beatmap; BeatmapDetails.Beatmap = beatmap; if (beatmap.Track != null) beatmap.Track.Looping = true; } private readonly WeakReference<Track> lastTrack = new WeakReference<Track>(null); /// <summary> /// Ensures some music is playing for the current track. /// Will resume playback from a manual user pause if the track has changed. /// </summary> private void ensurePlayingSelected() { Track track = Beatmap.Value.Track; bool isNewTrack = !lastTrack.TryGetTarget(out var last) || last != track; track.RestartPoint = Beatmap.Value.Metadata.PreviewTime; if (!track.IsRunning && (music?.IsUserPaused != true || isNewTrack)) track.Restart(); lastTrack.SetTarget(track); } private void onBeatmapSetAdded(BeatmapSetInfo s) => Carousel.UpdateBeatmapSet(s); private void onBeatmapSetRemoved(BeatmapSetInfo s) => Carousel.RemoveBeatmapSet(s); private void onBeatmapRestored(BeatmapInfo b) => Carousel.UpdateBeatmapSet(beatmaps.QueryBeatmapSet(s => s.ID == b.BeatmapSetInfoID)); private void onBeatmapHidden(BeatmapInfo b) => Carousel.UpdateBeatmapSet(beatmaps.QueryBeatmapSet(s => s.ID == b.BeatmapSetInfoID)); private void carouselBeatmapsLoaded() { bindBindables(); // If a selection was already obtained, do not attempt to update the selected beatmap. if (Carousel.SelectedBeatmapSet != null) return; // Attempt to select the current beatmap on the carousel, if it is valid to be selected. if (!Beatmap.IsDefault && Beatmap.Value.BeatmapSetInfo?.DeletePending == false && Beatmap.Value.BeatmapSetInfo?.Protected == false && Carousel.SelectBeatmap(Beatmap.Value.BeatmapInfo, false)) return; // If the current active beatmap could not be selected, select a new random beatmap. if (!Carousel.SelectNextRandom()) { // in the case random selection failed, we want to trigger selectionChanged // to show the dummy beatmap (we have nothing else to display). performUpdateSelected(); } } private bool boundLocalBindables; private void bindBindables() { if (boundLocalBindables) return; // manual binding to parent ruleset to allow for delayed load in the incoming direction. rulesetNoDebounce = decoupledRuleset.Value = Ruleset.Value; Ruleset.ValueChanged += r => updateSelectedRuleset(r.NewValue); decoupledRuleset.ValueChanged += r => Ruleset.Value = r.NewValue; decoupledRuleset.DisabledChanged += r => Ruleset.Disabled = r; Beatmap.BindDisabledChanged(disabled => Carousel.AllowSelection = !disabled, true); Beatmap.BindValueChanged(workingBeatmapChanged); boundLocalBindables = true; } private void delete(BeatmapSetInfo beatmap) { if (beatmap == null || beatmap.ID <= 0) return; dialogOverlay?.Push(new BeatmapDeleteDialog(beatmap)); } private void clearScores(BeatmapInfo beatmap) { if (beatmap == null || beatmap.ID <= 0) return; dialogOverlay?.Push(new BeatmapClearScoresDialog(beatmap, () => // schedule done here rather than inside the dialog as the dialog may fade out and never callback. Schedule(() => BeatmapDetails.Leaderboard.RefreshScores()))); } public virtual bool OnPressed(GlobalAction action) { if (!this.IsCurrentScreen()) return false; switch (action) { case GlobalAction.Select: FinaliseSelection(); return true; } return false; } public bool OnReleased(GlobalAction action) => action == GlobalAction.Select; protected override bool OnKeyDown(KeyDownEvent e) { if (e.Repeat) return false; switch (e.Key) { case Key.Delete: if (e.ShiftPressed) { if (!Beatmap.IsDefault) delete(Beatmap.Value.BeatmapSetInfo); return true; } break; } return base.OnKeyDown(e); } private class ResetScrollContainer : Container { private readonly Action onHoverAction; public ResetScrollContainer(Action onHoverAction) { this.onHoverAction = onHoverAction; } protected override bool OnHover(HoverEvent e) { onHoverAction?.Invoke(); return base.OnHover(e); } } } }
/* Copyright 2012 Michael Edwards Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //-CRE- using System; using System.Collections.Generic; using System.Linq; using System.Text; using Glass.Mapper.Sc.Configuration; using Glass.Mapper.Sc.Fields; using Sitecore.Data; using Sitecore.Data.Fields; using Sitecore.Data.Items; using Sitecore.Links; namespace Glass.Mapper.Sc.DataMappers { /// <summary> /// Class SitecoreFieldLinkMapper /// </summary> public class SitecoreFieldLinkMapper : AbstractSitecoreFieldMapper { private readonly IUrlOptionsResolver _urlOptionsResolver; /// <summary> /// Initializes a new instance of the <see cref="SitecoreFieldLinkMapper"/> class. /// </summary> public SitecoreFieldLinkMapper() : this(new UrlOptionsResolver()) { } public SitecoreFieldLinkMapper(IUrlOptionsResolver urlOptionsResolver) : base(typeof(Link)) { _urlOptionsResolver = urlOptionsResolver; } /// <summary> /// Sets the field value. /// </summary> /// <param name="value">The value.</param> /// <param name="config">The config.</param> /// <param name="context">The context.</param> /// <returns>System.String.</returns> /// <exception cref="System.NotImplementedException"></exception> public override string SetFieldValue(object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context) { throw new NotImplementedException(); } /// <summary> /// Gets the field value. /// </summary> /// <param name="fieldValue">The field value.</param> /// <param name="config">The config.</param> /// <param name="context">The context.</param> /// <returns>System.Object.</returns> /// <exception cref="System.NotImplementedException"></exception> public override object GetFieldValue(string fieldValue, SitecoreFieldConfiguration config, SitecoreDataMappingContext context) { throw new NotImplementedException(); } /// <summary> /// Gets the field. /// </summary> /// <param name="field">The field.</param> /// <param name="config">The config.</param> /// <param name="context">The context.</param> /// <returns>System.Object.</returns> public override object GetField(Sitecore.Data.Fields.Field field, SitecoreFieldConfiguration config, SitecoreDataMappingContext context) { if (field == null || field.Value.Trim().IsNullOrEmpty()) return null; Link link = new Link(); LinkField linkField = new LinkField(field); link.Anchor = linkField.Anchor; link.Class = linkField.Class; link.Text = linkField.Text; link.Title = linkField.Title; link.Target = linkField.Target; link.Query = linkField.QueryString; switch (linkField.LinkType) { case "anchor": link.Url = linkField.Anchor; link.Type = LinkType.Anchor; break; case "external": link.Url = linkField.Url; link.Type = LinkType.External; break; case "mailto": link.Url = linkField.Url; link.Type = LinkType.MailTo; break; case "javascript": link.Url = linkField.Url; link.Type = LinkType.JavaScript; break; case "media": if (linkField.TargetItem == null) link.Url = string.Empty; else { global::Sitecore.Data.Items.MediaItem media = new global::Sitecore.Data.Items.MediaItem(linkField.TargetItem); link.Url = global::Sitecore.Resources.Media.MediaManager.GetMediaUrl(media); } link.Type = LinkType.Media; link.TargetId = linkField.TargetID.Guid; break; case "internal": var urlOptions = _urlOptionsResolver.CreateUrlOptions(config.UrlOptions); link.Url = linkField.TargetItem == null ? string.Empty : LinkManager.GetItemUrl(linkField.TargetItem, urlOptions); link.Type = LinkType.Internal; link.TargetId = linkField.TargetID.Guid; link.Text = linkField.Text.IsNullOrEmpty() ? (linkField.TargetItem == null ? string.Empty : linkField.TargetItem.DisplayName) : linkField.Text; break; default: return null; } return link; } /// <summary> /// Sets the field. /// </summary> /// <param name="field">The field.</param> /// <param name="value">The value.</param> /// <param name="config">The config.</param> /// <param name="context">The context.</param> /// <exception cref="Glass.Mapper.MapperException"> /// No item with ID {0}. Can not update Link linkField.Formatted(newId) /// or /// No item with ID {0}. Can not update Link linkField.Formatted(newId) /// </exception> public override void SetField(Field field, object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context) { Link link = value as Link; if (field == null) return; var item = field.Item; LinkField linkField = new LinkField(field); if (link == null || link.Type == LinkType.NotSet) { linkField.Clear(); return; } switch (link.Type) { case LinkType.Internal: linkField.LinkType = "internal"; if (linkField.TargetID.Guid != link.TargetId) { if (link.TargetId == Guid.Empty) { ItemLink iLink = new ItemLink(item.Database.Name, item.ID, linkField.InnerField.ID, linkField.TargetItem.Database.Name, linkField.TargetID, linkField.TargetItem.Paths.FullPath); linkField.RemoveLink(iLink); } else { ID newId = new ID(link.TargetId); Item target = item.Database.GetItem(newId); if (target != null) { linkField.TargetID = newId; ItemLink nLink = new ItemLink(item.Database.Name, item.ID, linkField.InnerField.ID, target.Database.Name, target.ID, target.Paths.FullPath); linkField.UpdateLink(nLink); linkField.Url = LinkManager.GetItemUrl(target); } else throw new MapperException("No item with ID {0}. Can not update Link linkField".Formatted(newId)); } } break; case LinkType.Media: linkField.LinkType = "media"; if (linkField.TargetID.Guid != link.TargetId) { if (link.TargetId == Guid.Empty) { ItemLink iLink = new ItemLink(item.Database.Name, item.ID, linkField.InnerField.ID, linkField.TargetItem.Database.Name, linkField.TargetID, linkField.TargetItem.Paths.FullPath); linkField.RemoveLink(iLink); } else { ID newId = new ID(link.TargetId); Item target = item.Database.GetItem(newId); if (target != null) { global::Sitecore.Data.Items.MediaItem media = new global::Sitecore.Data.Items.MediaItem(target); linkField.TargetID = newId; ItemLink nLink = new ItemLink(item.Database.Name, item.ID, linkField.InnerField.ID, target.Database.Name, target.ID, target.Paths.FullPath); linkField.UpdateLink(nLink); linkField.Url = global::Sitecore.Resources.Media.MediaManager.GetMediaUrl(media); } else throw new MapperException("No item with ID {0}. Can not update Link linkField".Formatted(newId)); } } break; case LinkType.External: linkField.LinkType = "external"; linkField.Url = link.Url; break; case LinkType.Anchor: linkField.LinkType = "anchor"; linkField.Url = link.Anchor; break; case LinkType.MailTo: linkField.LinkType = "mailto"; linkField.Url = link.Url; break; case LinkType.JavaScript: linkField.LinkType = "javascript"; linkField.Url = link.Url; break; } if (!link.Anchor.IsNullOrEmpty()) linkField.Anchor = link.Anchor; if (!link.Class.IsNullOrEmpty()) linkField.Class = link.Class; if (!link.Text.IsNullOrEmpty()) linkField.Text = link.Text; if (!link.Title.IsNullOrEmpty()) linkField.Title = link.Title; if (!link.Query.IsNullOrEmpty()) linkField.QueryString = link.Query; if (!link.Target.IsNullOrEmpty()) linkField.Target = link.Target; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // The BigNumber class implements methods for formatting and parsing // big numeric values. To format and parse numeric values, applications should // use the Format and Parse methods provided by the numeric // classes (BigInteger). Those // Format and Parse methods share a common implementation // provided by this class, and are thus documented in detail here. // // Formatting // // The Format methods provided by the numeric classes are all of the // form // // public static String Format(XXX value, String format); // public static String Format(XXX value, String format, NumberFormatInfo info); // // where XXX is the name of the particular numeric class. The methods convert // the numeric value to a string using the format string given by the // format parameter. If the format parameter is null or // an empty string, the number is formatted as if the string "G" (general // format) was specified. The info parameter specifies the // NumberFormatInfo instance to use when formatting the number. If the // info parameter is null or omitted, the numeric formatting information // is obtained from the current culture. The NumberFormatInfo supplies // such information as the characters to use for decimal and thousand // separators, and the spelling and placement of currency symbols in monetary // values. // // Format strings fall into two categories: Standard format strings and // user-defined format strings. A format string consisting of a single // alphabetic character (A-Z or a-z), optionally followed by a sequence of // digits (0-9), is a standard format string. All other format strings are // used-defined format strings. // // A standard format string takes the form Axx, where A is an // alphabetic character called the format specifier and xx is a // sequence of digits called the precision specifier. The format // specifier controls the type of formatting applied to the number and the // precision specifier controls the number of significant digits or decimal // places of the formatting operation. The following table describes the // supported standard formats. // // C c - Currency format. The number is // converted to a string that represents a currency amount. The conversion is // controlled by the currency format information of the NumberFormatInfo // used to format the number. The precision specifier indicates the desired // number of decimal places. If the precision specifier is omitted, the default // currency precision given by the NumberFormatInfo is used. // // D d - Decimal format. This format is // supported for integral types only. The number is converted to a string of // decimal digits, prefixed by a minus sign if the number is negative. The // precision specifier indicates the minimum number of digits desired in the // resulting string. If required, the number will be left-padded with zeros to // produce the number of digits given by the precision specifier. // // E e Engineering (scientific) format. // The number is converted to a string of the form // "-d.ddd...E+ddd" or "-d.ddd...e+ddd", where each // 'd' indicates a digit (0-9). The string starts with a minus sign if the // number is negative, and one digit always precedes the decimal point. The // precision specifier indicates the desired number of digits after the decimal // point. If the precision specifier is omitted, a default of 6 digits after // the decimal point is used. The format specifier indicates whether to prefix // the exponent with an 'E' or an 'e'. The exponent is always consists of a // plus or minus sign and three digits. // // F f Fixed point format. The number is // converted to a string of the form "-ddd.ddd....", where each // 'd' indicates a digit (0-9). The string starts with a minus sign if the // number is negative. The precision specifier indicates the desired number of // decimal places. If the precision specifier is omitted, the default numeric // precision given by the NumberFormatInfo is used. // // G g - General format. The number is // converted to the shortest possible decimal representation using fixed point // or scientific format. The precision specifier determines the number of // significant digits in the resulting string. If the precision specifier is // omitted, the number of significant digits is determined by the type of the // number being converted (10 for int, 19 for long, 7 for // float, 15 for double, 19 for Currency, and 29 for // Decimal). Trailing zeros after the decimal point are removed, and the // resulting string contains a decimal point only if required. The resulting // string uses fixed point format if the exponent of the number is less than // the number of significant digits and greater than or equal to -4. Otherwise, // the resulting string uses scientific format, and the case of the format // specifier controls whether the exponent is prefixed with an 'E' or an // 'e'. // // N n Number format. The number is // converted to a string of the form "-d,ddd,ddd.ddd....", where // each 'd' indicates a digit (0-9). The string starts with a minus sign if the // number is negative. Thousand separators are inserted between each group of // three digits to the left of the decimal point. The precision specifier // indicates the desired number of decimal places. If the precision specifier // is omitted, the default numeric precision given by the // NumberFormatInfo is used. // // X x - Hexadecimal format. This format is // supported for integral types only. The number is converted to a string of // hexadecimal digits. The format specifier indicates whether to use upper or // lower case characters for the hexadecimal digits above 9 ('X' for 'ABCDEF', // and 'x' for 'abcdef'). The precision specifier indicates the minimum number // of digits desired in the resulting string. If required, the number will be // left-padded with zeros to produce the number of digits given by the // precision specifier. // // Some examples of standard format strings and their results are shown in the // table below. (The examples all assume a default NumberFormatInfo.) // // Value Format Result // 12345.6789 C $12,345.68 // -12345.6789 C ($12,345.68) // 12345 D 12345 // 12345 D8 00012345 // 12345.6789 E 1.234568E+004 // 12345.6789 E10 1.2345678900E+004 // 12345.6789 e4 1.2346e+004 // 12345.6789 F 12345.68 // 12345.6789 F0 12346 // 12345.6789 F6 12345.678900 // 12345.6789 G 12345.6789 // 12345.6789 G7 12345.68 // 123456789 G7 1.234568E8 // 12345.6789 N 12,345.68 // 123456789 N4 123,456,789.0000 // 0x2c45e x 2c45e // 0x2c45e X 2C45E // 0x2c45e X8 0002C45E // // Format strings that do not start with an alphabetic character, or that start // with an alphabetic character followed by a non-digit, are called // user-defined format strings. The following table describes the formatting // characters that are supported in user defined format strings. // // // 0 - Digit placeholder. If the value being // formatted has a digit in the position where the '0' appears in the format // string, then that digit is copied to the output string. Otherwise, a '0' is // stored in that position in the output string. The position of the leftmost // '0' before the decimal point and the rightmost '0' after the decimal point // determines the range of digits that are always present in the output // string. // // # - Digit placeholder. If the value being // formatted has a digit in the position where the '#' appears in the format // string, then that digit is copied to the output string. Otherwise, nothing // is stored in that position in the output string. // // . - Decimal point. The first '.' character // in the format string determines the location of the decimal separator in the // formatted value; any additional '.' characters are ignored. The actual // character used as a the decimal separator in the output string is given by // the NumberFormatInfo used to format the number. // // , - Thousand separator and number scaling. // The ',' character serves two purposes. First, if the format string contains // a ',' character between two digit placeholders (0 or #) and to the left of // the decimal point if one is present, then the output will have thousand // separators inserted between each group of three digits to the left of the // decimal separator. The actual character used as a the decimal separator in // the output string is given by the NumberFormatInfo used to format the // number. Second, if the format string contains one or more ',' characters // immediately to the left of the decimal point, or after the last digit // placeholder if there is no decimal point, then the number will be divided by // 1000 times the number of ',' characters before it is formatted. For example, // the format string '0,,' will represent 100 million as just 100. Use of the // ',' character to indicate scaling does not also cause the formatted number // to have thousand separators. Thus, to scale a number by 1 million and insert // thousand separators you would use the format string '#,##0,,'. // // % - Percentage placeholder. The presence of // a '%' character in the format string causes the number to be multiplied by // 100 before it is formatted. The '%' character itself is inserted in the // output string where it appears in the format string. // // E+ E- e+ e- - Scientific notation. // If any of the strings 'E+', 'E-', 'e+', or 'e-' are present in the format // string and are immediately followed by at least one '0' character, then the // number is formatted using scientific notation with an 'E' or 'e' inserted // between the number and the exponent. The number of '0' characters following // the scientific notation indicator determines the minimum number of digits to // output for the exponent. The 'E+' and 'e+' formats indicate that a sign // character (plus or minus) should always precede the exponent. The 'E-' and // 'e-' formats indicate that a sign character should only precede negative // exponents. // // \ - Literal character. A backslash character // causes the next character in the format string to be copied to the output // string as-is. The backslash itself isn't copied, so to place a backslash // character in the output string, use two backslashes (\\) in the format // string. // // 'ABC' "ABC" - Literal string. Characters // enclosed in single or double quotation marks are copied to the output string // as-is and do not affect formatting. // // ; - Section separator. The ';' character is // used to separate sections for positive, negative, and zero numbers in the // format string. // // Other - All other characters are copied to // the output string in the position they appear. // // For fixed point formats (formats not containing an 'E+', 'E-', 'e+', or // 'e-'), the number is rounded to as many decimal places as there are digit // placeholders to the right of the decimal point. If the format string does // not contain a decimal point, the number is rounded to the nearest // integer. If the number has more digits than there are digit placeholders to // the left of the decimal point, the extra digits are copied to the output // string immediately before the first digit placeholder. // // For scientific formats, the number is rounded to as many significant digits // as there are digit placeholders in the format string. // // To allow for different formatting of positive, negative, and zero values, a // user-defined format string may contain up to three sections separated by // semicolons. The results of having one, two, or three sections in the format // string are described in the table below. // // Sections: // // One - The format string applies to all values. // // Two - The first section applies to positive values // and zeros, and the second section applies to negative values. If the number // to be formatted is negative, but becomes zero after rounding according to // the format in the second section, then the resulting zero is formatted // according to the first section. // // Three - The first section applies to positive // values, the second section applies to negative values, and the third section // applies to zeros. The second section may be left empty (by having no // characters between the semicolons), in which case the first section applies // to all non-zero values. If the number to be formatted is non-zero, but // becomes zero after rounding according to the format in the first or second // section, then the resulting zero is formatted according to the third // section. // // For both standard and user-defined formatting operations on values of type // float and double, if the value being formatted is a NaN (Not // a Number) or a positive or negative infinity, then regardless of the format // string, the resulting string is given by the NaNSymbol, // PositiveInfinitySymbol, or NegativeInfinitySymbol property of // the NumberFormatInfo used to format the number. // // Parsing // // The Parse methods provided by the numeric classes are all of the form // // public static XXX Parse(String s); // public static XXX Parse(String s, int style); // public static XXX Parse(String s, int style, NumberFormatInfo info); // // where XXX is the name of the particular numeric class. The methods convert a // string to a numeric value. The optional style parameter specifies the // permitted style of the numeric string. It must be a combination of bit flags // from the NumberStyles enumeration. The optional info parameter // specifies the NumberFormatInfo instance to use when parsing the // string. If the info parameter is null or omitted, the numeric // formatting information is obtained from the current culture. // // Numeric strings produced by the Format methods using the Currency, // Decimal, Engineering, Fixed point, General, or Number standard formats // (the C, D, E, F, G, and N format specifiers) are guaranteed to be parseable // by the Parse methods if the NumberStyles.Any style is // specified. Note, however, that the Parse methods do not accept // NaNs or Infinities. // namespace System.Numerics { using System; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; using System.Security; using System.Text; using Conditional = System.Diagnostics.ConditionalAttribute; internal static class BigNumber { #if !SILVERLIGHT || FEATURE_NETCORE private const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | NumberStyles.AllowExponent | NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier); internal struct BigNumberBuffer { public StringBuilder digits; public int precision; public int scale; public bool sign; // negative sign exists public static BigNumberBuffer Create() { BigNumberBuffer number = new BigNumberBuffer(); number.digits = new StringBuilder(); return number; } } internal static bool TryValidateParseStyleInteger(NumberStyles style, out ArgumentException e) { // Check for undefined flags if ((style & InvalidNumberStyles) != 0) { e = new ArgumentException(SR.GetString(SR.Argument_InvalidNumberStyles, "style")); return false; } if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number if ((style & ~NumberStyles.HexNumber) != 0) { e = new ArgumentException(SR.GetString(SR.Argument_InvalidHexStyle)); return false; } } e = null; return true; } [SecuritySafeCritical] internal unsafe static Boolean TryParseBigInteger(String value, NumberStyles style, NumberFormatInfo info, out BigInteger result) { result = BigInteger.Zero; ArgumentException e; if (!TryValidateParseStyleInteger(style, out e)) throw e; // TryParse still throws ArgumentException on invalid NumberStyles BigNumberBuffer bignumber = BigNumberBuffer.Create(); Byte * numberBufferBytes = stackalloc Byte[Number.NumberBuffer.NumberBufferBytes]; Number.NumberBuffer number = new Number.NumberBuffer(numberBufferBytes); result = 0; if (!Number.TryStringToNumber(value, style, ref number, bignumber.digits, info, false)) { return false; } bignumber.precision = number.precision; bignumber.scale = number.scale; bignumber.sign = number.sign; if ((style & NumberStyles.AllowHexSpecifier) != 0) { if (!HexNumberToBigInteger(ref bignumber, ref result)) { return false; } } else { if (!NumberToBigInteger(ref bignumber, ref result)) { return false; } } return true; } internal unsafe static BigInteger ParseBigInteger(String value, NumberStyles style, NumberFormatInfo info) { if (value == null) throw new ArgumentNullException("value"); ArgumentException e; if (!TryValidateParseStyleInteger(style, out e)) throw e; BigInteger result = BigInteger.Zero; if (!TryParseBigInteger(value, style, info, out result)) { throw new FormatException(SR.GetString(SR.Overflow_ParseBigInteger)); } return result; } private unsafe static Boolean HexNumberToBigInteger(ref BigNumberBuffer number, ref BigInteger value) { if (number.digits == null || number.digits.Length == 0) return false; int len = number.digits.Length - 1; // ignore trailing '\0' byte[] bits = new byte[(len / 2) + (len % 2)]; bool shift = false; bool isNegative = false; int bitIndex = 0; // parse the string into a little-endian two's complement byte array // string value : O F E B 7 \0 // string index (i) : 0 1 2 3 4 5 <-- // byte[] (bitIndex): 2 1 1 0 0 <-- // for (int i = len-1; i > -1; i--) { char c = number.digits[i]; byte b; if (c >= '0' && c <= '9') { b = (byte)(c - '0'); } else if (c >= 'A' && c <= 'F') { b = (byte)((c - 'A') + 10); } else { Contract.Assert(c >= 'a' && c <= 'f'); b = (byte)((c - 'a') + 10); } if (i == 0 && (b & 0x08) == 0x08) isNegative = true; if (shift) { bits[bitIndex] = (byte)(bits[bitIndex] | (b << 4)); bitIndex++; } else { bits[bitIndex] = isNegative ? (byte)(b | 0xF0) : (b); } shift = !shift; } value = new BigInteger(bits); return true; } private unsafe static Boolean NumberToBigInteger(ref BigNumberBuffer number, ref BigInteger value) { Int32 i = number.scale; Int32 cur = 0; value = 0; while (--i >= 0) { value *= 10; if (number.digits[cur] != '\0') { value += (Int32)(number.digits[cur++] - '0'); } } while (number.digits[cur] != '\0') { if (number.digits[cur++] != '0') return false; // disallow non-zero trailing decimal places } if (number.sign) { value = -value; } return true; } #endif //!SILVERLIGHT ||FEATURE_NETCORE // this function is consistent with VM\COMNumber.cpp!COMNumber::ParseFormatSpecifier internal static char ParseFormatSpecifier(String format, out Int32 digits) { digits = -1; if (String.IsNullOrEmpty(format)) { return 'R'; } int i = 0; char ch = format[i]; if (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z') { i++; int n = -1; if (i < format.Length && format[i] >= '0' && format[i] <= '9') { n = format[i++] - '0'; while (i < format.Length && format[i] >= '0' && format[i] <= '9') { n = n * 10 + (format[i++] - '0'); if (n >= 10) break; } } if (i >= format.Length || format[i] == '\0') { digits = n; return ch; } } return (char)0; // custom format } private static String FormatBigIntegerToHexString(BigInteger value, char format, int digits, NumberFormatInfo info) { StringBuilder sb = new StringBuilder(); byte[] bits = value.ToByteArray(); String fmt = null; int cur = bits.Length-1; if (cur > -1) { // [FF..F8] drop the high F as the two's complement negative number remains clear // [F7..08] retain the high bits as the two's complement number is wrong without it // [07..00] drop the high 0 as the two's complement positive number remains clear bool clearHighF = false; byte head = bits[cur]; if (head > 0xF7) { head -= 0xF0; clearHighF = true; } if (head < 0x08 || clearHighF) { // {0xF8-0xFF} print as {8-F} // {0x00-0x07} print as {0-7} fmt = String.Format(CultureInfo.InvariantCulture, "{0}1", format); sb.Append(head.ToString(fmt, info)); cur--; } } if (cur > -1) { fmt = String.Format(CultureInfo.InvariantCulture, "{0}2", format); while (cur > -1) { sb.Append(bits[cur--].ToString(fmt, info)); } } if (digits > 0 && digits > sb.Length) { // insert leading zeros. User specified "X5" so we create "0ABCD" instead of "ABCD" sb.Insert(0, (value._sign >= 0 ? ("0") : (format == 'x' ? "f" : "F")), digits - sb.Length); } return sb.ToString(); } // // internal [unsafe] static String FormatBigInteger(BigInteger value, String format, NumberFormatInfo info) { // #if !SILVERLIGHT ||FEATURE_NETCORE [SecuritySafeCritical] #endif // !SILVERLIGHT ||FEATURE_NETCORE internal #if !SILVERLIGHT ||FEATURE_NETCORE unsafe #endif //!SILVERLIGHT ||FEATURE_NETCORE static String FormatBigInteger(BigInteger value, String format, NumberFormatInfo info) { int digits = 0; char fmt = ParseFormatSpecifier(format, out digits); if (fmt == 'x' || fmt == 'X') return FormatBigIntegerToHexString(value, fmt, digits, info); bool decimalFmt = (fmt == 'g' || fmt == 'G' || fmt == 'd' || fmt == 'D' || fmt == 'r' || fmt == 'R'); #if SILVERLIGHT ||FEATURE_NETCORE || MONO if (!decimalFmt) { // Silverlight supports invariant formats only throw new FormatException(SR.GetString(SR.Format_InvalidFormatSpecifier)); } #endif //SILVERLIGHT ||FEATURE_NETCORE || MONO if (value._bits == null) { if (fmt == 'g' || fmt == 'G' || fmt == 'r' || fmt == 'R') { if (digits > 0) format = String.Format(CultureInfo.InvariantCulture, "D{0}", digits.ToString(CultureInfo.InvariantCulture)); else format = "D"; } return value._sign.ToString(format, info); } // First convert to base 10^9. const uint kuBase = 1000000000; // 10^9 const int kcchBase = 9; int cuSrc = BigInteger.Length(value._bits); int cuMax; try { cuMax = checked(cuSrc * 10 / 9 + 2); } catch (OverflowException e) { throw new FormatException(SR.GetString(SR.Format_TooLarge), e); } uint[] rguDst = new uint[cuMax]; int cuDst = 0; for (int iuSrc = cuSrc; --iuSrc >= 0; ) { uint uCarry = value._bits[iuSrc]; for (int iuDst = 0; iuDst < cuDst; iuDst++) { Contract.Assert(rguDst[iuDst] < kuBase); ulong uuRes = NumericsHelpers.MakeUlong(rguDst[iuDst], uCarry); rguDst[iuDst] = (uint)(uuRes % kuBase); uCarry = (uint)(uuRes / kuBase); } if (uCarry != 0) { rguDst[cuDst++] = uCarry % kuBase; uCarry /= kuBase; if (uCarry != 0) rguDst[cuDst++] = uCarry; } } int cchMax; try { // Each uint contributes at most 9 digits to the decimal representation. cchMax = checked(cuDst * kcchBase); } catch (OverflowException e) { throw new FormatException(SR.GetString(SR.Format_TooLarge), e); } if (decimalFmt) { if (digits > 0 && digits > cchMax) cchMax = digits; if (value._sign < 0) { try { // Leave an extra slot for a minus sign. cchMax = checked(cchMax + info.NegativeSign.Length); } catch (OverflowException e) { throw new FormatException(SR.GetString(SR.Format_TooLarge), e); } } } int rgchBufSize; try { // We'll pass the rgch buffer to native code, which is going to treat it like a string of digits, so it needs // to be null terminated. Let's ensure that we can allocate a buffer of that size. rgchBufSize = checked(cchMax + 1); } catch (OverflowException e) { throw new FormatException(SR.GetString(SR.Format_TooLarge), e); } char[] rgch = new char[rgchBufSize]; int ichDst = cchMax; for (int iuDst = 0; iuDst < cuDst - 1; iuDst++) { uint uDig = rguDst[iuDst]; Contract.Assert(uDig < kuBase); for (int cch = kcchBase; --cch >= 0; ) { rgch[--ichDst] = (char)('0' + uDig % 10); uDig /= 10; } } for (uint uDig = rguDst[cuDst - 1]; uDig != 0; ) { rgch[--ichDst] = (char)('0' + uDig % 10); uDig /= 10; } #if !SILVERLIGHT ||FEATURE_NETCORE if (!decimalFmt) { // // Go to the VM for GlobLoc aware formatting // Byte * numberBufferBytes = stackalloc Byte[Number.NumberBuffer.NumberBufferBytes]; Number.NumberBuffer number = new Number.NumberBuffer(numberBufferBytes); // sign = true for negative and false for 0 and positive values number.sign = (value._sign < 0); // the cut-off point to switch (G)eneral from (F)ixed-point to (E)xponential form number.precision = 29; number.digits[0] = '\0'; number.scale = cchMax - ichDst; int maxDigits = Math.Min(ichDst + 50, cchMax); for (int i = ichDst; i < maxDigits; i++) { number.digits[i - ichDst] = rgch[i]; } fixed(char* pinnedExtraDigits = rgch) { return Number.FormatNumberBuffer(number.PackForNative(), format, info, pinnedExtraDigits + ichDst); } } #endif //!SILVERLIGHT ||FEATURE_NETCORE // Format Round-trip decimal // This format is supported for integral types only. The number is converted to a string of // decimal digits (0-9), prefixed by a minus sign if the number is negative. The precision // specifier indicates the minimum number of digits desired in the resulting string. If required, // the number is padded with zeros to its left to produce the number of digits given by the // precision specifier. int numDigitsPrinted = cchMax - ichDst; while (digits > 0 && digits > numDigitsPrinted) { // pad leading zeros rgch[--ichDst] = '0'; digits--; } if (value._sign < 0) { String negativeSign = info.NegativeSign; for (int i = info.NegativeSign.Length - 1; i > -1; i--) rgch[--ichDst] = info.NegativeSign[i]; } return new String(rgch, ichDst, cchMax - ichDst); } } }
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Debugger.Common; using Debugger.SbProcessRpc; using Google.Protobuf; using Grpc.Core; using LldbApi; using System.Collections.Concurrent; using System.Threading.Tasks; namespace DebuggerGrpcServer { // Server implementation of SBProcess RPC. class SbProcessRpcServiceImpl : SbProcessRpcService.SbProcessRpcServiceBase { readonly ConcurrentDictionary<int, SbProcess> processStore; readonly ObjectStore<SbUnixSignals> signalsStore; readonly ObjectStore<RemoteThread> threadStore; readonly RemoteThreadImpl.Factory remoteThreadFactory; public SbProcessRpcServiceImpl(ConcurrentDictionary<int, SbProcess> processStore, ObjectStore<RemoteThread> threadStore, RemoteThreadImpl.Factory remoteThreadFactory, ObjectStore<SbUnixSignals> signalsStore) { this.processStore = processStore; this.threadStore = threadStore; this.remoteThreadFactory = remoteThreadFactory; this.signalsStore = signalsStore; } #region SbProcessRpcService.SbProcessRpcServiceBase public override Task<GetTargetResponse> GetTarget(GetTargetRequest request, ServerCallContext context) { SbProcess sbProcess = GrpcLookupUtils.GetProcess(request.Process, processStore); var target = sbProcess.GetTarget(); var grpcSbThread = new GrpcSbTarget { Id = target.GetId() }; return Task.FromResult(new GetTargetResponse { Target = grpcSbThread }); } // Get the total number of threads in the thread list. public override Task<GetNumThreadsResponse> GetNumThreads(GetNumThreadsRequest request, ServerCallContext context) { SbProcess sbProcess = GrpcLookupUtils.GetProcess(request.Process, processStore); int numberThreads = sbProcess.GetNumThreads(); return Task.FromResult(new GetNumThreadsResponse { NumberThreads = numberThreads }); } // Get a thread at the specified index in the thread list. public override Task<GetThreadAtIndexResponse> GetThreadAtIndex( GetThreadAtIndexRequest request, ServerCallContext context) { var sbProcess = GrpcLookupUtils.GetProcess(request.Process, processStore); var sbThread = sbProcess.GetThreadAtIndex(request.Index); var grpcSbThread = new GrpcSbThread(); if (sbThread != null) { var remoteThread = remoteThreadFactory.Create(sbThread); grpcSbThread.Id = threadStore.AddObject(remoteThread); } return Task.FromResult(new GetThreadAtIndexResponse { Thread = grpcSbThread }); } // Returns the currently selected thread. public override Task<GetSelectedThreadResponse> GetSelectedThread( GetSelectedThreadRequest request, ServerCallContext context) { var sbProcess = GrpcLookupUtils.GetProcess(request.Process, processStore); var sbThread = sbProcess.GetSelectedThread(); var grpcSbThread = new GrpcSbThread(); if (sbThread != null) { var remoteThread = remoteThreadFactory.Create(sbThread); grpcSbThread.Id = threadStore.AddObject(remoteThread); } return Task.FromResult(new GetSelectedThreadResponse { Thread = grpcSbThread }); } // Continues the process. // Returns true if successful, false otherwise. public override Task<ContinueResponse> Continue(ContinueRequest request, ServerCallContext contest) { var sbProcess = GrpcLookupUtils.GetProcess(request.Process, processStore); var result = sbProcess.Continue(); return Task.FromResult(new ContinueResponse { Result = result }); } // Pauses the process. // Retruns true is successful, false otherwise. public override Task<StopResponse> Stop(StopRequest request, ServerCallContext context) { var sbProcess = GrpcLookupUtils.GetProcess(request.Process, processStore); var result = sbProcess.Stop(); return Task.FromResult(new StopResponse { Result = result }); } // Kills the process. // Returns true if successful, false otherwise. public override Task<KillResponse> Kill(KillRequest request, ServerCallContext context) { var sbProcess = GrpcLookupUtils.GetProcess(request.Process, processStore); var result = sbProcess.Kill(); return Task.FromResult(new KillResponse { Result = result }); } // Detaches the process. // Retruns true if successful, false otherwise. public override Task<DetachResponse> Detach(DetachRequest request, ServerCallContext context) { var sbProcess = GrpcLookupUtils.GetProcess(request.Process, processStore); var result = sbProcess.Detach(); return Task.FromResult(new DetachResponse { Result = result }); } public override Task<SetSelectedThreadByIdResponse> SetSelectedThreadById( SetSelectedThreadByIdRequest request, ServerCallContext context) { var sbProcess = GrpcLookupUtils.GetProcess(request.Process, processStore); var success = sbProcess.SetSelectedThreadById(request.ThreadId); return Task.FromResult(new SetSelectedThreadByIdResponse { Success = success }); } public override Task<GetUnixSignalsResponse> GetUnixSignals( GetUnixSignalsRequest request, ServerCallContext context) { var sbProcess = GrpcLookupUtils.GetProcess(request.Process, processStore); var signals = sbProcess.GetUnixSignals(); var response = new GetUnixSignalsResponse(); if (signals != null) { response.Signals = new GrpcSbUnixSignals { Id = signalsStore.AddObject(signals) }; } return Task.FromResult(response); } public override Task<ReadMemoryResponse> ReadMemory( ReadMemoryRequest request, ServerCallContext context) { var sbProcess = GrpcLookupUtils.GetProcess(request.Process, processStore); var buffer = new byte[request.Size]; SbError error; var sizeRead = sbProcess.ReadMemory( request.Address, buffer, request.Size, out error); var response = new ReadMemoryResponse { Error = new GrpcSbError { Success = error.Success(), Error = error.GetCString(), }, Memory = ByteString.CopyFrom(buffer), Size = sizeRead }; return Task.FromResult(response); } public override Task<WriteMemoryResponse> WriteMemory( WriteMemoryRequest reqeust, ServerCallContext context) { var sbProcess = GrpcLookupUtils.GetProcess(reqeust.Process, processStore); SbError error; var sizeWrote = sbProcess.WriteMemory(reqeust.Address, reqeust.Buffer.ToByteArray(), reqeust.Size, out error); return Task.FromResult(new WriteMemoryResponse { Error = new GrpcSbError { Success = error.Success(), Error = error.GetCString() }, Size = sizeWrote }); } public override Task<SaveCoreResponse> SaveCore( SaveCoreRequest request, ServerCallContext context) { var sbProcess = GrpcLookupUtils.GetProcess(request.Process, processStore); SbError error = sbProcess.SaveCore(request.DumpPath); return Task.FromResult(new SaveCoreResponse { Error = new GrpcSbError { Success = error.Success(), Error = error.GetCString() }, }); } #endregion } }
using System; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Text; namespace Lucene.Net.Search { /* * 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 AtomicReader = Lucene.Net.Index.AtomicReader; using BinaryDocValues = Lucene.Net.Index.BinaryDocValues; using IBits = Lucene.Net.Util.IBits; using BytesRef = Lucene.Net.Util.BytesRef; using NumericUtils = Lucene.Net.Util.NumericUtils; using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator; using SortedDocValues = Lucene.Net.Index.SortedDocValues; using SortedSetDocValues = Lucene.Net.Index.SortedSetDocValues; using Terms = Lucene.Net.Index.Terms; using TermsEnum = Lucene.Net.Index.TermsEnum; /// <summary> /// Expert: Maintains caches of term values. /// /// <para/>Created: May 19, 2004 11:13:14 AM /// <para/> /// @lucene.internal /// <para/> /// @since lucene 1.4 </summary> /// <seealso cref="Lucene.Net.Util.FieldCacheSanityChecker"/> public interface IFieldCache { /// <summary> /// Checks the internal cache for an appropriate entry, and if none is found, /// reads the terms in <paramref name="field"/> and returns a bit set at the size of /// <c>reader.MaxDoc</c>, with turned on bits for each docid that /// does have a value for this field. /// </summary> IBits GetDocsWithField(AtomicReader reader, string field); /// <summary> /// Checks the internal cache for an appropriate entry, and if none is /// found, reads the terms in <paramref name="field"/> as a single <see cref="byte"/> and returns an array /// of size <c>reader.MaxDoc</c> of the value each document /// has in the given field. </summary> /// <param name="reader"> Used to get field values. </param> /// <param name="field"> Which field contains the single <see cref="byte"/> values. </param> /// <param name="setDocsWithField"> If true then <see cref="GetDocsWithField(AtomicReader, string)"/> will /// also be computed and stored in the <see cref="IFieldCache"/>. </param> /// <returns> The values in the given field for each document. </returns> /// <exception cref="IOException"> If any error occurs. </exception> [Obsolete("(4.4) Index as a numeric field using Int32Field and then use GetInt32s(AtomicReader, string, bool) instead.")] FieldCache.Bytes GetBytes(AtomicReader reader, string field, bool setDocsWithField); /// <summary> /// Checks the internal cache for an appropriate entry, and if none is found, /// reads the terms in <paramref name="field"/> as bytes and returns an array of /// size <c>reader.MaxDoc</c> of the value each document has in the /// given field. </summary> /// <param name="reader"> Used to get field values. </param> /// <param name="field"> Which field contains the <see cref="byte"/>s. </param> /// <param name="parser"> Computes <see cref="byte"/> for string values. </param> /// <param name="setDocsWithField"> If true then <see cref="GetDocsWithField(AtomicReader, string)"/> will /// also be computed and stored in the <see cref="IFieldCache"/>. </param> /// <returns> The values in the given field for each document. </returns> /// <exception cref="IOException"> If any error occurs. </exception> [Obsolete("(4.4) Index as a numeric field using Int32Field and then use GetInt32s(AtomicReader, string, bool) instead.")] FieldCache.Bytes GetBytes(AtomicReader reader, string field, FieldCache.IByteParser parser, bool setDocsWithField); /// <summary> /// Checks the internal cache for an appropriate entry, and if none is /// found, reads the terms in <paramref name="field"/> as <see cref="short"/>s and returns an array /// of size <c>reader.MaxDoc</c> of the value each document /// has in the given field. /// <para/> /// NOTE: this was getShorts() in Lucene /// </summary> /// <param name="reader"> Used to get field values. </param> /// <param name="field"> Which field contains the <see cref="short"/>s. </param> /// <param name="setDocsWithField"> If true then <see cref="GetDocsWithField(AtomicReader, string)"/> will /// also be computed and stored in the <see cref="IFieldCache"/>. </param> /// <returns> The values in the given field for each document. </returns> /// <exception cref="IOException"> If any error occurs. </exception> [Obsolete("(4.4) Index as a numeric field using Int32Field and then use GetInt32s(AtomicReader, string, bool) instead.")] FieldCache.Int16s GetInt16s(AtomicReader reader, string field, bool setDocsWithField); /// <summary> /// Checks the internal cache for an appropriate entry, and if none is found, /// reads the terms in <paramref name="field"/> as shorts and returns an array of /// size <c>reader.MaxDoc</c> of the value each document has in the /// given field. /// <para/> /// NOTE: this was getShorts() in Lucene /// </summary> /// <param name="reader"> Used to get field values. </param> /// <param name="field"> Which field contains the <see cref="short"/>s. </param> /// <param name="parser"> Computes <see cref="short"/> for string values. </param> /// <param name="setDocsWithField"> If true then <see cref="GetDocsWithField(AtomicReader, string)"/> will /// also be computed and stored in the <see cref="IFieldCache"/>. </param> /// <returns> The values in the given field for each document. </returns> /// <exception cref="IOException"> If any error occurs. </exception> [Obsolete("(4.4) Index as a numeric field using Int32Field and then use GetInt32s(AtomicReader, string, bool) instead.")] FieldCache.Int16s GetInt16s(AtomicReader reader, string field, FieldCache.IInt16Parser parser, bool setDocsWithField); /// <summary> /// Returns an <see cref="FieldCache.Int32s"/> over the values found in documents in the given /// field. /// <para/> /// NOTE: this was getInts() in Lucene /// </summary> /// <seealso cref="GetInt32s(AtomicReader, string, FieldCache.IInt32Parser, bool)"/> FieldCache.Int32s GetInt32s(AtomicReader reader, string field, bool setDocsWithField); /// <summary> /// Returns an <see cref="FieldCache.Int32s"/> over the values found in documents in the given /// field. If the field was indexed as <see cref="Documents.NumericDocValuesField"/>, it simply /// uses <see cref="AtomicReader.GetNumericDocValues(string)"/> to read the values. /// Otherwise, it checks the internal cache for an appropriate entry, and if /// none is found, reads the terms in <paramref name="field"/> as <see cref="int"/>s and returns /// an array of size <c>reader.MaxDoc</c> of the value each document /// has in the given field. /// <para/> /// NOTE: this was getInts() in Lucene /// </summary> /// <param name="reader"> /// Used to get field values. </param> /// <param name="field"> /// Which field contains the <see cref="int"/>s. </param> /// <param name="parser"> /// Computes <see cref="int"/> for string values. May be <c>null</c> if the /// requested field was indexed as <see cref="Documents.NumericDocValuesField"/> or /// <see cref="Documents.Int32Field"/>. </param> /// <param name="setDocsWithField"> /// If true then <see cref="GetDocsWithField(AtomicReader, string)"/> will also be computed and /// stored in the <see cref="IFieldCache"/>. </param> /// <returns> The values in the given field for each document. </returns> /// <exception cref="IOException"> /// If any error occurs. </exception> FieldCache.Int32s GetInt32s(AtomicReader reader, string field, FieldCache.IInt32Parser parser, bool setDocsWithField); /// <summary> /// Returns a <see cref="FieldCache.Singles"/> over the values found in documents in the given /// field. /// <para/> /// NOTE: this was getFloats() in Lucene /// </summary> /// <seealso cref="GetSingles(AtomicReader, string, FieldCache.ISingleParser, bool)"/> FieldCache.Singles GetSingles(AtomicReader reader, string field, bool setDocsWithField); /// <summary> /// Returns a <see cref="FieldCache.Singles"/> over the values found in documents in the given /// field. If the field was indexed as <see cref="Documents.NumericDocValuesField"/>, it simply /// uses <see cref="AtomicReader.GetNumericDocValues(string)"/> to read the values. /// Otherwise, it checks the internal cache for an appropriate entry, and if /// none is found, reads the terms in <paramref name="field"/> as <see cref="float"/>s and returns /// an array of size <c>reader.MaxDoc</c> of the value each document /// has in the given field. /// <para/> /// NOTE: this was getFloats() in Lucene /// </summary> /// <param name="reader"> /// Used to get field values. </param> /// <param name="field"> /// Which field contains the <see cref="float"/>s. </param> /// <param name="parser"> /// Computes <see cref="float"/> for string values. May be <c>null</c> if the /// requested field was indexed as <see cref="Documents.NumericDocValuesField"/> or /// <see cref="Documents.SingleField"/>. </param> /// <param name="setDocsWithField"> /// If true then <see cref="GetDocsWithField(AtomicReader, string)"/> will also be computed and /// stored in the <see cref="IFieldCache"/>. </param> /// <returns> The values in the given field for each document. </returns> /// <exception cref="IOException"> /// If any error occurs. </exception> FieldCache.Singles GetSingles(AtomicReader reader, string field, FieldCache.ISingleParser parser, bool setDocsWithField); /// <summary> /// Returns a <see cref="FieldCache.Int64s"/> over the values found in documents in the given /// field. /// <para/> /// NOTE: this was getLongs() in Lucene /// </summary> /// <seealso cref="GetInt64s(AtomicReader, string, FieldCache.IInt64Parser, bool)"/> FieldCache.Int64s GetInt64s(AtomicReader reader, string field, bool setDocsWithField); /// <summary> /// Returns a <see cref="FieldCache.Int64s"/> over the values found in documents in the given /// field. If the field was indexed as <see cref="Documents.NumericDocValuesField"/>, it simply /// uses <see cref="AtomicReader.GetNumericDocValues(string)"/> to read the values. /// Otherwise, it checks the internal cache for an appropriate entry, and if /// none is found, reads the terms in <paramref name="field"/> as <see cref="long"/>s and returns /// an array of size <c>reader.MaxDoc</c> of the value each document /// has in the given field. /// <para/> /// NOTE: this was getLongs() in Lucene /// </summary> /// <param name="reader"> /// Used to get field values. </param> /// <param name="field"> /// Which field contains the <see cref="long"/>s. </param> /// <param name="parser"> /// Computes <see cref="long"/> for string values. May be <c>null</c> if the /// requested field was indexed as <see cref="Documents.NumericDocValuesField"/> or /// <see cref="Documents.Int64Field"/>. </param> /// <param name="setDocsWithField"> /// If true then <see cref="GetDocsWithField(AtomicReader, string)"/> will also be computed and /// stored in the <see cref="IFieldCache"/>. </param> /// <returns> The values in the given field for each document. </returns> /// <exception cref="IOException"> /// If any error occurs. </exception> FieldCache.Int64s GetInt64s(AtomicReader reader, string field, FieldCache.IInt64Parser parser, bool setDocsWithField); /// <summary> /// Returns a <see cref="FieldCache.Doubles"/> over the values found in documents in the given /// field. /// </summary> /// <seealso cref="GetDoubles(AtomicReader, string, FieldCache.IDoubleParser, bool)"/> FieldCache.Doubles GetDoubles(AtomicReader reader, string field, bool setDocsWithField); /// <summary> /// Returns a <see cref="FieldCache.Doubles"/> over the values found in documents in the given /// field. If the field was indexed as <see cref="Documents.NumericDocValuesField"/>, it simply /// uses <see cref="AtomicReader.GetNumericDocValues(string)"/> to read the values. /// Otherwise, it checks the internal cache for an appropriate entry, and if /// none is found, reads the terms in <paramref name="field"/> as <see cref="double"/>s and returns /// an array of size <c>reader.MaxDoc</c> of the value each document /// has in the given field. /// </summary> /// <param name="reader"> /// Used to get field values. </param> /// <param name="field"> /// Which field contains the <see cref="double"/>s. </param> /// <param name="parser"> /// Computes <see cref="double"/> for string values. May be <c>null</c> if the /// requested field was indexed as <see cref="Documents.NumericDocValuesField"/> or /// <see cref="Documents.DoubleField"/>. </param> /// <param name="setDocsWithField"> /// If true then <see cref="GetDocsWithField(AtomicReader, string)"/> will also be computed and /// stored in the <see cref="IFieldCache"/>. </param> /// <returns> The values in the given field for each document. </returns> /// <exception cref="IOException"> /// If any error occurs. </exception> FieldCache.Doubles GetDoubles(AtomicReader reader, string field, FieldCache.IDoubleParser parser, bool setDocsWithField); /// <summary> /// Checks the internal cache for an appropriate entry, and if none /// is found, reads the term values in <paramref name="field"/> /// and returns a <see cref="BinaryDocValues"/> instance, providing a /// method to retrieve the term (as a <see cref="BytesRef"/>) per document. </summary> /// <param name="reader"> Used to get field values. </param> /// <param name="field"> Which field contains the strings. </param> /// <param name="setDocsWithField"> If true then <see cref="GetDocsWithField(AtomicReader, string)"/> will /// also be computed and stored in the <see cref="IFieldCache"/>. </param> /// <returns> The values in the given field for each document. </returns> /// <exception cref="IOException"> If any error occurs. </exception> BinaryDocValues GetTerms(AtomicReader reader, string field, bool setDocsWithField); /// <summary> /// Expert: just like <see cref="GetTerms(AtomicReader, string, bool)"/>, /// but you can specify whether more RAM should be consumed in exchange for /// faster lookups (default is "true"). Note that the /// first call for a given reader and field "wins", /// subsequent calls will share the same cache entry. /// </summary> BinaryDocValues GetTerms(AtomicReader reader, string field, bool setDocsWithField, float acceptableOverheadRatio); /// <summary> /// Checks the internal cache for an appropriate entry, and if none /// is found, reads the term values in <paramref name="field"/> /// and returns a <see cref="SortedDocValues"/> instance, /// providing methods to retrieve sort ordinals and terms /// (as a <see cref="BytesRef"/>) per document. </summary> /// <param name="reader"> Used to get field values. </param> /// <param name="field"> Which field contains the strings. </param> /// <returns> The values in the given field for each document. </returns> /// <exception cref="IOException"> If any error occurs. </exception> SortedDocValues GetTermsIndex(AtomicReader reader, string field); /// <summary> /// Expert: just like /// <see cref="GetTermsIndex(AtomicReader, string)"/>, but you can specify /// whether more RAM should be consumed in exchange for /// faster lookups (default is "true"). Note that the /// first call for a given reader and field "wins", /// subsequent calls will share the same cache entry. /// </summary> SortedDocValues GetTermsIndex(AtomicReader reader, string field, float acceptableOverheadRatio); /// <summary> /// Checks the internal cache for an appropriate entry, and if none is found, reads the term values /// in <paramref name="field"/> and returns a <see cref="SortedSetDocValues"/> instance, providing a method to retrieve /// the terms (as ords) per document. /// </summary> /// <param name="reader"> Used to build a <see cref="SortedSetDocValues"/> instance </param> /// <param name="field"> Which field contains the strings. </param> /// <returns> a <see cref="SortedSetDocValues"/> instance </returns> /// <exception cref="IOException"> If any error occurs. </exception> SortedSetDocValues GetDocTermOrds(AtomicReader reader, string field); // LUCENENET specific CacheEntry moved to FieldCache static class /// <summary> /// EXPERT: Generates an array of <see cref="FieldCache.CacheEntry"/> objects representing all items /// currently in the <see cref="IFieldCache"/>. /// <para> /// NOTE: These <see cref="FieldCache.CacheEntry"/> objects maintain a strong reference to the /// Cached Values. Maintaining references to a <see cref="FieldCache.CacheEntry"/> the <see cref="AtomicReader"/> /// associated with it has garbage collected will prevent the Value itself /// from being garbage collected when the Cache drops the <see cref="WeakReference"/>. /// </para> /// @lucene.experimental /// </summary> FieldCache.CacheEntry[] GetCacheEntries(); /// <summary> /// <para> /// EXPERT: Instructs the FieldCache to forcibly expunge all entries /// from the underlying caches. This is intended only to be used for /// test methods as a way to ensure a known base state of the Cache /// (with out needing to rely on GC to free <see cref="WeakReference"/>s). /// It should not be relied on for "Cache maintenance" in general /// application code. /// </para> /// @lucene.experimental /// </summary> void PurgeAllCaches(); /// <summary> /// Expert: drops all cache entries associated with this /// reader <see cref="Index.IndexReader.CoreCacheKey"/>. NOTE: this cache key must /// precisely match the reader that the cache entry is /// keyed on. If you pass a top-level reader, it usually /// will have no effect as Lucene now caches at the segment /// reader level. /// </summary> void PurgeByCacheKey(object coreCacheKey); /// <summary> /// If non-null, <see cref="FieldCacheImpl"/> will warn whenever /// entries are created that are not sane according to /// <see cref="Lucene.Net.Util.FieldCacheSanityChecker"/>. /// </summary> TextWriter InfoStream { set; get; } } public static class FieldCache { /// <summary> /// Field values as 8-bit signed bytes /// </summary> public abstract class Bytes { /// <summary> /// Return a single Byte representation of this field's value. /// </summary> public abstract byte Get(int docID); /// <summary> /// Zero value for every document /// </summary> public static readonly Bytes EMPTY = new EmptyBytes(); private sealed class EmptyBytes : Bytes { public override byte Get(int docID) { return 0; } } } /// <summary> /// Field values as 16-bit signed shorts /// <para/> /// NOTE: This was Shorts in Lucene /// </summary> public abstract class Int16s { /// <summary> /// Return a <see cref="short"/> representation of this field's value. /// </summary> public abstract short Get(int docID); /// <summary> /// Zero value for every document /// </summary> public static readonly Int16s EMPTY = new EmptyInt16s(); private sealed class EmptyInt16s : Int16s { public override short Get(int docID) { return 0; } } } /// <summary> /// Field values as 32-bit signed integers /// <para/> /// NOTE: This was Ints in Lucene /// </summary> public abstract class Int32s { /// <summary> /// Return an <see cref="int"/> representation of this field's value. /// </summary> public abstract int Get(int docID); /// <summary> /// Zero value for every document /// </summary> public static readonly Int32s EMPTY = new EmptyInt32s(); private sealed class EmptyInt32s : Int32s { public override int Get(int docID) { return 0; } } } /// <summary> /// Field values as 64-bit signed long integers /// <para/> /// NOTE: This was Longs in Lucene /// </summary> public abstract class Int64s { /// <summary> /// Return an <see cref="long"/> representation of this field's value. /// </summary> public abstract long Get(int docID); /// <summary> /// Zero value for every document /// </summary> public static readonly Int64s EMPTY = new EmptyInt64s(); private sealed class EmptyInt64s : Int64s { public override long Get(int docID) { return 0; } } } /// <summary> /// Field values as 32-bit floats /// <para/> /// NOTE: This was Floats in Lucene /// </summary> public abstract class Singles { /// <summary> /// Return an <see cref="float"/> representation of this field's value. /// </summary> public abstract float Get(int docID); /// <summary> /// Zero value for every document /// </summary> public static readonly Singles EMPTY = new EmptySingles(); private sealed class EmptySingles : Singles { public override float Get(int docID) { return 0; } } } /// <summary> /// Field values as 64-bit doubles /// </summary> public abstract class Doubles { /// <summary> /// Return a <see cref="double"/> representation of this field's value. /// </summary> /// <param name="docID"></param> public abstract double Get(int docID); /// <summary> /// Zero value for every document /// </summary> public static readonly Doubles EMPTY = new EmptyDoubles(); private sealed class EmptyDoubles : Doubles { public override double Get(int docID) { return 0; } } } /// <summary> /// Placeholder indicating creation of this cache is currently in-progress. /// </summary> public sealed class CreationPlaceholder { internal object Value { get; set; } } /// <summary> /// Marker interface as super-interface to all parsers. It /// is used to specify a custom parser to /// <see cref="SortField.SortField(string, IParser)"/>. /// </summary> public interface IParser { /// <summary> /// Pulls a <see cref="Index.TermsEnum"/> from the given <see cref="Index.Terms"/>. This method allows certain parsers /// to filter the actual <see cref="Index.TermsEnum"/> before the field cache is filled. /// </summary> /// <param name="terms">The <see cref="Index.Terms"/> instance to create the <see cref="Index.TermsEnum"/> from.</param> /// <returns>A possibly filtered <see cref="Index.TermsEnum"/> instance, this method must not return <c>null</c>.</returns> /// <exception cref="System.IO.IOException">If an <see cref="IOException"/> occurs</exception> TermsEnum TermsEnum(Terms terms); } /// <summary> /// Interface to parse bytes from document fields. /// </summary> /// <seealso cref="IFieldCache.GetBytes(AtomicReader, string, IByteParser, bool)"/> [Obsolete] public interface IByteParser : IParser { /// <summary> /// Return a single Byte representation of this field's value. /// </summary> byte ParseByte(BytesRef term); } /// <summary> /// Interface to parse <see cref="short"/>s from document fields. /// <para/> /// NOTE: This was ShortParser in Lucene /// </summary> /// <seealso cref="IFieldCache.GetInt16s(AtomicReader, string, IInt16Parser, bool)"/> [Obsolete] public interface IInt16Parser : IParser { /// <summary> /// Return a <see cref="short"/> representation of this field's value. /// <para/> /// NOTE: This was parseShort() in Lucene /// </summary> short ParseInt16(BytesRef term); } /// <summary> /// Interface to parse <see cref="int"/>s from document fields. /// <para/> /// NOTE: This was IntParser in Lucene /// </summary> /// <seealso cref="IFieldCache.GetInt32s(AtomicReader, string, IInt32Parser, bool)"/> public interface IInt32Parser : IParser { /// <summary> /// Return an <see cref="int"/> representation of this field's value. /// <para/> /// NOTE: This was parseInt() in Lucene /// </summary> int ParseInt32(BytesRef term); } /// <summary> /// Interface to parse <see cref="float"/>s from document fields. /// <para/> /// NOTE: This was FloatParser in Lucene /// </summary> public interface ISingleParser : IParser { /// <summary> /// Return an <see cref="float"/> representation of this field's value. /// <para/> /// NOTE: This was parseFloat() in Lucene /// </summary> float ParseSingle(BytesRef term); } /// <summary> /// Interface to parse <see cref="long"/> from document fields. /// <para/> /// NOTE: This was LongParser in Lucene /// </summary> /// <seealso cref="IFieldCache.GetInt64s(AtomicReader, string, IInt64Parser, bool)"/> public interface IInt64Parser : IParser { /// <summary> /// Return a <see cref="long"/> representation of this field's value. /// <para/> /// NOTE: This was parseLong() in Lucene /// </summary> long ParseInt64(BytesRef term); } /// <summary> /// Interface to parse <see cref="double"/>s from document fields. /// </summary> /// <seealso cref="IFieldCache.GetDoubles(AtomicReader, string, IDoubleParser, bool)"/> public interface IDoubleParser : IParser { /// <summary> /// Return an <see cref="double"/> representation of this field's value. /// </summary> double ParseDouble(BytesRef term); } /// <summary> /// Expert: The cache used internally by sorting and range query classes. /// </summary> public static IFieldCache DEFAULT = new FieldCacheImpl(); /// <summary> /// The default parser for byte values, which are encoded by <see cref="sbyte.ToString(string, IFormatProvider)"/> /// using <see cref="CultureInfo.InvariantCulture"/>. /// </summary> [Obsolete] public static readonly IByteParser DEFAULT_BYTE_PARSER = new ByteParser(); [Obsolete] private sealed class ByteParser : IByteParser { public byte ParseByte(BytesRef term) { // TODO: would be far better to directly parse from // UTF8 bytes... but really users should use // IntField, instead, which already decodes // directly from byte[] return (byte)sbyte.Parse(term.Utf8ToString(), CultureInfo.InvariantCulture); } public override string ToString() { return typeof(IFieldCache).FullName + ".DEFAULT_BYTE_PARSER"; } public TermsEnum TermsEnum(Terms terms) { return terms.GetIterator(null); } } /// <summary> /// The default parser for <see cref="short"/> values, which are encoded by <see cref="short.ToString(string, IFormatProvider)"/> /// using <see cref="CultureInfo.InvariantCulture"/>. /// <para/> /// NOTE: This was DEFAULT_SHORT_PARSER in Lucene /// </summary> [Obsolete] public static readonly IInt16Parser DEFAULT_INT16_PARSER = new Int16Parser(); [Obsolete] private sealed class Int16Parser : IInt16Parser { /// <summary> /// NOTE: This was parseShort() in Lucene /// </summary> public short ParseInt16(BytesRef term) { // TODO: would be far better to directly parse from // UTF8 bytes... but really users should use // IntField, instead, which already decodes // directly from byte[] return short.Parse(term.Utf8ToString(), NumberStyles.Integer, CultureInfo.InvariantCulture); } public override string ToString() { return typeof(IFieldCache).FullName + ".DEFAULT_INT16_PARSER"; } public TermsEnum TermsEnum(Terms terms) { return terms.GetIterator(null); } } /// <summary> /// The default parser for <see cref="int"/> values, which are encoded by <see cref="int.ToString(string, IFormatProvider)"/> /// using <see cref="CultureInfo.InvariantCulture"/>. /// <para/> /// NOTE: This was DEFAULT_INT_PARSER in Lucene /// </summary> [Obsolete] public static readonly IInt32Parser DEFAULT_INT32_PARSER = new Int32Parser(); [Obsolete] private sealed class Int32Parser : IInt32Parser { /// <summary> /// NOTE: This was parseInt() in Lucene /// </summary> public int ParseInt32(BytesRef term) { // TODO: would be far better to directly parse from // UTF8 bytes... but really users should use // IntField, instead, which already decodes // directly from byte[] return int.Parse(term.Utf8ToString(), NumberStyles.Integer, CultureInfo.InvariantCulture); } public TermsEnum TermsEnum(Terms terms) { return terms.GetIterator(null); } public override string ToString() { return typeof(IFieldCache).FullName + ".DEFAULT_INT32_PARSER"; } } /// <summary> /// The default parser for <see cref="float"/> values, which are encoded by <see cref="float.ToString(string, IFormatProvider)"/> /// using <see cref="CultureInfo.InvariantCulture"/>. /// <para/> /// NOTE: This was DEFAULT_FLOAT_PARSER in Lucene /// </summary> [Obsolete] public static readonly ISingleParser DEFAULT_SINGLE_PARSER = new SingleParser(); [Obsolete] private sealed class SingleParser : ISingleParser { /// <summary> /// NOTE: This was parseFloat() in Lucene /// </summary> public float ParseSingle(BytesRef term) { // TODO: would be far better to directly parse from // UTF8 bytes... but really users should use // FloatField, instead, which already decodes // directly from byte[] // LUCENENET: We parse to double first and then cast to float, which allows us to parse // double.MaxValue.ToString("R") (resulting in Infinity). This is how it worked in Java // and the TestFieldCache.TestInfoStream() test depends on this behavior to pass. // We also need to use the same logic as DEFAULT_DOUBLE_PARSER to ensure we have signed zero // support, so just call it directly rather than duplicating the logic here. return (float)DEFAULT_DOUBLE_PARSER.ParseDouble(term); } public TermsEnum TermsEnum(Terms terms) { return terms.GetIterator(null); } public override string ToString() { return typeof(IFieldCache).FullName + ".DEFAULT_SINGLE_PARSER"; } } /// <summary> /// The default parser for <see cref="long"/> values, which are encoded by <see cref="long.ToString(string, IFormatProvider)"/> /// using <see cref="CultureInfo.InvariantCulture"/>. /// <para/> /// NOTE: This was DEFAULT_LONG_PARSER in Lucene /// </summary> [Obsolete] public static readonly IInt64Parser DEFAULT_INT64_PARSER = new Int64Parser(); [Obsolete] private sealed class Int64Parser : IInt64Parser { /// <summary> /// NOTE: This was parseLong() in Lucene /// </summary> public long ParseInt64(BytesRef term) { // TODO: would be far better to directly parse from // UTF8 bytes... but really users should use // LongField, instead, which already decodes // directly from byte[] return long.Parse(term.Utf8ToString(), NumberStyles.Integer, CultureInfo.InvariantCulture); } public TermsEnum TermsEnum(Terms terms) { return terms.GetIterator(null); } public override string ToString() { return typeof(IFieldCache).FullName + ".DEFAULT_INT64_PARSER"; } } /// <summary> /// The default parser for <see cref="double"/> values, which are encoded by <see cref="double.ToString(string, IFormatProvider)"/> /// using <see cref="CultureInfo.InvariantCulture"/>. /// </summary> [Obsolete] public static readonly IDoubleParser DEFAULT_DOUBLE_PARSER = new DoubleParser(); [Obsolete] private sealed class DoubleParser : IDoubleParser { public double ParseDouble(BytesRef term) { // TODO: would be far better to directly parse from // UTF8 bytes... but really users should use // DoubleField, instead, which already decodes // directly from byte[] string text = term.Utf8ToString(); double value = double.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture); // LUCENENET specific special case - check whether a negative // zero was passed in and, if so, convert the sign. Unfotunately, double.Parse() // doesn't take care of this for us. if (value == 0 && text.TrimStart().StartsWith("-", StringComparison.Ordinal)) { value = -0d; // Hard-coding the value in case double.Parse() works right someday (which would break if we did value * -1) } return value; } public TermsEnum TermsEnum(Terms terms) { return terms.GetIterator(null); } public override string ToString() { return typeof(IFieldCache).FullName + ".DEFAULT_DOUBLE_PARSER"; } } /// <summary> /// A parser instance for <see cref="int"/> values encoded by <see cref="NumericUtils"/>, e.g. when indexed /// via <see cref="Documents.Int32Field"/>/<see cref="Analysis.NumericTokenStream"/>. /// <para/> /// NOTE: This was NUMERIC_UTILS_INT_PARSER in Lucene /// </summary> public static readonly IInt32Parser NUMERIC_UTILS_INT32_PARSER = new NumericUtilsInt32Parser(); private sealed class NumericUtilsInt32Parser : IInt32Parser { /// <summary> /// NOTE: This was parseInt() in Lucene /// </summary> public int ParseInt32(BytesRef term) { return NumericUtils.PrefixCodedToInt32(term); } public TermsEnum TermsEnum(Terms terms) { return NumericUtils.FilterPrefixCodedInt32s(terms.GetIterator(null)); } public override string ToString() { return typeof(IFieldCache).FullName + ".NUMERIC_UTILS_INT32_PARSER"; } } /// <summary> /// A parser instance for <see cref="float"/> values encoded with <see cref="NumericUtils"/>, e.g. when indexed /// via <see cref="Documents.SingleField"/>/<see cref="Analysis.NumericTokenStream"/>. /// <para/> /// NOTE: This was NUMERIC_UTILS_FLOAT_PARSER in Lucene /// </summary> public static readonly ISingleParser NUMERIC_UTILS_SINGLE_PARSER = new NumericUtilsSingleParser(); private sealed class NumericUtilsSingleParser : ISingleParser { /// <summary> /// NOTE: This was parseFloat() in Lucene /// </summary> public float ParseSingle(BytesRef term) { return NumericUtils.SortableInt32ToSingle(NumericUtils.PrefixCodedToInt32(term)); } public override string ToString() { return typeof(IFieldCache).FullName + ".NUMERIC_UTILS_SINGLE_PARSER"; } public TermsEnum TermsEnum(Terms terms) { return NumericUtils.FilterPrefixCodedInt32s(terms.GetIterator(null)); } } /// <summary> /// A parser instance for <see cref="long"/> values encoded by <see cref="NumericUtils"/>, e.g. when indexed /// via <see cref="Documents.Int64Field"/>/<see cref="Analysis.NumericTokenStream"/>. /// <para/> /// NOTE: This was NUMERIC_UTILS_LONG_PARSER in Lucene /// </summary> public static readonly IInt64Parser NUMERIC_UTILS_INT64_PARSER = new NumericUtilsInt64Parser(); private sealed class NumericUtilsInt64Parser : IInt64Parser { /// <summary> /// NOTE: This was parseLong() in Lucene /// </summary> public long ParseInt64(BytesRef term) { return NumericUtils.PrefixCodedToInt64(term); } public override string ToString() { return typeof(IFieldCache).FullName + ".NUMERIC_UTILS_INT64_PARSER"; } public TermsEnum TermsEnum(Terms terms) { return NumericUtils.FilterPrefixCodedInt64s(terms.GetIterator(null)); } } /// <summary> /// A parser instance for <see cref="double"/> values encoded with <see cref="NumericUtils"/>, e.g. when indexed /// via <see cref="Documents.DoubleField"/>/<see cref="Analysis.NumericTokenStream"/>. /// </summary> public static readonly IDoubleParser NUMERIC_UTILS_DOUBLE_PARSER = new NumericUtilsDoubleParser(); private sealed class NumericUtilsDoubleParser : IDoubleParser { public double ParseDouble(BytesRef term) { return NumericUtils.SortableInt64ToDouble(NumericUtils.PrefixCodedToInt64(term)); } public override string ToString() { return typeof(IFieldCache).FullName + ".NUMERIC_UTILS_DOUBLE_PARSER"; } public TermsEnum TermsEnum(Terms terms) { return NumericUtils.FilterPrefixCodedInt64s(terms.GetIterator(null)); } } // .NET Port: skipping down to about line 681 of java version. The actual interface methods of FieldCache are in IFieldCache below. /// <summary> /// EXPERT: A unique Identifier/Description for each item in the <see cref="IFieldCache"/>. /// Can be useful for logging/debugging. /// <para/> /// @lucene.experimental /// </summary> public sealed class CacheEntry { private readonly object readerKey; private readonly string fieldName; private readonly Type cacheType; private readonly object custom; private readonly object value; private string size; public CacheEntry(object readerKey, string fieldName, Type cacheType, object custom, object value) { this.readerKey = readerKey; this.fieldName = fieldName; this.cacheType = cacheType; this.custom = custom; this.value = value; } public object ReaderKey { get { return readerKey; } } public string FieldName { get { return fieldName; } } public Type CacheType { get { return cacheType; } } public object Custom { get { return custom; } } public object Value { get { return value; } } /// <summary> /// Computes (and stores) the estimated size of the cache <see cref="Value"/> /// </summary> /// <seealso cref="EstimatedSize"/> public void EstimateSize() { long bytesUsed = RamUsageEstimator.SizeOf(Value); size = RamUsageEstimator.HumanReadableUnits(bytesUsed); } /// <summary> /// The most recently estimated size of the value, <c>null</c> unless /// <see cref="EstimateSize()"/> has been called. /// </summary> public string EstimatedSize { get { return size; } } public override string ToString() { StringBuilder b = new StringBuilder(); b.Append("'").Append(ReaderKey).Append("'=>"); b.Append("'").Append(FieldName).Append("',"); b.Append(CacheType).Append(",").Append(Custom); b.Append("=>").Append(Value.GetType().FullName).Append("#"); b.Append(RuntimeHelpers.GetHashCode(Value)); String s = EstimatedSize; if (null != s) { b.Append(" (size =~ ").Append(s).Append(')'); } return b.ToString(); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source { public class EnumTests : CSharpTestBase { // The value of first enumerator, and the value of each successive enumerator [Fact] public void ValueOfFirst() { var text = @"enum Suits { ValueA, ValueB, ValueC, ValueD } "; VerifyEnumsValue(text, "Suits", 0, 1, 2, 3); } // The value can be explicated initialized [Fact] public void ExplicateInit() { var text = @"public enum Suits { ValueA = -1, ValueB = 2, ValueC = 3, ValueD = 4, }; "; VerifyEnumsValue(text, "Suits", -1, 2, 3, 4); } // The value can be explicated and implicit initialized [Fact] public void MixedInit() { var text = @"public enum Suits { ValueA, ValueB = 10, ValueC, ValueD, }; "; VerifyEnumsValue(text, "Suits", 0, 10, 11, 12); } // Enumerator initializers must be of integral or enumeration type [Fact] public void OutOfUnderlyingRange() { var text = @"public enum Suits : byte { ValueA = ""3"", // Can't implicitly convert ValueB = 2.2, // Can't implicitly convert ValueC = 257 // Out of underlying range }; "; var comp = CreateCompilationWithMscorlib(text); VerifyEnumsValue(comp, "Suits", SpecialType.System_Byte, null, null, null); text = @"enum Suits : short { a, b, c, d = -65536, e, f }"; comp = CreateCompilationWithMscorlib(text); VerifyEnumsValue(comp, "Suits", SpecialType.System_Int16, (short)0, (short)1, (short)2, null, null, null); } // Explicit associated value [Fact] public void ExplicitAssociated() { var text = @"class C<T> { const int field = 100; enum TestEnum { A, B = A, // another member C = D, // another member D = (byte)11, // type can be implicitly converted to underlying type E = 'a', // type can be implicitly converted to underlying type F = 3 + 5, // expression G = field, // const field TestEnum, // its own type name var, // contextual keyword T, // Type parameter }; enum EnumB { B = TestEnum.T }; } "; VerifyEnumsValue(text, "C.TestEnum", 0, 0, 11, 11, 97, 8, 100, 101, 102, 103); VerifyEnumsValue(text, "C.EnumB", 103); text = @"class c1 { public static int StaticField = 10; public static readonly int ReadonlyField = 100; enum EnumTest { A = StaticField, B = ReadonlyField }; } "; VerifyEnumsValue(text, "c1.EnumTest", null, null); } [WorkItem(539167, "DevDiv")] // No enum-body [Fact] public void CS1514ERR_LbraceExpected_NoEnumBody() { var text = @"enum Figure ;"; VerifyEnumsValue(text, "Figure"); var comp = CreateCompilationWithMscorlib(text); // Same errors as parsing "class Name ;". DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_LbraceExpected }, new ErrorDescription { Code = (int)ErrorCode.ERR_RbraceExpected }); } [Fact] public void EnumEOFBeforeMembers() { var text = @"enum E"; VerifyEnumsValue(text, "E"); var comp = CreateCompilationWithMscorlib(text); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_LbraceExpected }, new ErrorDescription { Code = (int)ErrorCode.ERR_RbraceExpected }); } [Fact] public void EnumEOFWithinMembers() { var text = @"enum E {"; VerifyEnumsValue(text, "E"); var comp = CreateCompilationWithMscorlib(text); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_RbraceExpected }); } // No enum-body [Fact] public void NullEnumBody() { var text = @"enum Figure { }"; VerifyEnumsValue(text, "Figure"); } // No identifier [Fact] public void CS1001ERR_IdentifierExpected_NoIDForEnum() { var text = @"enum { One, Two, Three };"; var comp = CreateCompilationWithMscorlib(text); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_IdentifierExpected }); } // Same identifier for enum members [Fact] public void CS0102ERR_DuplicateNameInClass_SameIDForEnum() { var text = @"enum TestEnum { One, One }"; VerifyEnumsValue(text, "TestEnum", 0, 1); var comp = CreateCompilationWithMscorlib(text); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInClass }); } // Modifiers for enum [Fact] public void CS0109WRN_NewNotRequired_ModifiersForEnum() { var text = @"class Program { protected enum Figure1 { One = 1 }; // OK new public enum Figure2 { Zero = 0 }; // new + protection modifier is OK abstract enum Figure3 { Zero }; // abstract not valid private private enum Figure4 { One = 1 }; // Duplicate modifier is not OK private public enum Figure5 { }; // More than one protection modifiers is not OK sealed enum Figure0 { Zero }; // sealed not valid new enum Figure { Zero }; // OK }"; //VerifyEnumsValue(text, "TestEnum", 0, 1); var comp = CreateCompilationWithMscorlib(text); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberProtection }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateModifier }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewNotRequired }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewNotRequired }); } [WorkItem(527757, "DevDiv")] // Modifiers for enum member [Fact()] public void CS1041ERR_IdentifierExpectedKW_ModifiersForEnumMember() { var text = @"enum ColorA { public Red } "; //VerifyEnumsValue(text, "ColorA", 0); var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (2,2): error CS1513: } expected // { Diagnostic(ErrorCode.ERR_RbraceExpected, ""), // (3,12): error CS0116: A namespace does not directly contain members such as fields or methods // public Red Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "Red"), // (4,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}")); text = @"enum ColorA { void foo() {} } "; VerifyEnumsValue(text, "ColorA", 0); var comp1 = CreateCompilationWithMscorlib(text); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp1.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_IdentifierExpectedKW }, new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected }, new ErrorDescription { Code = (int)ErrorCode.ERR_SyntaxError }); } // Flag Attribute and Enumerate a Enum [Fact] public void FlagOnEnum() { var text = @" [System.Flags] public enum Suits { ValueA = 1, ValueB = 2, ValueC = 4, ValueD = 8, Combi = ValueA | ValueB } "; VerifyEnumsValue(text, "Suits", 1, 2, 4, 8, 3); } // Customer Attribute on Enum declaration [Fact] public void AttributeOnEnum() { var text = @" class Attr1 : System.Attribute { } [Attr1] enum Figure { One, Two, Three }; "; VerifyEnumsValue(text, "Figure", 0, 1, 2); var comp = CreateCompilationWithMscorlib(text); DiagnosticsUtils.VerifyErrorCodes(comp.GetDiagnostics()); } // Convert integer to Enum instance [ClrOnlyFact(ClrOnlyReason.Unknown)] public void ConvertOnEnum() { var source = @" using System; class c1 { public enum Suits { ValueA = 1, ValueB = 2, ValueC = 4, ValueD = 2, ValueE = 2, } static void Main(string[] args) { Suits S = (Suits)Enum.ToObject(typeof(Suits), 2); Console.WriteLine(S.ToString()); // ValueE Suits S1 = (Suits)Enum.ToObject(typeof(Suits), -1); Console.WriteLine(S1.ToString()); // -1 } } "; VerifyEnumsValue(source, "c1.Suits", 1, 2, 4, 2, 2); CompileAndVerify(source, expectedOutput: @" ValueE -1 "); } // Enum used in switch [Fact] public void CS0152ERR_DuplicateCaseLabel_SwitchInEnum() { var source = @" class c1 { public enum Suits { ValueA, ValueB, ValueC, } public void main() { Suits s = Suits.ValueA; switch (s) { case Suits.ValueA: break; case Suits.ValueB: break; case Suits.ValueC: break; default: break; } } } "; var comp = CreateCompilationWithMscorlib(source); DiagnosticsUtils.VerifyErrorCodes(comp.GetDiagnostics()); source = @" class c1 { public enum Suits { ValueA = 2, ValueB, ValueC = 2, } public void main() { Suits s = Suits.ValueA; switch (s) { case Suits.ValueA: break; case Suits.ValueB: break; case Suits.ValueC: break; default: break; } } } "; comp = CreateCompilationWithMscorlib(source); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateCaseLabel }); } // The literal 0 implicitly converts to any enum type. [ClrOnlyFact] public void ZeroInEnum() { var source = @" using System; class c1 { enum Gender : byte { Male = 2 } static void Main(string[] args) { Gender s = 0; Console.WriteLine(s); s = -0; Console.WriteLine(s); s = 0.0e+999; Console.WriteLine(s); } } "; CompileAndVerify(source, expectedOutput: @" 0 0 0 "); } // Derived. [Fact] public void CS0527ERR_NonInterfaceInInterfaceList_DerivedFromEnum() { var text = @" enum A { Red } struct C : A{} interface D : A{} "; var comp = CreateCompilationWithMscorlib(text); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList }); } // Enums can Not be declared in nested enum declaration [Fact] public void CS1022ERR_EOFExpected_NestedFromEnum() { var text = @" public enum Num { { public enum Figure { Zero }; } } "; VerifyEnumsValue(text, "Num"); VerifyEnumsValue(text, "Figure", 0); var comp = CreateCompilationWithMscorlib(text); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected }, new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected }, new ErrorDescription { Code = (int)ErrorCode.ERR_IdentifierExpected }, new ErrorDescription { Code = (int)ErrorCode.ERR_RbraceExpected }); } // Enums can be declared anywhere [Fact] public void DeclEnum() { var text = @" namespace ns { enum Gender { Male } } struct B { enum Gender { Male } } "; VerifyEnumsValue(text, "ns.Gender", 0); VerifyEnumsValue(text, "B.Gender", 0); } // Enums obey local scope rules [Fact] public void DeclEnum_01() { var text = @" namespace ns { enum E1 { yes = 1, no = yes - 1 }; public class mine { public enum E1 { yes = 1, no = yes - 1 }; } } "; VerifyEnumsValue(text, "ns.E1", 1, 0); VerifyEnumsValue(text, "ns.mine.E1", 1, 0); } // Nullable Enums [Fact] public void NullableOfEnum() { var source = @" enum EnumA { }; enum EnumB : long { Num = 1000 }; class c1 { static public void Main(string[] args) { EnumA a = 0; EnumA? c = null; a = (EnumA)c; } } "; VerifyEnumsValue(source, "EnumB", 1000L); } // Operator on null and enum [Fact] public void OperatorOnNullableAndEnum() { var source = @"class c1 { MyEnum? e = null & MyEnum.One; } enum MyEnum { One }"; var comp = CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (3,17): warning CS0458: The result of the expression is always 'null' of type 'MyEnum?' // MyEnum? e = null & MyEnum.One; Diagnostic(ErrorCode.WRN_AlwaysNull, "null & MyEnum.One").WithArguments("MyEnum?") ); } [WorkItem(5030, "DevDiv_Projects/Roslyn")] // Operator on enum [Fact] public void CS0019ERR_BadBinaryOps_OperatorOnEnum() { var source = @" class c1 { static public void Main(string[] args) { Enum1 e1 = e1 + 5L; Enum2 e2 = e1 + e2; e1 = Enum1.A1 + Enum1.B1; bool b1 = e1 == 1; bool b7 = e1 == e2; e1++; // OK --e2; // OK e1 = e1 ^ Enum1.A1; // OK e1 ^= Enum1.B1; // OK var s = sizeof(Enum1); // OK } } public enum Enum1 { A1 = 1, B1 = 2 }; public enum Enum2 : byte { A2, B2 }; "; var comp = CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (6,20): error CS0019: Operator '+' cannot be applied to operands of type 'Enum1' and 'long' // Enum1 e1 = e1 + 5L; Diagnostic(ErrorCode.ERR_BadBinaryOps, "e1 + 5L").WithArguments("+", "Enum1", "long"), // (7,20): error CS0019: Operator '+' cannot be applied to operands of type 'Enum1' and 'Enum2' // Enum2 e2 = e1 + e2; Diagnostic(ErrorCode.ERR_BadBinaryOps, "e1 + e2").WithArguments("+", "Enum1", "Enum2"), // (8,14): error CS0019: Operator '+' cannot be applied to operands of type 'Enum1' and 'Enum1' // e1 = Enum1.A1 + Enum1.B1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "Enum1.A1 + Enum1.B1").WithArguments("+", "Enum1", "Enum1"), // (9,19): error CS0019: Operator '==' cannot be applied to operands of type 'Enum1' and 'int' // bool b1 = e1 == 1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "e1 == 1").WithArguments("==", "Enum1", "int"), // (10,19): error CS0019: Operator '==' cannot be applied to operands of type 'Enum1' and 'Enum2' // bool b7 = e1 == e2; Diagnostic(ErrorCode.ERR_BadBinaryOps, "e1 == e2").WithArguments("==", "Enum1", "Enum2"), // (6,20): error CS0165: Use of unassigned local variable 'e1' // Enum1 e1 = e1 + 5L; Diagnostic(ErrorCode.ERR_UseDefViolation, "e1").WithArguments("e1"), // (7,25): error CS0165: Use of unassigned local variable 'e2' // Enum2 e2 = e1 + e2; Diagnostic(ErrorCode.ERR_UseDefViolation, "e2").WithArguments("e2"), // (15,13): warning CS0219: The variable 's' is assigned but its value is never used // var s = sizeof(Enum1); // OK Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s").WithArguments("s")); } [WorkItem(5030, "DevDiv_Projects/Roslyn")] // Operator on enum member [ClrOnlyFact] public void OperatorOnEnumMember() { var source = @" using System; class c1 { static public void Main(string[] args) { E s = E.one; var b1 = E.three > E.two; var b2 = E.three < E.two; var b3 = E.three == E.two; var b4 = E.three != E.two; var b5 = s > E.two; var b6 = s < E.two; var b7 = s == E.two; var b8 = s != E.two; Console.WriteLine(b1); Console.WriteLine(b2); Console.WriteLine(b3); Console.WriteLine(b4); Console.WriteLine(b5); Console.WriteLine(b6); Console.WriteLine(b7); Console.WriteLine(b8); } } public enum E { one = 1, two = 2, three = 3 }; "; CompileAndVerify(source, expectedOutput: @" True False False True False True False True "); } // CLS-Compliant [Fact] public void CS3009WRN_CLS_BadBase_CLSCompliantOnEnum() { var text = @" [assembly: System.CLSCompliant(true)] public class c1 { public enum COLORS : uint { RED, GREEN, BLUE }; } "; var comp = CreateCompilationWithMscorlib(text); VerifyEnumsValue(comp, "c1.COLORS", SpecialType.System_UInt32, 0u, 1u, 2u); comp.VerifyDiagnostics( // (5,17): warning CS3009: 'c1.COLORS': base type 'uint' is not CLS-compliant // public enum COLORS : uint { RED, GREEN, BLUE }; Diagnostic(ErrorCode.WRN_CLS_BadBase, "COLORS").WithArguments("c1.COLORS", "uint")); } [WorkItem(539178, "DevDiv")] // No underlying type after ':' [Fact] public void CS3031ERR_TypeExpected_NoUnderlyingTypeForEnum() { var text = @"enum Figure : { One, Two, Three } "; var comp = CreateCompilationWithMscorlib(text); DiagnosticsUtils.VerifyErrorCodes(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_TypeExpected }, new ErrorDescription { Code = (int)ErrorCode.ERR_IntegralTypeExpected }); VerifyEnumsValue(comp, "Figure", SpecialType.System_Int32, 0, 1, 2); } [Fact] public void CS1008ERR_IntegralTypeExpected() { var text = @"enum Figure : System.Int16 { One, Two, Three } "; var comp = CreateCompilationWithMscorlib(text); DiagnosticsUtils.VerifyErrorCodes(comp.GetDiagnostics()); // ok VerifyEnumsValue(comp, "Figure", SpecialType.System_Int16, (short)0, (short)1, (short)2); text = @"class C { } enum Figure : C { One, Two, Three } "; comp = CreateCompilationWithMscorlib(text); DiagnosticsUtils.VerifyErrorCodes(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_IntegralTypeExpected }); VerifyEnumsValue(comp, "Figure", SpecialType.System_Int32, 0, 1, 2); } // 'partial' as Enum name [Fact] public void partialAsEnumName() { var text = @" partial class EnumPartial { internal enum partial { } partial M; } "; VerifyEnumsValue(text, "EnumPartial.partial"); var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (6,13): warning CS0169: The field 'EnumPartial.M' is never used // partial M; Diagnostic(ErrorCode.WRN_UnreferencedField, "M").WithArguments("EnumPartial.M") ); var classEnum = comp.SourceModule.GlobalNamespace.GetMembers("EnumPartial").Single() as NamedTypeSymbol; var member = classEnum.GetMembers("M").Single() as FieldSymbol; Assert.Equal(TypeKind.Enum, member.Type.TypeKind); } // Enum as an optional parameter [Fact] public void CS1763ERR_NotNullRefDefaultParameter_EnumAsOptionalParamete() { var text = @" enum ABC { a, b, c } class c1 { public int Foo(ABC o = ABC.a | ABC.b) { return 0; } public int Moo(object o = ABC.a) { return 1; } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (9,27): error CS1763: 'o' is of type 'object'. A default parameter value of a reference type other than string can only be initialized with null // public int Moo(object o = ABC.a) Diagnostic(ErrorCode.ERR_NotNullRefDefaultParameter, "o").WithArguments("o", "object")); } [WorkItem(540765, "DevDiv")] [Fact] public void TestInitializeWithEnumMemberEnumConst() { var text = @" class Test { public enum E0 : short { Member1 } const E0 e0 = E0.Member1; public enum E1 { Member1, Member2 = e1, Member3 = e0 } const E1 e1 = E1.Member1; }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics(); // No Errors } [WorkItem(540765, "DevDiv")] [Fact] public void TestInitializeWithEnumMemberEnumConst2() { var text = @" class Test { const E1 e = E1.Member1; public enum E1 { Member2 = e, Member1 } }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,14): error CS0110: The evaluation of the constant value for 'Test.e' involves a circular definition Diagnostic(ErrorCode.ERR_CircConstValue, "e").WithArguments("Test.e")); // No Errors } [WorkItem(540765, "DevDiv")] [Fact] public void TestInitializeWithEnumMemberEnumConst3() { var text = @" class Test { const E1 e = E1.Member1; public enum E1 { Member1, Member2 = e //fine } public enum E2 { Member = e //fine } public enum E3 { Member = (E3)e //CS0266 } public enum E4 { Member = (e) //fine } public enum E5 { Member = (e) + 1 //fine } }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (16,18): error CS0266: Cannot implicitly convert type 'Test.E3' to 'int'. An explicit conversion exists (are you missing a cast?) // Member = (E3)e Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "(E3)e").WithArguments("Test.E3", "int")); } [WorkItem(540771, "DevDiv")] [Fact] public void TestUseEnumMemberFromBaseGenericType() { var text = @" class Base<T, U> { public enum Enum1 { A, B, C } } class Derived<T, U> : Base<U, T> { const Enum1 E = Enum1.C; }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics(); // No Errors } [WorkItem(667303)] [Fact] public void TestFullNameForEnumBaseType() { var text = @"public enum Works1 : byte {} public enum Works2 : sbyte {} public enum Works3 : short {} public enum Works4 : ushort {} public enum Works5 : int {} public enum Works6 : uint {} public enum Works7 : long {} public enum Works8 : ulong {} public enum Breaks1 : System.Byte {} public enum Breaks2 : System.SByte {} public enum Breaks3 : System.Int16 {} public enum Breaks4 : System.UInt16 {} public enum Breaks5 : System.Int32 {} public enum Breaks6 : System.UInt32 {} public enum Breaks7 : System.Int64 {} public enum Breaks8 : System.UInt64 {}"; CreateCompilationWithMscorlib(text).VerifyDiagnostics(); // No Errors } [WorkItem(667303, "DevDiv")] [Fact] public void TestBadEnumBaseType() { var text = @"public enum Breaks1 : string {} public enum Breaks2 : System.String {}"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (1,23): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // public enum Breaks1 : string {} Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "string").WithLocation(1, 23), // (2,23): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // public enum Breaks2 : System.String {} Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "System.String").WithLocation(2, 23) ); } [WorkItem(750553, "DevDiv")] [Fact] public void InvalidEnumUnderlyingType() { var text = @"enum E1 : int[] { } enum E2 : int* { } enum E3 : dynamic { } class C<T> { enum E4 : T { } } "; var compilation = CreateCompilationWithMscorlib(text); compilation.VerifyDiagnostics( // (2,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // enum E2 : int* { } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*").WithLocation(2, 11), // (2,11): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum E2 : int* { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "int*").WithLocation(2, 11), // (3,11): error CS1980: Cannot define a class or member that utilizes 'dynamic' because the compiler required type 'System.Runtime.CompilerServices.DynamicAttribute' cannot be found. Are you missing a reference? // enum E3 : dynamic { } Diagnostic(ErrorCode.ERR_DynamicAttributeMissing, "dynamic").WithArguments("System.Runtime.CompilerServices.DynamicAttribute").WithLocation(3, 11), // (3,11): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum E3 : dynamic { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "dynamic").WithLocation(3, 11), // (1,11): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum E1 : int[] { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "int[]").WithLocation(1, 11), // (4,24): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // class C<T> { enum E4 : T { } } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "T").WithLocation(4, 24) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var diagnostics = model.GetDeclarationDiagnostics(); diagnostics.Verify( // (2,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // enum E2 : int* { } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*").WithLocation(2, 11), // (2,11): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum E2 : int* { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "int*").WithLocation(2, 11), // (1,11): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum E1 : int[] { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "int[]").WithLocation(1, 11), // (3,11): error CS1980: Cannot define a class or member that utilizes 'dynamic' because the compiler required type 'System.Runtime.CompilerServices.DynamicAttribute' cannot be found. Are you missing a reference? // enum E3 : dynamic { } Diagnostic(ErrorCode.ERR_DynamicAttributeMissing, "dynamic").WithArguments("System.Runtime.CompilerServices.DynamicAttribute").WithLocation(3, 11), // (3,11): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum E3 : dynamic { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "dynamic").WithLocation(3, 11), // (4,24): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // class C<T> { enum E4 : T { } } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "T").WithLocation(4, 24) ); var decls = tree.GetCompilationUnitRoot().DescendantNodes().OfType<EnumDeclarationSyntax>().ToArray(); Assert.Equal(decls.Length, 4); foreach (var decl in decls) { var symbol = model.GetDeclaredSymbol(decl); var type = symbol.EnumUnderlyingType; Assert.Equal(type.SpecialType, SpecialType.System_Int32); } } private List<Symbol> VerifyEnumsValue(string text, string enumName, params object[] expectedEnumValues) { var comp = CreateCompilationWithMscorlib(text); var specialType = SpecialType.System_Int32; if (expectedEnumValues.Length > 0) { var first = expectedEnumValues.First(); if (first != null && first.GetType() == typeof(long)) specialType = SpecialType.System_Int64; } return VerifyEnumsValue(comp, enumName, specialType, expectedEnumValues); } private List<Symbol> VerifyEnumsValue(CSharpCompilation comp, string enumName, SpecialType underlyingType, params object[] expectedEnumValues) { var global = comp.SourceModule.GlobalNamespace; var symEnum = GetSymbolByFullName(comp, enumName) as NamedTypeSymbol; Assert.NotNull(symEnum); var type = symEnum.EnumUnderlyingType; Assert.NotNull(type); Assert.Equal(underlyingType, type.SpecialType); var fields = symEnum.GetMembers().OfType<FieldSymbol>().Cast<Symbol>().ToList(); Assert.Equal(expectedEnumValues.Length, fields.Count); var count = 0; foreach (var item in fields) { var field = item as FieldSymbol; Assert.Equal(expectedEnumValues[count++], field.ConstantValue); } return fields; } private static Symbol GetSymbolByFullName(CSharpCompilation compilation, string memberName) { string[] names = memberName.Split('.'); Symbol currentSymbol = compilation.GlobalNamespace; foreach (var name in names) { Assert.True(currentSymbol is NamespaceOrTypeSymbol, string.Format("{0} does not have members", currentSymbol.ToTestDisplayString())); var currentContainer = (NamespaceOrTypeSymbol)currentSymbol; var members = currentContainer.GetMembers(name); Assert.True(members.Length > 0, string.Format("No members named {0} inside {1}", name, currentSymbol.ToTestDisplayString())); Assert.True(members.Length <= 1, string.Format("Multiple members named {0} inside {1}", name, currentSymbol.ToTestDisplayString())); currentSymbol = members.First(); } return currentSymbol; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Mithril_Kendo_WebApp.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using UnityEngine; namespace UnityStandardAssets.CinematicEffects { [ExecuteInEditMode] [RequireComponent(typeof(Camera))] [AddComponentMenu("Image Effects/Cinematic/Bloom")] #if UNITY_5_4_OR_NEWER [ImageEffectAllowedInSceneView] #endif public class Bloom : MonoBehaviour { [Serializable] public struct Settings { [SerializeField] [Tooltip("Filters out pixels under this level of brightness.")] public float threshold; public float thresholdGamma { set { threshold = value; } get { return Mathf.Max(0.0f, threshold); } } public float thresholdLinear { set { threshold = Mathf.LinearToGammaSpace(value); } get { return Mathf.GammaToLinearSpace(thresholdGamma); } } [SerializeField, Range(0, 1)] [Tooltip("Makes transition between under/over-threshold gradual.")] public float softKnee; [SerializeField, Range(1, 7)] [Tooltip("Changes extent of veiling effects in a screen resolution-independent fashion.")] public float radius; [SerializeField] [Tooltip("Blend factor of the result image.")] public float intensity; [SerializeField] [Tooltip("Controls filter quality and buffer resolution.")] public bool highQuality; [SerializeField] [Tooltip("Reduces flashing noise with an additional filter.")] public bool antiFlicker; [Tooltip("Dirtiness texture to add smudges or dust to the lens.")] public Texture dirtTexture; [Min(0f), Tooltip("Amount of lens dirtiness.")] public float dirtIntensity; public static Settings defaultSettings { get { var settings = new Settings { threshold = 0.9f, softKnee = 0.5f, radius = 2.0f, intensity = 0.7f, highQuality = true, antiFlicker = false, dirtTexture = null, dirtIntensity = 2.5f }; return settings; } } } #region Public Properties [SerializeField] public Settings settings = Settings.defaultSettings; #endregion [SerializeField, HideInInspector] private Shader m_Shader; public Shader shader { get { if (m_Shader == null) { const string shaderName = "Hidden/Image Effects/Cinematic/Bloom"; m_Shader = Shader.Find(shaderName); } return m_Shader; } } private Material m_Material; public Material material { get { if (m_Material == null) m_Material = ImageEffectHelper.CheckShaderAndCreateMaterial(shader); return m_Material; } } #region Private Members const int kMaxIterations = 16; RenderTexture[] m_blurBuffer1 = new RenderTexture[kMaxIterations]; RenderTexture[] m_blurBuffer2 = new RenderTexture[kMaxIterations]; int m_Threshold; int m_Curve; int m_PrefilterOffs; int m_SampleScale; int m_Intensity; int m_DirtTex; int m_DirtIntensity; int m_BaseTex; private void Awake() { m_Threshold = Shader.PropertyToID("_Threshold"); m_Curve = Shader.PropertyToID("_Curve"); m_PrefilterOffs = Shader.PropertyToID("_PrefilterOffs"); m_SampleScale = Shader.PropertyToID("_SampleScale"); m_Intensity = Shader.PropertyToID("_Intensity"); m_DirtTex = Shader.PropertyToID("_DirtTex"); m_DirtIntensity = Shader.PropertyToID("_DirtIntensity"); m_BaseTex = Shader.PropertyToID("_BaseTex"); } private void OnEnable() { if (!ImageEffectHelper.IsSupported(shader, true, false, this)) enabled = false; } private void OnDisable() { if (m_Material != null) DestroyImmediate(m_Material); m_Material = null; } private void OnRenderImage(RenderTexture source, RenderTexture destination) { var useRGBM = Application.isMobilePlatform; // source texture size var tw = source.width; var th = source.height; // halve the texture size for the low quality mode if (!settings.highQuality) { tw /= 2; th /= 2; } // blur buffer format var rtFormat = useRGBM ? RenderTextureFormat.Default : RenderTextureFormat.DefaultHDR; // determine the iteration count var logh = Mathf.Log(th, 2) + settings.radius - 8; var logh_i = (int)logh; var iterations = Mathf.Clamp(logh_i, 1, kMaxIterations); // update the shader properties var threshold = settings.thresholdLinear; material.SetFloat(m_Threshold, threshold); var knee = threshold * settings.softKnee + 1e-5f; var curve = new Vector3(threshold - knee, knee * 2, 0.25f / knee); material.SetVector(m_Curve, curve); var pfo = !settings.highQuality && settings.antiFlicker; material.SetFloat(m_PrefilterOffs, pfo ? -0.5f : 0.0f); material.SetFloat(m_SampleScale, 0.5f + logh - logh_i); material.SetFloat(m_Intensity, Mathf.Max(0.0f, settings.intensity)); bool useDirtTexture = false; if (settings.dirtTexture != null) { material.SetTexture(m_DirtTex, settings.dirtTexture); material.SetFloat(m_DirtIntensity, settings.dirtIntensity); useDirtTexture = true; } // prefilter pass var prefiltered = RenderTexture.GetTemporary(tw, th, 0, rtFormat); Graphics.Blit(source, prefiltered, material, settings.antiFlicker ? 1 : 0); // construct a mip pyramid var last = prefiltered; for (var level = 0; level < iterations; level++) { m_blurBuffer1[level] = RenderTexture.GetTemporary(last.width / 2, last.height / 2, 0, rtFormat); Graphics.Blit(last, m_blurBuffer1[level], material, level == 0 ? (settings.antiFlicker ? 3 : 2) : 4); last = m_blurBuffer1[level]; } // upsample and combine loop for (var level = iterations - 2; level >= 0; level--) { var basetex = m_blurBuffer1[level]; material.SetTexture(m_BaseTex, basetex); m_blurBuffer2[level] = RenderTexture.GetTemporary(basetex.width, basetex.height, 0, rtFormat); Graphics.Blit(last, m_blurBuffer2[level], material, settings.highQuality ? 6 : 5); last = m_blurBuffer2[level]; } // finish process int pass = useDirtTexture ? 9 : 7; pass += settings.highQuality ? 1 : 0; material.SetTexture(m_BaseTex, source); Graphics.Blit(last, destination, material, pass); // release the temporary buffers for (var i = 0; i < kMaxIterations; i++) { if (m_blurBuffer1[i] != null) RenderTexture.ReleaseTemporary(m_blurBuffer1[i]); if (m_blurBuffer2[i] != null) RenderTexture.ReleaseTemporary(m_blurBuffer2[i]); m_blurBuffer1[i] = null; m_blurBuffer2[i] = null; } RenderTexture.ReleaseTemporary(prefiltered); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Threading.Tasks; using System.Xml; using Microsoft.Build.BackEnd; using Microsoft.Build.BackEnd.SdkResolution; using Microsoft.Build.Collections; using Microsoft.Build.Engine.UnitTests.BackEnd; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using ElementLocation = Microsoft.Build.Construction.ElementLocation; using ILoggingService = Microsoft.Build.BackEnd.Logging.ILoggingService; using LegacyThreadingData = Microsoft.Build.Execution.LegacyThreadingData; using TargetDotNetFrameworkVersion = Microsoft.Build.Utilities.TargetDotNetFrameworkVersion; using ToolLocationHelper = Microsoft.Build.Utilities.ToolLocationHelper; using Xunit; using Xunit.Abstractions; namespace Microsoft.Build.UnitTests.BackEnd { /// <summary> /// Unit tests for the TaskBuilder component /// </summary> public class TaskBuilder_Tests : ITargetBuilderCallback { /// <summary> /// The mock component host and logger /// </summary> private MockHost _host; private readonly ITestOutputHelper _testOutput; /// <summary> /// The temporary project we use to run the test /// </summary> private ProjectInstance _testProject; /// <summary> /// Prepares the environment for the test. /// </summary> public TaskBuilder_Tests(ITestOutputHelper output) { _host = new MockHost(); _testOutput = output; _testProject = CreateTestProject(); } /********************************************************************************* * * OUTPUT PARAMS * *********************************************************************************/ /// <summary> /// Verifies that we do look up the task during execute when the condition is true. /// </summary> [Fact] public void TasksAreDiscoveredWhenTaskConditionTrue() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <NonExistantTask Condition=""'1'=='1'""/> <Message Text='Made it'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); project.Build("t", loggers); logger.AssertLogContains("MSB4036"); logger.AssertLogDoesntContain("Made it"); } /// <summary> /// Tests that when the task condition is false, Execute still returns true even though we never loaded /// the task. We verify that we never loaded the task because if we did try, the task load itself would /// have failed, resulting in an error. /// </summary> [Fact] public void TasksNotDiscoveredWhenTaskConditionFalse() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <NonExistantTask Condition=""'1'=='2'""/> <Message Text='Made it'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); project.Build("t", loggers); logger.AssertLogContains("Made it"); } /// <summary> /// Verify when task outputs are overridden the override messages are correctly displayed /// </summary> [Fact] public void OverridePropertiesInCreateProperty() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <ItemGroup> <EmbeddedResource Include='a.resx'> <LogicalName>foo</LogicalName> </EmbeddedResource> <EmbeddedResource Include='b.resx'> <LogicalName>bar</LogicalName> </EmbeddedResource> <EmbeddedResource Include='c.resx'> <LogicalName>barz</LogicalName> </EmbeddedResource> </ItemGroup> <Target Name='t'> <CreateProperty Value=""@(EmbeddedResource->'/assemblyresource:%(Identity),%(LogicalName)', ' ')"" Condition=""'%(LogicalName)' != '' ""> <Output TaskParameter=""Value"" PropertyName=""LinkSwitches""/> </CreateProperty> <Message Text='final:[$(LinkSwitches)]'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); project.Build("t", loggers); logger.AssertLogContains(new string[] { "final:[/assemblyresource:c.resx,barz]" }); logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("TaskStarted", "CreateProperty") }); logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:a.resx,foo", "/assemblyresource:b.resx,bar") }); logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:b.resx,bar", "/assemblyresource:c.resx,barz") }); } /// <summary> /// Verify that when a task outputs are inferred the override messages are displayed /// </summary> [Fact] public void OverridePropertiesInInferredCreateProperty() { string[] files = null; try { files = ObjectModelHelpers.GetTempFiles(2, new DateTime(2005, 1, 1)); MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <ItemGroup> <i Include='" + files[0] + "'><output>" + files[1] + @"</output></i> </ItemGroup> <ItemGroup> <EmbeddedResource Include='a.resx'> <LogicalName>foo</LogicalName> </EmbeddedResource> <EmbeddedResource Include='b.resx'> <LogicalName>bar</LogicalName> </EmbeddedResource> <EmbeddedResource Include='c.resx'> <LogicalName>barz</LogicalName> </EmbeddedResource> </ItemGroup> <Target Name='t2' DependsOnTargets='t'> <Message Text='final:[$(LinkSwitches)]'/> </Target> <Target Name='t' Inputs='%(i.Identity)' Outputs='%(i.Output)'> <Message Text='start:[Hello]'/> <CreateProperty Value=""@(EmbeddedResource->'/assemblyresource:%(Identity),%(LogicalName)', ' ')"" Condition=""'%(LogicalName)' != '' ""> <Output TaskParameter=""Value"" PropertyName=""LinkSwitches""/> </CreateProperty> <Message Text='end:[hello]'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); project.Build("t2", loggers); // We should only see messages from the second target, as the first is only inferred logger.AssertLogDoesntContain("start:"); logger.AssertLogDoesntContain("end:"); logger.AssertLogContains(new string[] { "final:[/assemblyresource:c.resx,barz]" }); logger.AssertLogDoesntContain(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("TaskStarted", "CreateProperty")); logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:a.resx,foo", "/assemblyresource:b.resx,bar") }); logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:b.resx,bar", "/assemblyresource:c.resx,barz") }); } finally { ObjectModelHelpers.DeleteTempFiles(files); } } /// <summary> /// Tests that tasks batch on outputs correctly. /// </summary> [Fact] public void TaskOutputBatching() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <ItemGroup> <TaskParameterItem Include=""foo""> <ParameterName>Value</ParameterName> <ParameterName2>Include</ParameterName2> <PropertyName>MetadataProperty</PropertyName> <ItemType>MetadataItem</ItemType> </TaskParameterItem> </ItemGroup> <Target Name='Build'> <CreateProperty Value=""@(TaskParameterItem)""> <Output TaskParameter=""Value"" PropertyName=""Property1""/> </CreateProperty> <Message Text='Property1=[$(Property1)]' /> <CreateProperty Value=""@(TaskParameterItem)""> <Output TaskParameter=""%(TaskParameterItem.ParameterName)"" PropertyName=""Property2""/> </CreateProperty> <Message Text='Property2=[$(Property2)]' /> <CreateProperty Value=""@(TaskParameterItem)""> <Output TaskParameter=""Value"" PropertyName=""%(TaskParameterItem.PropertyName)""/> </CreateProperty> <Message Text='MetadataProperty=[$(MetadataProperty)]' /> <CreateItem Include=""@(TaskParameterItem)""> <Output TaskParameter=""Include"" ItemName=""TestItem1""/> </CreateItem> <Message Text='TestItem1=[@(TestItem1)]' /> <CreateItem Include=""@(TaskParameterItem)""> <Output TaskParameter=""%(TaskParameterItem.ParameterName2)"" ItemName=""TestItem2""/> </CreateItem> <Message Text='TestItem2=[@(TestItem2)]' /> <CreateItem Include=""@(TaskParameterItem)""> <Output TaskParameter=""Include"" ItemName=""%(TaskParameterItem.ItemType)""/> </CreateItem> <Message Text='MetadataItem=[@(MetadataItem)]' /> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); project.Build(loggers); logger.AssertLogContains("Property1=[foo]"); logger.AssertLogContains("Property2=[foo]"); logger.AssertLogContains("MetadataProperty=[foo]"); logger.AssertLogContains("TestItem1=[foo]"); logger.AssertLogContains("TestItem2=[foo]"); logger.AssertLogContains("MetadataItem=[foo]"); } /// <summary> /// MSbuildLastTaskResult property contains true or false indicating /// the success or failure of the last task. /// </summary> [Fact] public void MSBuildLastTaskResult() { string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project DefaultTargets='t2' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <Message Text='[start:$(MSBuildLastTaskResult)]'/> <!-- Should be blank --> <Warning Text='warning'/> <Message Text='[0:$(MSBuildLastTaskResult)]'/> <!-- Should be true, only a warning--> <!-- task's Execute returns false --> <Copy SourceFiles='|' DestinationFolder='c:\' ContinueOnError='true' /> <PropertyGroup> <p>$(MSBuildLastTaskResult)</p> </PropertyGroup> <Message Text='[1:$(MSBuildLastTaskResult)]'/> <!-- Should be false: propertygroup did not reset it --> <Message Text='[p:$(p)]'/> <!-- Should be false as stored earlier --> <Message Text='[2:$(MSBuildLastTaskResult)]'/> <!-- Message succeeded, should now be true --> </Target> <Target Name='t2' DependsOnTargets='t'> <Message Text='[3:$(MSBuildLastTaskResult)]'/> <!-- Should still have true --> <!-- check Error task as well --> <Error Text='error' ContinueOnError='true' /> <Message Text='[4:$(MSBuildLastTaskResult)]'/> <!-- Should be false --> <!-- trigger OnError target, ContinueOnError is false --> <Error Text='error2'/> <OnError ExecuteTargets='t3'/> </Target> <Target Name='t3' > <Message Text='[5:$(MSBuildLastTaskResult)]'/> <!-- Should be false --> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); MockLogger logger = new MockLogger(); loggers.Add(logger); project.Build("t2", loggers); logger.AssertLogContains("[start:]"); logger.AssertLogContains("[0:true]"); logger.AssertLogContains("[1:false]"); logger.AssertLogContains("[p:false]"); logger.AssertLogContains("[2:true]"); logger.AssertLogContains("[3:true]"); logger.AssertLogContains("[4:false]"); logger.AssertLogContains("[4:false]"); } /// <summary> /// Verifies that we can add "recursivedir" built-in metadata as target outputs. /// This is to support wildcards in CreateItem. Allowing anything /// else could let the item get corrupt (inconsistent values for Filename and FullPath, for example) /// </summary> [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] [Trait("Category", "mono-osx-failing")] public void TasksCanAddRecursiveDirBuiltInMetadata() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <CreateItem Include='$(programfiles)\reference assemblies\**\*.dll;'> <Output TaskParameter='Include' ItemName='x' /> </CreateItem> <Message Text='@(x)'/> <Message Text='[%(x.RecursiveDir)]'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); bool result = project.Build("t", loggers); Assert.True(result); logger.AssertLogDoesntContain("[]"); logger.AssertLogDoesntContain("MSB4118"); logger.AssertLogDoesntContain("MSB3031"); } /// <summary> /// Verify CreateItem prevents adding any built-in metadata explicitly, even recursivedir. /// </summary> [Fact] public void OtherBuiltInMetadataErrors() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <CreateItem Include='Foo' AdditionalMetadata='RecursiveDir=1'> <Output TaskParameter='Include' ItemName='x' /> </CreateItem> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); bool result = project.Build("t", loggers); Assert.False(result); logger.AssertLogContains("MSB3031"); } /// <summary> /// Verify CreateItem prevents adding any built-in metadata explicitly, even recursivedir. /// </summary> [Fact] public void OtherBuiltInMetadataErrors2() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <CreateItem Include='Foo' AdditionalMetadata='Extension=1'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); bool result = project.Build("t", loggers); Assert.False(result); logger.AssertLogContains("MSB3031"); } /// <summary> /// Verify that properties can be passed in to a task and out as items, despite the /// built-in metadata restrictions. /// </summary> [Fact] public void PropertiesInItemsOutOfTask() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <PropertyGroup> <p>c:\a.ext</p> </PropertyGroup> <CreateItem Include='$(p)'> <Output TaskParameter='Include' ItemName='x' /> </CreateItem> <Message Text='[%(x.Extension)]'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); bool result = project.Build("t", loggers); Assert.True(result); logger.AssertLogContains("[.ext]"); } /// <summary> /// Verify that properties can be passed in to a task and out as items, despite /// having illegal characters for a file name /// </summary> [Fact] public void IllegalFileCharsInItemsOutOfTask() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <PropertyGroup> <p>||illegal||</p> </PropertyGroup> <CreateItem Include='$(p)'> <Output TaskParameter='Include' ItemName='x' /> </CreateItem> <Message Text='[@(x)]'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); bool result = project.Build("t", loggers); Assert.True(result); logger.AssertLogContains("[||illegal||]"); } /// <summary> /// If an item being output from a task has null metadata, we shouldn't crash. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void NullMetadataOnOutputItems() { string customTaskPath = Assembly.GetExecutingAssembly().Location; string projectContents = @"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <UsingTask TaskName=`NullMetadataTask` AssemblyFile=`" + customTaskPath + @"` /> <Target Name=`Build`> <NullMetadataTask> <Output TaskParameter=`OutputItems` ItemName=`Outputs`/> </NullMetadataTask> <Message Text=`[%(Outputs.Identity): %(Outputs.a)]` Importance=`High` /> </Target> </Project>"; MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents, _testOutput); logger.AssertLogContains("[foo: ]"); } /// <summary> /// If an item being output from a task has null metadata, we shouldn't crash. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void NullMetadataOnLegacyOutputItems() { string customTaskPath = Assembly.GetExecutingAssembly().Location; string projectContents = @"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <UsingTask TaskName=`NullMetadataTask` AssemblyFile=`" + customTaskPath + @"` /> <Target Name=`Build`> <NullMetadataTask> <Output TaskParameter=`OutputItems` ItemName=`Outputs`/> </NullMetadataTask> <Message Text=`[%(Outputs.Identity): %(Outputs.a)]` Importance=`High` /> </Target> </Project>"; MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents, _testOutput); logger.AssertLogContains("[foo: ]"); } #if FEATURE_CODETASKFACTORY /// <summary> /// If an item being output from a task has null metadata, we shouldn't crash. /// </summary> [Fact] public void NullMetadataOnOutputItems_InlineTask() { string projectContents = @" <Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`NullMetadataTask_v12` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll`> <ParameterGroup> <OutputItems ParameterType=`Microsoft.Build.Framework.ITaskItem[]` Output=`true` /> </ParameterGroup> <Task> <Code> <![CDATA[ OutputItems = new ITaskItem[1]; IDictionary<string, string> metadata = new Dictionary<string, string>(); metadata.Add(`a`, null); OutputItems[0] = new TaskItem(`foo`, (IDictionary)metadata); return true; ]]> </Code> </Task> </UsingTask> <Target Name=`Build`> <NullMetadataTask_v12> <Output TaskParameter=`OutputItems` ItemName=`Outputs` /> </NullMetadataTask_v12> <Message Text=`[%(Outputs.Identity): %(Outputs.a)]` Importance=`High` /> </Target> </Project>"; MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents, _testOutput); logger.AssertLogContains("[foo: ]"); } /// <summary> /// If an item being output from a task has null metadata, we shouldn't crash. /// </summary> [Fact] [Trait("Category", "non-mono-tests")] public void NullMetadataOnLegacyOutputItems_InlineTask() { string projectContents = @" <Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`NullMetadataTask_v4` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildFrameworkToolsPath)\Microsoft.Build.Tasks.v4.0.dll`> <ParameterGroup> <OutputItems ParameterType=`Microsoft.Build.Framework.ITaskItem[]` Output=`true` /> </ParameterGroup> <Task> <Code> <![CDATA[ OutputItems = new ITaskItem[1]; IDictionary<string, string> metadata = new Dictionary<string, string>(); metadata.Add(`a`, null); OutputItems[0] = new TaskItem(`foo`, (IDictionary)metadata); return true; ]]> </Code> </Task> </UsingTask> <Target Name=`Build`> <NullMetadataTask_v4> <Output TaskParameter=`OutputItems` ItemName=`Outputs` /> </NullMetadataTask_v4> <Message Text=`[%(Outputs.Identity): %(Outputs.a)]` Importance=`High` /> </Target> </Project>"; MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents, _testOutput); logger.AssertLogContains("[foo: ]"); } #endif /// <summary> /// Validates that the defining project metadata is set (or not set) as expected in /// various task output-related operations, using a task built against the current /// version of MSBuild. /// </summary> [Fact] public void ValidateDefiningProjectMetadataOnTaskOutputs() { string customTaskPath = Assembly.GetExecutingAssembly().Location; ValidateDefiningProjectMetadataOnTaskOutputsHelper(customTaskPath); } /// <summary> /// Validates that the defining project metadata is set (or not set) as expected in /// various task output-related operations, using a task built against V4 MSBuild, /// which didn't support the defining project metadata. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void ValidateDefiningProjectMetadataOnTaskOutputs_LegacyItems() { string customTaskPath = Assembly.GetExecutingAssembly().Location; ValidateDefiningProjectMetadataOnTaskOutputsHelper(customTaskPath); } #if FEATURE_APARTMENT_STATE /// <summary> /// Tests that putting the RunInSTA attribute on a task causes it to run in the STA thread. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadRequired() { TestSTATask(true, false, false); } /// <summary> /// Tests an STA task with an exception /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadRequiredWithException() { TestSTATask(true, false, true); } /// <summary> /// Tests an STA task with failure. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadRequiredWithFailure() { TestSTATask(true, true, false); } /// <summary> /// Tests an MTA task. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadNotRequired() { TestSTATask(false, false, false); } /// <summary> /// Tests an MTA task with an exception. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadNotRequiredWithException() { TestSTATask(false, false, true); } /// <summary> /// Tests an MTA task with failure. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadNotRequiredWithFailure() { TestSTATask(false, true, false); } #endif #region ITargetBuilderCallback Members /// <summary> /// Empty impl /// </summary> Task<ITargetResult[]> ITargetBuilderCallback.LegacyCallTarget(string[] targets, bool continueOnError, ElementLocation referenceLocation) { throw new NotImplementedException(); } /// <summary> /// Empty impl /// </summary> void IRequestBuilderCallback.Yield() { } /// <summary> /// Empty impl /// </summary> void IRequestBuilderCallback.Reacquire() { } /// <summary> /// Empty impl /// </summary> void IRequestBuilderCallback.EnterMSBuildCallbackState() { } /// <summary> /// Empty impl /// </summary> void IRequestBuilderCallback.ExitMSBuildCallbackState() { } #endregion #region IRequestBuilderCallback Members /// <summary> /// Empty impl /// </summary> Task<BuildResult[]> IRequestBuilderCallback.BuildProjects(string[] projectFiles, PropertyDictionary<ProjectPropertyInstance>[] properties, string[] toolsVersions, string[] targets, bool waitForResults, bool skipNonexistentTargets) { throw new NotImplementedException(); } /// <summary> /// Not implemented. /// </summary> Task IRequestBuilderCallback.BlockOnTargetInProgress(int blockingRequestId, string blockingTarget, BuildResult partialBuildResult) { throw new NotImplementedException(); } #endregion /********************************************************************************* * * Helpers * *********************************************************************************/ /// <summary> /// Helper method for validating the setting of defining project metadata on items /// coming from task outputs /// </summary> private void ValidateDefiningProjectMetadataOnTaskOutputsHelper(string customTaskPath) { string projectAPath = Path.Combine(ObjectModelHelpers.TempProjectDir, "a.proj"); string projectBPath = Path.Combine(ObjectModelHelpers.TempProjectDir, "b.proj"); string projectAContents = @" <Project xmlns=`msbuildnamespace` ToolsVersion=`msbuilddefaulttoolsversion`> <UsingTask TaskName=`ItemCreationTask` AssemblyFile=`" + customTaskPath + @"` /> <Import Project=`b.proj` /> <Target Name=`Run`> <ItemCreationTask InputItemsToPassThrough=`@(PassThrough)` InputItemsToCopy=`@(Copy)`> <Output TaskParameter=`OutputString` ItemName=`A` /> <Output TaskParameter=`PassedThroughOutputItems` ItemName=`B` /> <Output TaskParameter=`CreatedOutputItems` ItemName=`C` /> <Output TaskParameter=`CopiedOutputItems` ItemName=`D` /> </ItemCreationTask> <Warning Text=`A is wrong: EXPECTED: [a] ACTUAL: [%(A.DefiningProjectName)]` Condition=`'%(A.DefiningProjectName)' != 'a'` /> <Warning Text=`B is wrong: EXPECTED: [a] ACTUAL: [%(B.DefiningProjectName)]` Condition=`'%(B.DefiningProjectName)' != 'a'` /> <Warning Text=`C is wrong: EXPECTED: [a] ACTUAL: [%(C.DefiningProjectName)]` Condition=`'%(C.DefiningProjectName)' != 'a'` /> <Warning Text=`D is wrong: EXPECTED: [a] ACTUAL: [%(D.DefiningProjectName)]` Condition=`'%(D.DefiningProjectName)' != 'a'` /> </Target> </Project> "; string projectBContents = @" <Project xmlns=`msbuildnamespace` ToolsVersion=`msbuilddefaulttoolsversion`> <ItemGroup> <PassThrough Include=`aaa.cs` /> <Copy Include=`bbb.cs` /> </ItemGroup> </Project> "; try { File.WriteAllText(projectAPath, ObjectModelHelpers.CleanupFileContents(projectAContents)); File.WriteAllText(projectBPath, ObjectModelHelpers.CleanupFileContents(projectBContents)); MockLogger logger = new MockLogger(_testOutput); ObjectModelHelpers.BuildTempProjectFileExpectSuccess("a.proj", logger); logger.AssertNoWarnings(); } finally { if (File.Exists(projectAPath)) { File.Delete(projectAPath); } if (File.Exists(projectBPath)) { File.Delete(projectBPath); } } } #if FEATURE_APARTMENT_STATE /// <summary> /// Executes an STA task test. /// </summary> private void TestSTATask(bool requireSTA, bool failTask, bool throwException) { MockLogger logger = new MockLogger(); logger.AllowTaskCrashes = throwException; string taskAssemblyName = null; Project project = CreateSTATestProject(requireSTA, failTask, throwException, out taskAssemblyName); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); BuildParameters parameters = new BuildParameters(); parameters.Loggers = new ILogger[] { logger }; BuildResult result = BuildManager.DefaultBuildManager.Build(parameters, new BuildRequestData(project.CreateProjectInstance(), new string[] { "Foo" })); if (requireSTA) { logger.AssertLogContains("STA"); } else { logger.AssertLogContains("MTA"); } if (throwException) { logger.AssertLogContains("EXCEPTION"); Assert.Equal(BuildResultCode.Failure, result.OverallResult); return; } else { logger.AssertLogDoesntContain("EXCEPTION"); } if (failTask) { logger.AssertLogContains("FAIL"); Assert.Equal(BuildResultCode.Failure, result.OverallResult); } else { logger.AssertLogDoesntContain("FAIL"); } if (!throwException && !failTask) { Assert.Equal(BuildResultCode.Success, result.OverallResult); } } /// <summary> /// Helper to create a project which invokes the STA helper task. /// </summary> private Project CreateSTATestProject(bool requireSTA, bool failTask, bool throwException, out string assemblyToDelete) { assemblyToDelete = GenerateSTATask(requireSTA); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <UsingTask TaskName='ThreadTask' AssemblyFile='" + assemblyToDelete + @"'/> <Target Name='Foo'> <ThreadTask Fail='" + failTask + @"' ThrowException='" + throwException + @"'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); return project; } #endif /// <summary> /// Helper to create the STA test task. /// </summary> private string GenerateSTATask(bool requireSTA) { string taskContents = @" using System; using Microsoft.Build.Framework; namespace ClassLibrary2 {" + (requireSTA ? "[RunInSTA]" : String.Empty) + @" public class ThreadTask : ITask { #region ITask Members public IBuildEngine BuildEngine { get; set; } public bool ThrowException { get; set; } public bool Fail { get; set; } public bool Execute() { string message; if (System.Threading.Thread.CurrentThread.GetApartmentState() == System.Threading.ApartmentState.STA) { message = ""STA""; } else { message = ""MTA""; } BuildEngine.LogMessageEvent(new BuildMessageEventArgs(message, """", ""ThreadTask"", MessageImportance.High)); if (ThrowException) { throw new InvalidOperationException(""EXCEPTION""); } if (Fail) { BuildEngine.LogMessageEvent(new BuildMessageEventArgs(""FAIL"", """", ""ThreadTask"", MessageImportance.High)); } return !Fail; } public ITaskHost HostObject { get; set; } #endregion } }"; return CustomTaskHelper.GetAssemblyForTask(taskContents); } /// <summary> /// Creates a test project. /// </summary> /// <returns>The project.</returns> private ProjectInstance CreateTestProject() { string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <ItemGroup> <Compile Include='b.cs' /> <Compile Include='c.cs' /> </ItemGroup> <ItemGroup> <Reference Include='System' /> </ItemGroup> <Target Name='Empty' /> <Target Name='Skip' Inputs='testProject.proj' Outputs='testProject.proj' /> <Target Name='Error' > <ErrorTask1 ContinueOnError='True'/> <ErrorTask2 ContinueOnError='False'/> <ErrorTask3 /> <OnError ExecuteTargets='Foo'/> <OnError ExecuteTargets='Bar'/> </Target> <Target Name='Foo' Inputs='foo.cpp' Outputs='foo.o'> <FooTask1/> </Target> <Target Name='Bar'> <BarTask1/> </Target> <Target Name='Baz' DependsOnTargets='Bar'> <BazTask1/> <BazTask2/> </Target> <Target Name='Baz2' DependsOnTargets='Bar;Foo'> <Baz2Task1/> <Baz2Task2/> <Baz2Task3/> </Target> <Target Name='DepSkip' DependsOnTargets='Skip'> <DepSkipTask1/> <DepSkipTask2/> <DepSkipTask3/> </Target> <Target Name='DepError' DependsOnTargets='Foo;Skip;Error'> <DepSkipTask1/> <DepSkipTask2/> <DepSkipTask3/> </Target> </Project> "); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestConfiguration config = new BuildRequestConfiguration(1, new BuildRequestData("testfile", new Dictionary<string, string>(), "3.5", new string[0], null), "2.0"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); config.Project = project.CreateProjectInstance(); cache.AddConfiguration(config); return config.Project; } /// <summary> /// The mock component host object. /// </summary> private class MockHost : MockLoggingService, IBuildComponentHost, IBuildComponent { #region IBuildComponentHost Members /// <summary> /// The config cache /// </summary> private IConfigCache _configCache; /// <summary> /// The logging service /// </summary> private ILoggingService _loggingService; /// <summary> /// The results cache /// </summary> private IResultsCache _resultsCache; /// <summary> /// The request builder /// </summary> private IRequestBuilder _requestBuilder; /// <summary> /// The target builder /// </summary> private ITargetBuilder _targetBuilder; /// <summary> /// The build parameters. /// </summary> private BuildParameters _buildParameters; /// <summary> /// Retrieves the LegacyThreadingData associated with a particular component host /// </summary> private LegacyThreadingData _legacyThreadingData; private ISdkResolverService _sdkResolverService; /// <summary> /// Constructor /// /// UNDONE: Refactor this, and the other MockHosts, to use a common base implementation. The duplication of the /// logging implementation alone is unfortunate. /// </summary> public MockHost() { _buildParameters = new BuildParameters(); _legacyThreadingData = new LegacyThreadingData(); _configCache = new ConfigCache(); ((IBuildComponent)_configCache).InitializeComponent(this); _loggingService = this; _resultsCache = new ResultsCache(); ((IBuildComponent)_resultsCache).InitializeComponent(this); _requestBuilder = new RequestBuilder(); ((IBuildComponent)_requestBuilder).InitializeComponent(this); _targetBuilder = new TargetBuilder(); ((IBuildComponent)_targetBuilder).InitializeComponent(this); _sdkResolverService = new MockSdkResolverService(); ((IBuildComponent)_sdkResolverService).InitializeComponent(this); } /// <summary> /// Returns the node logging service. We don't distinguish here. /// </summary> public ILoggingService LoggingService { get { return _loggingService; } } /// <summary> /// Retrieves the name of the host. /// </summary> public string Name { get { return "TaskBuilder_Tests.MockHost"; } } /// <summary> /// Returns the build parameters. /// </summary> public BuildParameters BuildParameters { get { return _buildParameters; } } /// <summary> /// Retrieves the LegacyThreadingData associated with a particular component host /// </summary> LegacyThreadingData IBuildComponentHost.LegacyThreadingData { get { return _legacyThreadingData; } } /// <summary> /// Constructs and returns a component of the specified type. /// </summary> /// <param name="type">The type of component to return</param> /// <returns>The component</returns> public IBuildComponent GetComponent(BuildComponentType type) { switch (type) { case BuildComponentType.ConfigCache: return (IBuildComponent)_configCache; case BuildComponentType.LoggingService: return (IBuildComponent)_loggingService; case BuildComponentType.ResultsCache: return (IBuildComponent)_resultsCache; case BuildComponentType.RequestBuilder: return (IBuildComponent)_requestBuilder; case BuildComponentType.TargetBuilder: return (IBuildComponent)_targetBuilder; case BuildComponentType.SdkResolverService: return (IBuildComponent)_sdkResolverService; default: throw new ArgumentException("Unexpected type " + type); } } /// <summary> /// Register a component factory. /// </summary> public void RegisterFactory(BuildComponentType type, BuildComponentFactoryDelegate factory) { } #endregion #region IBuildComponent Members /// <summary> /// Sets the component host /// </summary> /// <param name="host">The component host</param> public void InitializeComponent(IBuildComponentHost host) { throw new NotImplementedException(); } /// <summary> /// Shuts down the component /// </summary> public void ShutdownComponent() { throw new NotImplementedException(); } #endregion } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Windows.Forms; using Ai2dShooter.Common; using Ai2dShooter.Map; using Ai2dShooter.Model; using Ai2dShooter.View; namespace Ai2dShooter.Controller { /// <summary> /// Class that keeps track of the current game. /// </summary> public sealed class GameController { #region Public Fields /// <summary> /// Currently running game. Updated whenever a new game is created. /// </summary> public static GameController Instance { get; set; } public static bool HasGame { get { return Instance != null; }} /// <summary> /// True if there is a game that is running or could be resumed. /// </summary> public bool GameRunning; public bool GamePaused { get; private set; } public bool ArePlayersShooting { get { return _shootingPlayers != null; } } #endregion #region Private Fields private readonly Dictionary<Player, Player[]> _opponents = new Dictionary<Player, Player[]>(); private readonly Dictionary<Player, Player[]> _friends = new Dictionary<Player, Player[]>(); private Player[] _shootingPlayers; private int _deathCount; #endregion #region Constructor public GameController(Player[] players) { // update game instance Instance = this; // prepare game for the players foreach (var p in players) { // register to events var p1 = p; p.LocationChanged += () => { if (IsShootingPlayer(p1) || !p1.IsAlive) return; CheckForOpponents(p1); }; p.Death += () => { // the players aren't shooting anymore _shootingPlayers = null; // remove from opponent's opponent list foreach (var opponent in _opponents[p1]) _opponents[opponent] = _opponents[opponent].Except(new[] {p1}).ToArray(); // remove own opponent list _opponents.Remove(p1); // remove from friends' friend list foreach (var friend in _friends[p1]) _friends[friend] = _friends[friend].Except(new[] {p1}).ToArray(); // remove own friend list _friends.Remove(p1); if (MainForm.Instance.PlaySoundEffects && _deathCount++ == 0) MainForm.Instance.Invoke((MethodInvoker) (() => Constants.FirstBloodSound.Play())); foreach (var o in _opponents.Values) if (o.Length == 0) { // game over! // did all players of one team survive? if (MainForm.Instance.PlaySoundEffects && _opponents[_opponents.Keys.ToArray()[0]].Length == _opponents.Keys.Count) MainForm.Instance.Invoke((MethodInvoker) (() => Constants.PerfectSound.Play())); //MainForm.ApplicationRunning = false; StopGame(); } }; // add opponents _opponents.Add(p, players.Where(pp => pp.Team != p.Team).ToArray()); // add friends _friends.Add(p, players.Where(pp => pp.Team == p.Team && pp != p).ToArray()); } } #endregion #region Main Methods /// <summary> /// Starts a new game and tells the players to start. /// </summary> public void StartGame() { if (MainForm.Instance.PlaySoundEffects) Constants.PlaySound.Play(); GamePaused = false; GameRunning = true; // start players on new thread so as not to block the main thread new Thread(() => { foreach (var player in _friends.Keys) { // use random timeout between players starting Thread.Sleep(Constants.Rnd.Next(Constants.AiMoveTimeout)); player.StartGame(); } }).Start(); } /// <summary> /// Stop (pause) game. /// </summary> public void StopGame() { Instance = null; MainForm.Instance.StopGame(); } /// <summary> /// Pauses or resumes the game. /// </summary> public void PauseResumeGame() { if (GamePaused) { GamePaused = false; return; } // set paused flag GamePaused = true; new Thread(() => { // acquire proper lock to pause NOW (rather than SOON): // if players are shooting, stop them // else, stop players from moving var lockMe = ArePlayersShooting ? Constants.ShootingLock : Constants.MovementLock; lock (lockMe) { while (GamePaused) Thread.Sleep(100); } }).Start(); } /// <summary> /// Returns the cell of the opponent that is closest to the player and is visible. /// </summary> /// <param name="player">Player looking for a target</param> /// <returns>Cell of the nearest target, or null if no target is visible</returns> public Cell GetClosestVisibleOpponentCell(Player player) { Cell closest = null; // get all visible cells var visibleCells = player.VisibleReachableCells.ToArray(); // iterate over opponents to see whether they're close by foreach (var o in _opponents[player].Where(o => visibleCells.Contains(o.Location))) { // ensure closest isn't null closest = closest ?? o.Location; // if the current target is closer than the previously closest target, update it if (player.Location.GetManhattenDistance(o.Location) < player.Location.GetManhattenDistance(closest)) closest = o.Location; } // return target return closest; } /// <summary> /// Finds the closest friendly player. /// </summary> /// <param name="player">Player looking for friends</param> /// <returns>Closest friend or null if everyone else is dead</returns> public Player GetClosestFriend(Player player) { Player closest = null; // iterate over fiends foreach (var f in _friends[player].Where(f => f.FollowedPlayer != player)) { // ensure closest isn't null for comparison below closest = closest ?? f; // update closest if the current friend is closer if (player.Location.GetManhattenDistance(f.Location) < player.Location.GetManhattenDistance(closest.Location)) closest = f; } // return closest friend return closest; } /// <summary> /// Determines whether the player is currently shooting /// </summary> /// <param name="player">Player that may be shooting</param> /// <returns>True if the player is shooting</returns> private bool IsShootingPlayer(Player player) { return _shootingPlayers != null && _shootingPlayers.Any(s => s == player); } /// <summary> /// Checks whether the player has any opponents in range (on a neighboring cell). /// </summary> /// <param name="player">Player that is looking for targets</param> public void CheckForOpponents(Player player) { if (IsShootingPlayer(player) || !player.IsAlive) return; lock (Constants.MovementLock) { if (!player.IsAlive || !_opponents.ContainsKey(player)) return; var opponents = _opponents[player].Where(o => !IsShootingPlayer(o)); // check whether player can shoot at any other player foreach (var opponent in opponents) { if (!player.IsAlive || !_opponents.ContainsKey(player)) return; // check next opponent if the current opponent is no neighbor if (!player.Location.Neighbors.Contains(opponent.Location)) continue; var op = opponent; // *someone* has spotted *someone* // did the player move into a camper's crosshair? if (opponent.Location.GetNeighbor(opponent.Orientation) == player.Location) { Console.WriteLine(player + " got camped by " + opponent + "!"); // swap player and opponent because campers have first strike op = player; player = opponent; } // tell the players who spotted whom Console.WriteLine(player + " has spotted " + op); player.EnemySpotted(); op.SpottedByEnemy(); // ensure we don't already have a shots exchange if (_shootingPlayers != null) throw new Exception("Can only have one gunfight at a time!"); _shootingPlayers = new[] {player, op}; // calculate stuff for the first shot var hit = Constants.Rnd.NextDouble() < player.ShootingAccuracy; var headshot = hit && (Constants.Rnd.NextDouble() < player.HeadshotChance); var frontalAttack = op.Location.GetDirection(player.Location) == op.Orientation; var knife = player.UsesKnife; if (!knife) player.Ammo--; Thread.Sleep(Constants.ShootingTimeout); op.Damage(player, (int)((hit ? 1 : 0)*(frontalAttack ? player.FrontDamage : player.BackDamage)* (headshot ? 2 : 1)*(knife ? 0.5 : 1)), frontalAttack, headshot, knife); // done! return; } } } /// <summary> /// Returns the cell where the friends have the lowest influence (highest distance). /// </summary> /// <param name="cells">Cells where the player could move to</param> /// <param name="player">Player looking for a cell to move to</param> /// <returns>Cell where there is the least influence by the player's team.</returns> public Cell GetCellWithLowestInfluence(Cell[] cells, Player player) { // if no friends are alive, return random cell if (_friends[player].Length == 0) return cells[Constants.Rnd.Next(cells.Length)]; // if there is only one option, return that if (_friends[player].Length == 1) return cells[0]; // prepare variables var influence = new int[cells.Length]; // loop over possibilities for (var i = 0; i < cells.Length; i++) { // loop over friends foreach (var p in _friends[player]) { // add influence influence[i] += GetInfluenceOnCell(p, cells[i]); } } // find all cells where influence is minimal var minInfluence = influence.Min(); var minInfluenceIndices = new List<int>(); for (var i = 0; i < influence.Length; i++) { if (influence[i] == minInfluence) minInfluenceIndices.Add(i); } // return random cell with lowest influence return cells[minInfluenceIndices[Constants.Rnd.Next(minInfluenceIndices.Count)]]; } /// <summary> /// Gets the influence of a player on the cell. /// </summary> /// <param name="player">Player</param> /// <param name="cell">Cell</param> /// <returns>Influence of the player on the cell</returns> private static int GetInfluenceOnCell(Player player, Cell cell) { if (player.FollowedPlayer != null) return 0; var distance = player.Location.GetManhattenDistance(cell); return distance <= 2 * Constants.Visibility ? 2 * Constants.Visibility - distance : 0; } /// <summary> /// Gets a complete influence map of an array of players on the maze. /// </summary> /// <param name="players">Players</param> /// <returns>Influence map of the players</returns> public static int[,] GetInfluenceMap(Player[] players) { var result = new int[Maze.Instance.Width, Maze.Instance.Height]; for (var x = 0; x < Maze.Instance.Width; x++) for (var y = 0; y < Maze.Instance.Height; y++) foreach (var p in players) result[x, y] += GetInfluenceOnCell(p, Maze.Instance.Cells[x, y]); return result; } #endregion } }
using System; using System.Collections.Generic; using Content.Server.Construction.Components; using Content.Server.DoAfter; using Content.Shared.Construction; using Content.Shared.Construction.Steps; using Content.Shared.Interaction; using Robust.Shared.Containers; using Robust.Shared.GameObjects; namespace Content.Server.Construction { public sealed partial class ConstructionSystem { private readonly HashSet<EntityUid> _constructionUpdateQueue = new(); private void InitializeInteractions() { #region DoAfter Subscriptions // DoAfter handling. // The ConstructionDoAfter events are meant to be raised either directed or broadcast. // If they're raised broadcast, we will re-raise them as directed on the target. // This allows us to easily use the DoAfter system for our purposes. SubscribeLocalEvent<ConstructionDoAfterComplete>(OnDoAfterComplete); SubscribeLocalEvent<ConstructionDoAfterCancelled>(OnDoAfterCancelled); SubscribeLocalEvent<ConstructionComponent, ConstructionDoAfterComplete>(EnqueueEvent); SubscribeLocalEvent<ConstructionComponent, ConstructionDoAfterCancelled>(EnqueueEvent); #endregion // Event handling. Add your subscriptions here! Just make sure they're all handled by EnqueueEvent. SubscribeLocalEvent<ConstructionComponent, InteractUsingEvent>(EnqueueEvent); } /// <summary> /// Takes in an entity with <see cref="ConstructionComponent"/> and an object event, and handles any /// possible construction interactions, depending on the construction's state. /// </summary> /// <remarks>When <see cref="validation"/> is true, this method will simply return whether the interaction /// would be handled by the entity or not. It essentially becomes a pure method that modifies nothing.</remarks> /// <returns>The result of this interaction with the entity.</returns> private HandleResult HandleEvent(EntityUid uid, object ev, bool validation, ConstructionComponent? construction = null) { if (!Resolve(uid, ref construction)) return HandleResult.False; // If the state machine is in an invalid state (not on a valid node) we can't do anything, ever. if (GetCurrentNode(uid, construction) is not {} node) { return HandleResult.False; } // If we're currently in an edge, we'll let the edge handle or validate the interaction. if (GetCurrentEdge(uid, construction) is {} edge) { var result = HandleEdge(uid, ev, edge, validation, construction); // Reset edge index to none if this failed... if (!validation && result is HandleResult.False && construction.StepIndex == 0) construction.EdgeIndex = null; return result; } // If we're not on an edge, let the node handle or validate the interaction. return HandleNode(uid, ev, node, validation, construction); } /// <summary> /// Takes in an entity, a <see cref="ConstructionGraphNode"/> and an object event, and handles any /// possible construction interactions. This will check the interaction against all possible edges, /// and if any of the edges accepts the interaction, we will enter it. /// </summary> /// <remarks>When <see cref="validation"/> is true, this method will simply return whether the interaction /// would be handled by the entity or not. It essentially becomes a pure method that modifies nothing.</remarks> /// <returns>The result of this interaction with the entity.</returns> private HandleResult HandleNode(EntityUid uid, object ev, ConstructionGraphNode node, bool validation, ConstructionComponent? construction = null) { if (!Resolve(uid, ref construction)) return HandleResult.False; // Let's make extra sure this is zero... construction.StepIndex = 0; // When we handle a node, we're essentially testing the current event interaction against all of this node's // edges' first steps. If any of them accepts the interaction, we stop iterating and enter that edge. for (var i = 0; i < node.Edges.Count; i++) { var edge = node.Edges[i]; if (HandleEdge(uid, ev, edge, validation, construction) is var result and not HandleResult.False) { // Only a True result may modify the state. // In the case of DoAfter, it's only allowed to modify the waiting flag and the current edge index. // In the case of validated, it should NEVER modify the state at all. if (result is not HandleResult.True) { if (result is HandleResult.DoAfter) { construction.EdgeIndex = i; } return result; } // If we're not on the same edge as we were before, that means handling that edge changed the node. if (construction.Node != node.Name) return result; // If we're still in the same node, that means we entered the edge and it's still not done. construction.EdgeIndex = i; UpdatePathfinding(uid, construction); return result; } } return HandleResult.False; } /// <summary> /// Takes in an entity, a <see cref="ConstructionGraphEdge"/> and an object event, and handles any /// possible construction interactions. This will check the interaction against one of the steps in the edge /// depending on the construction's <see cref="ConstructionComponent.StepIndex"/>. /// </summary> /// <remarks>When <see cref="validation"/> is true, this method will simply return whether the interaction /// would be handled by the entity or not. It essentially becomes a pure method that modifies nothing.</remarks> /// <returns>The result of this interaction with the entity.</returns> private HandleResult HandleEdge(EntityUid uid, object ev, ConstructionGraphEdge edge, bool validation, ConstructionComponent? construction = null) { if (!Resolve(uid, ref construction)) return HandleResult.False; var step = GetStepFromEdge(edge, construction.StepIndex); if (step == null) { _sawmill.Warning($"Called {nameof(HandleEdge)} on entity {uid} but the current state is not valid for that!"); return HandleResult.False; } // We need to ensure we currently satisfy any and all edge conditions. if (!CheckConditions(uid, edge.Conditions)) return HandleResult.False; // We can only perform the "step completed" logic if this returns true. if (HandleStep(uid, ev, step, validation, out var user, construction) is var handle and not HandleResult.True) return handle; // We increase the step index, meaning we move to the next step! construction.StepIndex++; // Check if the new step index is greater than the amount of steps in the edge... if (construction.StepIndex >= edge.Steps.Count) { // Edge finished! PerformActions(uid, user, edge.Completed); construction.TargetEdgeIndex = null; construction.EdgeIndex = null; construction.StepIndex = 0; // We change the node now. ChangeNode(uid, user, edge.Target, true, construction); } return HandleResult.True; } /// <summary> /// Takes in an entity, a <see cref="ConstructionGraphStep"/> and an object event, and handles any possible /// construction interaction. Unlike <see cref="HandleInteraction"/>, if this succeeds it will perform the /// step's completion actions. Also sets the out parameter to the user's EntityUid. /// </summary> /// <remarks>When <see cref="validation"/> is true, this method will simply return whether the interaction /// would be handled by the entity or not. It essentially becomes a pure method that modifies nothing.</remarks> /// <returns>The result of this interaction with the entity.</returns> private HandleResult HandleStep(EntityUid uid, object ev, ConstructionGraphStep step, bool validation, out EntityUid? user, ConstructionComponent? construction = null) { user = null; if (!Resolve(uid, ref construction)) return HandleResult.False; // Let HandleInteraction actually handle the event for this step. // We can only perform the rest of our logic if it returns true. if (HandleInteraction(uid, ev, step, validation, out user, construction) is var handle and not HandleResult.True) return handle; // Actually perform the step completion actions, since the step was handled correctly. PerformActions(uid, user, step.Completed); UpdatePathfinding(uid, construction); return HandleResult.True; } /// <summary> /// Takes in an entity, a <see cref="ConstructionGraphStep"/> and an object event, and handles any possible /// construction interaction. Unlike <see cref="HandleStep"/>, this only handles the interaction itself /// and doesn't perform any step completion actions. Also sets the out parameter to the user's EntityUid. /// </summary> /// <remarks>When <see cref="validation"/> is true, this method will simply return whether the interaction /// would be handled by the entity or not. It essentially becomes a pure method that modifies nothing.</remarks> /// <returns>The result of this interaction with the entity.</returns> private HandleResult HandleInteraction(EntityUid uid, object ev, ConstructionGraphStep step, bool validation, out EntityUid? user, ConstructionComponent? construction = null) { user = null; if (!Resolve(uid, ref construction)) return HandleResult.False; // Whether this event is being re-handled after a DoAfter or not. Check DoAfterState for more info. var doAfterState = validation ? DoAfterState.Validation : DoAfterState.None; // Custom data from a prior HandleInteraction where a DoAfter was called... object? doAfterData = null; // The DoAfter events can only perform special logic when we're not validating events. if (!validation) { // Some events are handled specially... Such as doAfter. switch (ev) { case ConstructionDoAfterComplete complete: { // DoAfter completed! ev = complete.WrappedEvent; doAfterState = DoAfterState.Completed; doAfterData = complete.CustomData; construction.WaitingDoAfter = false; break; } case ConstructionDoAfterCancelled cancelled: { // DoAfter failed! ev = cancelled.WrappedEvent; doAfterState = DoAfterState.Cancelled; doAfterData = cancelled.CustomData; construction.WaitingDoAfter = false; break; } } } // Can't perform any interactions while we're waiting for a DoAfter... // This also makes any event validation fail. if (construction.WaitingDoAfter) return HandleResult.False; // The cases in this switch will handle the interaction and return switch (step) { // --- CONSTRUCTION STEP EVENT HANDLING START --- #region Construction Step Event Handling // So you want to create your own custom step for construction? // You're looking at the right place, then! You should create // a new case for your step here, and handle it as you see fit. // Make extra sure you handle DoAfter (if applicable) properly! // Also make sure your event handler properly handles validation. // Note: Please use braces for your new case, it's convenient. case EntityInsertConstructionGraphStep insertStep: { // EntityInsert steps only work with InteractUsing! if (ev is not InteractUsingEvent interactUsing) break; // TODO: Sanity checks. // If this step's DoAfter was cancelled, we just fail the interaction. if (doAfterState == DoAfterState.Cancelled) return HandleResult.False; var insert = interactUsing.Used; // Since many things inherit this step, we delegate the "is this entity valid?" logic to them. // While this is very OOP and I find it icky, I must admit that it simplifies the code here a lot. if(!insertStep.EntityValid(insert, EntityManager)) return HandleResult.False; // If we're only testing whether this step would be handled by the given event, then we're done. if (doAfterState == DoAfterState.Validation) return HandleResult.Validated; // If we still haven't completed this step's DoAfter... if (doAfterState == DoAfterState.None && insertStep.DoAfter > 0) { _doAfterSystem.DoAfter( new DoAfterEventArgs(interactUsing.User, step.DoAfter, default, interactUsing.Target) { BreakOnDamage = false, BreakOnStun = true, BreakOnTargetMove = true, BreakOnUserMove = true, NeedHand = true, // These events will be broadcast and handled by this very same system, that will // raise them directed to the target. These events wrap the original event. BroadcastFinishedEvent = new ConstructionDoAfterComplete(uid, ev), BroadcastCancelledEvent = new ConstructionDoAfterCancelled(uid, ev) }); // To properly signal that we're waiting for a DoAfter, we have to set the flag on the component // and then also return the DoAfter HandleResult. construction.WaitingDoAfter = true; return HandleResult.DoAfter; } // Material steps, which use stacks, are handled specially. Instead of inserting the whole item, // we split the stack in two and insert the split stack. if (insertStep is MaterialConstructionGraphStep materialInsertStep) { if (_stackSystem.Split(insert, materialInsertStep.Amount, EntityManager.GetComponent<TransformComponent>(interactUsing.User).Coordinates) is not {} stack) return HandleResult.False; insert = stack; } // Container-storage handling. if (!string.IsNullOrEmpty(insertStep.Store)) { // In the case we want to store this item in a container on the entity... var store = insertStep.Store; // Add this container to the collection of "construction-owned" containers. // Containers in that set will be transferred to new entities in the case of a prototype change. construction.Containers.Add(store); // The container doesn't necessarily need to exist, so we ensure it. _containerSystem.EnsureContainer<Container>(uid, store).Insert(insert); } else { // If we don't store the item in a container on the entity, we just delete it right away. EntityManager.DeleteEntity(insert); } // Step has been handled correctly, so we signal this. return HandleResult.True; } case ToolConstructionGraphStep toolInsertStep: { if (ev is not InteractUsingEvent interactUsing) break; // TODO: Sanity checks. user = interactUsing.User; // If we're validating whether this event handles the step... if (doAfterState == DoAfterState.Validation) { // Then we only really need to check whether the tool entity has that quality or not. return _toolSystem.HasQuality(interactUsing.Used, toolInsertStep.Tool) ? HandleResult.Validated : HandleResult.False; } // If we're handling an event after its DoAfter finished... if (doAfterState != DoAfterState.None) return doAfterState == DoAfterState.Completed ? HandleResult.True : HandleResult.False; if (!_toolSystem.UseTool(interactUsing.Used, interactUsing.User, uid, toolInsertStep.Fuel, toolInsertStep.DoAfter, toolInsertStep.Tool, new ConstructionDoAfterComplete(uid, ev), new ConstructionDoAfterCancelled(uid, ev))) return HandleResult.False; // In the case we're not waiting for a doAfter, then this step is complete! if (toolInsertStep.DoAfter <= 0) return HandleResult.True; construction.WaitingDoAfter = true; return HandleResult.DoAfter; } #endregion // --- CONSTRUCTION STEP EVENT HANDLING FINISH --- default: throw new ArgumentOutOfRangeException(nameof(step), "You need to code your ConstructionGraphStep behavior by adding a case to the switch."); } // If the handlers were not able to handle this event, return... return HandleResult.False; } public bool CheckConditions(EntityUid uid, IEnumerable<IGraphCondition> conditions) { foreach (var condition in conditions) { if (!condition.Condition(uid, EntityManager)) return false; } return true; } public void PerformActions(EntityUid uid, EntityUid? userUid, IEnumerable<IGraphAction> actions) { foreach (var action in actions) { // If an action deletes the entity, we stop performing actions. if (!Exists(uid)) break; action.PerformAction(uid, userUid, EntityManager); } } public void ResetEdge(EntityUid uid, ConstructionComponent? construction = null) { if (!Resolve(uid, ref construction)) return; construction.TargetEdgeIndex = null; construction.EdgeIndex = null; construction.StepIndex = 0; UpdatePathfinding(uid, construction); } private void UpdateInteractions() { // We iterate all entities waiting for their interactions to be handled. // This is much more performant than making an EntityQuery for ConstructionComponent, // since, for example, every single wall has a ConstructionComponent.... foreach (var uid in _constructionUpdateQueue) { // Ensure the entity exists and has a Construction component. if (!EntityManager.EntityExists(uid) || !EntityManager.TryGetComponent(uid, out ConstructionComponent? construction)) continue; // Handle all queued interactions! while (construction.InteractionQueue.TryDequeue(out var interaction)) { // We set validation to false because we actually want to perform the interaction here. HandleEvent(uid, interaction, false, construction); } } _constructionUpdateQueue.Clear(); } #region Event Handlers private void EnqueueEvent(EntityUid uid, ConstructionComponent construction, object args) { // Handled events get treated specially. if (args is HandledEntityEventArgs handled) { // If they're already handled, we do nothing. if (handled.Handled) return; // Otherwise, let's check if this event could be handled by the construction's current state. if (HandleEvent(uid, args, true, construction) != HandleResult.Validated) return; // Not validated, so we don't even enqueue this event. handled.Handled = true; } // Enqueue this event so it'll be handled in the next tick. // This prevents some issues that could occur from entity deletion, component deletion, etc in a handler. construction.InteractionQueue.Enqueue(args); // Add this entity to the queue so it'll be updated next tick. _constructionUpdateQueue.Add(uid); } private void OnDoAfterComplete(ConstructionDoAfterComplete ev) { // Make extra sure the target entity exists... if (!EntityManager.EntityExists(ev.TargetUid)) return; // Re-raise this event, but directed on the target UID. RaiseLocalEvent(ev.TargetUid, ev, false); } private void OnDoAfterCancelled(ConstructionDoAfterCancelled ev) { // Make extra sure the target entity exists... if (!EntityManager.EntityExists(ev.TargetUid)) return; // Re-raise this event, but directed on the target UID. RaiseLocalEvent(ev.TargetUid, ev, false); } #endregion #region Event Definitions /// <summary> /// This event signals that a construction interaction's DoAfter has completed successfully. /// This wraps the original event and also keeps some custom data that event handlers might need. /// </summary> private sealed class ConstructionDoAfterComplete : EntityEventArgs { public readonly EntityUid TargetUid; public readonly object WrappedEvent; public readonly object? CustomData; public ConstructionDoAfterComplete(EntityUid targetUid, object wrappedEvent, object? customData = null) { TargetUid = targetUid; WrappedEvent = wrappedEvent; CustomData = customData; } } /// <summary> /// This event signals that a construction interaction's DoAfter has failed or has been cancelled. /// This wraps the original event and also keeps some custom data that event handlers might need. /// </summary> private sealed class ConstructionDoAfterCancelled : EntityEventArgs { public readonly EntityUid TargetUid; public readonly object WrappedEvent; public readonly object? CustomData; public ConstructionDoAfterCancelled(EntityUid targetUid, object wrappedEvent, object? customData = null) { TargetUid = targetUid; WrappedEvent = wrappedEvent; CustomData = customData; } } #endregion #region Internal Enum Definitions /// <summary> /// Specifies the DoAfter status for a construction step event handler. /// </summary> private enum DoAfterState : byte { /// <summary> /// If None, this is the first time we're seeing this event and we might want to call a DoAfter /// if the step needs it. /// </summary> None, /// <summary> /// If Validation, we want to validate whether the specified event would handle the step or not. /// Will NOT modify the construction state at all. /// </summary> Validation, /// <summary> /// If Completed, this is the second (and last) time we're seeing this event, and /// the doAfter that was called the first time successfully completed. Handle completion logic now. /// </summary> Completed, /// <summary> /// If Cancelled, this is the second (and last) time we're seeing this event, and /// the doAfter that was called the first time was cancelled. Handle cleanup logic now. /// </summary> Cancelled } /// <summary> /// Specifies the result after attempting to handle a specific step with an event. /// </summary> private enum HandleResult : byte { /// <summary> /// The interaction wasn't handled or validated. /// </summary> False, /// <summary> /// The interaction would be handled successfully. Nothing was modified. /// </summary> Validated, /// <summary> /// The interaction was handled successfully. /// </summary> True, /// <summary> /// The interaction is waiting on a DoAfter now. /// This means the interaction started the DoAfter. /// </summary> DoAfter, } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace UnityApiPoc.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Runtime.InteropServices; using System.Text; using System.Collections.Generic; using OpenHome.Net.Core; namespace OpenHome.Net.Device.Providers { public interface IDvProviderLinnCoUkVolkano1 : IDisposable { } /// <summary> /// Provider for the linn.co.uk:Volkano:1 UPnP service /// </summary> public class DvProviderLinnCoUkVolkano1 : DvProvider, IDisposable, IDvProviderLinnCoUkVolkano1 { private GCHandle iGch; private ActionDelegate iDelegateReboot; private ActionDelegate iDelegateBootMode; private ActionDelegate iDelegateSetBootMode; private ActionDelegate iDelegateBspType; private ActionDelegate iDelegateUglyName; private ActionDelegate iDelegateMacAddress; private ActionDelegate iDelegateProductId; private ActionDelegate iDelegateBoardId; private ActionDelegate iDelegateBoardType; private ActionDelegate iDelegateMaxBoards; private ActionDelegate iDelegateSoftwareVersion; private ActionDelegate iDelegateSoftwareUpdate; private ActionDelegate iDelegateDeviceInfo; /// <summary> /// Constructor /// </summary> /// <param name="aDevice">Device which owns this provider</param> protected DvProviderLinnCoUkVolkano1(DvDevice aDevice) : base(aDevice, "linn.co.uk", "Volkano", 1) { iGch = GCHandle.Alloc(this); } /// <summary> /// Signal that the action Reboot is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// Reboot must be overridden if this is called.</remarks> protected void EnableActionReboot() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("Reboot"); iDelegateReboot = new ActionDelegate(DoReboot); EnableAction(action, iDelegateReboot, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action BootMode is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// BootMode must be overridden if this is called.</remarks> protected void EnableActionBootMode() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("BootMode"); List<String> allowedValues = new List<String>(); allowedValues.Add("Main"); allowedValues.Add("Fallback"); allowedValues.Add("Ram"); action.AddOutputParameter(new ParameterString("aMode", allowedValues)); allowedValues.Clear(); iDelegateBootMode = new ActionDelegate(DoBootMode); EnableAction(action, iDelegateBootMode, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action SetBootMode is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// SetBootMode must be overridden if this is called.</remarks> protected void EnableActionSetBootMode() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("SetBootMode"); List<String> allowedValues = new List<String>(); allowedValues.Add("Main"); allowedValues.Add("Fallback"); action.AddInputParameter(new ParameterString("aMode", allowedValues)); allowedValues.Clear(); iDelegateSetBootMode = new ActionDelegate(DoSetBootMode); EnableAction(action, iDelegateSetBootMode, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action BspType is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// BspType must be overridden if this is called.</remarks> protected void EnableActionBspType() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("BspType"); List<String> allowedValues = new List<String>(); action.AddOutputParameter(new ParameterString("aBspType", allowedValues)); iDelegateBspType = new ActionDelegate(DoBspType); EnableAction(action, iDelegateBspType, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action UglyName is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// UglyName must be overridden if this is called.</remarks> protected void EnableActionUglyName() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("UglyName"); List<String> allowedValues = new List<String>(); action.AddOutputParameter(new ParameterString("aUglyName", allowedValues)); iDelegateUglyName = new ActionDelegate(DoUglyName); EnableAction(action, iDelegateUglyName, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action MacAddress is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// MacAddress must be overridden if this is called.</remarks> protected void EnableActionMacAddress() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("MacAddress"); List<String> allowedValues = new List<String>(); action.AddOutputParameter(new ParameterString("aMacAddress", allowedValues)); iDelegateMacAddress = new ActionDelegate(DoMacAddress); EnableAction(action, iDelegateMacAddress, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action ProductId is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// ProductId must be overridden if this is called.</remarks> protected void EnableActionProductId() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("ProductId"); List<String> allowedValues = new List<String>(); action.AddOutputParameter(new ParameterString("aProductNumber", allowedValues)); iDelegateProductId = new ActionDelegate(DoProductId); EnableAction(action, iDelegateProductId, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action BoardId is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// BoardId must be overridden if this is called.</remarks> protected void EnableActionBoardId() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("BoardId"); List<String> allowedValues = new List<String>(); action.AddInputParameter(new ParameterUint("aIndex")); action.AddOutputParameter(new ParameterString("aBoardNumber", allowedValues)); iDelegateBoardId = new ActionDelegate(DoBoardId); EnableAction(action, iDelegateBoardId, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action BoardType is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// BoardType must be overridden if this is called.</remarks> protected void EnableActionBoardType() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("BoardType"); List<String> allowedValues = new List<String>(); action.AddInputParameter(new ParameterUint("aIndex")); action.AddOutputParameter(new ParameterString("aBoardNumber", allowedValues)); iDelegateBoardType = new ActionDelegate(DoBoardType); EnableAction(action, iDelegateBoardType, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action MaxBoards is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// MaxBoards must be overridden if this is called.</remarks> protected void EnableActionMaxBoards() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("MaxBoards"); action.AddOutputParameter(new ParameterUint("aMaxBoards")); iDelegateMaxBoards = new ActionDelegate(DoMaxBoards); EnableAction(action, iDelegateMaxBoards, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action SoftwareVersion is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// SoftwareVersion must be overridden if this is called.</remarks> protected void EnableActionSoftwareVersion() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("SoftwareVersion"); List<String> allowedValues = new List<String>(); action.AddOutputParameter(new ParameterString("aSoftwareVersion", allowedValues)); iDelegateSoftwareVersion = new ActionDelegate(DoSoftwareVersion); EnableAction(action, iDelegateSoftwareVersion, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action SoftwareUpdate is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// SoftwareUpdate must be overridden if this is called.</remarks> protected void EnableActionSoftwareUpdate() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("SoftwareUpdate"); List<String> allowedValues = new List<String>(); action.AddOutputParameter(new ParameterBool("aAvailable")); action.AddOutputParameter(new ParameterString("aSoftwareVersion", allowedValues)); iDelegateSoftwareUpdate = new ActionDelegate(DoSoftwareUpdate); EnableAction(action, iDelegateSoftwareUpdate, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action DeviceInfo is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// DeviceInfo must be overridden if this is called.</remarks> protected void EnableActionDeviceInfo() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("DeviceInfo"); List<String> allowedValues = new List<String>(); action.AddOutputParameter(new ParameterString("aDeviceInfoXml", allowedValues)); iDelegateDeviceInfo = new ActionDelegate(DoDeviceInfo); EnableAction(action, iDelegateDeviceInfo, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Reboot action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// Reboot action for the owning device. /// /// Must be implemented iff EnableActionReboot was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> protected virtual void Reboot(IDvInvocation aInvocation) { throw (new ActionDisabledError()); } /// <summary> /// BootMode action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// BootMode action for the owning device. /// /// Must be implemented iff EnableActionBootMode was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aaMode"></param> protected virtual void BootMode(IDvInvocation aInvocation, out string aaMode) { throw (new ActionDisabledError()); } /// <summary> /// SetBootMode action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// SetBootMode action for the owning device. /// /// Must be implemented iff EnableActionSetBootMode was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aaMode"></param> protected virtual void SetBootMode(IDvInvocation aInvocation, string aaMode) { throw (new ActionDisabledError()); } /// <summary> /// BspType action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// BspType action for the owning device. /// /// Must be implemented iff EnableActionBspType was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aaBspType"></param> protected virtual void BspType(IDvInvocation aInvocation, out string aaBspType) { throw (new ActionDisabledError()); } /// <summary> /// UglyName action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// UglyName action for the owning device. /// /// Must be implemented iff EnableActionUglyName was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aaUglyName"></param> protected virtual void UglyName(IDvInvocation aInvocation, out string aaUglyName) { throw (new ActionDisabledError()); } /// <summary> /// MacAddress action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// MacAddress action for the owning device. /// /// Must be implemented iff EnableActionMacAddress was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aaMacAddress"></param> protected virtual void MacAddress(IDvInvocation aInvocation, out string aaMacAddress) { throw (new ActionDisabledError()); } /// <summary> /// ProductId action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// ProductId action for the owning device. /// /// Must be implemented iff EnableActionProductId was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aaProductNumber"></param> protected virtual void ProductId(IDvInvocation aInvocation, out string aaProductNumber) { throw (new ActionDisabledError()); } /// <summary> /// BoardId action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// BoardId action for the owning device. /// /// Must be implemented iff EnableActionBoardId was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aaIndex"></param> /// <param name="aaBoardNumber"></param> protected virtual void BoardId(IDvInvocation aInvocation, uint aaIndex, out string aaBoardNumber) { throw (new ActionDisabledError()); } /// <summary> /// BoardType action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// BoardType action for the owning device. /// /// Must be implemented iff EnableActionBoardType was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aaIndex"></param> /// <param name="aaBoardNumber"></param> protected virtual void BoardType(IDvInvocation aInvocation, uint aaIndex, out string aaBoardNumber) { throw (new ActionDisabledError()); } /// <summary> /// MaxBoards action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// MaxBoards action for the owning device. /// /// Must be implemented iff EnableActionMaxBoards was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aaMaxBoards"></param> protected virtual void MaxBoards(IDvInvocation aInvocation, out uint aaMaxBoards) { throw (new ActionDisabledError()); } /// <summary> /// SoftwareVersion action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// SoftwareVersion action for the owning device. /// /// Must be implemented iff EnableActionSoftwareVersion was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aaSoftwareVersion"></param> protected virtual void SoftwareVersion(IDvInvocation aInvocation, out string aaSoftwareVersion) { throw (new ActionDisabledError()); } /// <summary> /// SoftwareUpdate action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// SoftwareUpdate action for the owning device. /// /// Must be implemented iff EnableActionSoftwareUpdate was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aaAvailable"></param> /// <param name="aaSoftwareVersion"></param> protected virtual void SoftwareUpdate(IDvInvocation aInvocation, out bool aaAvailable, out string aaSoftwareVersion) { throw (new ActionDisabledError()); } /// <summary> /// DeviceInfo action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// DeviceInfo action for the owning device. /// /// Must be implemented iff EnableActionDeviceInfo was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aaDeviceInfoXml"></param> protected virtual void DeviceInfo(IDvInvocation aInvocation, out string aaDeviceInfoXml) { throw (new ActionDisabledError()); } private static int DoReboot(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderLinnCoUkVolkano1 self = (DvProviderLinnCoUkVolkano1)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); try { invocation.ReadStart(); invocation.ReadEnd(); self.Reboot(invocation); } catch (ActionError e) { invocation.ReportActionError(e, "Reboot"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "Reboot" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Reboot" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Reboot" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoBootMode(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderLinnCoUkVolkano1 self = (DvProviderLinnCoUkVolkano1)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); string aMode; try { invocation.ReadStart(); invocation.ReadEnd(); self.BootMode(invocation, out aMode); } catch (ActionError e) { invocation.ReportActionError(e, "BootMode"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "BootMode" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "BootMode" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteString("aMode", aMode); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "BootMode" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoSetBootMode(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderLinnCoUkVolkano1 self = (DvProviderLinnCoUkVolkano1)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); string aMode; try { invocation.ReadStart(); aMode = invocation.ReadString("aMode"); invocation.ReadEnd(); self.SetBootMode(invocation, aMode); } catch (ActionError e) { invocation.ReportActionError(e, "SetBootMode"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "SetBootMode" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "SetBootMode" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "SetBootMode" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoBspType(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderLinnCoUkVolkano1 self = (DvProviderLinnCoUkVolkano1)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); string aBspType; try { invocation.ReadStart(); invocation.ReadEnd(); self.BspType(invocation, out aBspType); } catch (ActionError e) { invocation.ReportActionError(e, "BspType"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "BspType" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "BspType" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteString("aBspType", aBspType); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "BspType" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoUglyName(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderLinnCoUkVolkano1 self = (DvProviderLinnCoUkVolkano1)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); string aUglyName; try { invocation.ReadStart(); invocation.ReadEnd(); self.UglyName(invocation, out aUglyName); } catch (ActionError e) { invocation.ReportActionError(e, "UglyName"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "UglyName" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "UglyName" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteString("aUglyName", aUglyName); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "UglyName" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoMacAddress(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderLinnCoUkVolkano1 self = (DvProviderLinnCoUkVolkano1)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); string aMacAddress; try { invocation.ReadStart(); invocation.ReadEnd(); self.MacAddress(invocation, out aMacAddress); } catch (ActionError e) { invocation.ReportActionError(e, "MacAddress"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "MacAddress" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "MacAddress" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteString("aMacAddress", aMacAddress); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "MacAddress" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoProductId(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderLinnCoUkVolkano1 self = (DvProviderLinnCoUkVolkano1)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); string aProductNumber; try { invocation.ReadStart(); invocation.ReadEnd(); self.ProductId(invocation, out aProductNumber); } catch (ActionError e) { invocation.ReportActionError(e, "ProductId"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "ProductId" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "ProductId" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteString("aProductNumber", aProductNumber); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "ProductId" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoBoardId(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderLinnCoUkVolkano1 self = (DvProviderLinnCoUkVolkano1)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); uint aIndex; string aBoardNumber; try { invocation.ReadStart(); aIndex = invocation.ReadUint("aIndex"); invocation.ReadEnd(); self.BoardId(invocation, aIndex, out aBoardNumber); } catch (ActionError e) { invocation.ReportActionError(e, "BoardId"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "BoardId" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "BoardId" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteString("aBoardNumber", aBoardNumber); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "BoardId" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoBoardType(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderLinnCoUkVolkano1 self = (DvProviderLinnCoUkVolkano1)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); uint aIndex; string aBoardNumber; try { invocation.ReadStart(); aIndex = invocation.ReadUint("aIndex"); invocation.ReadEnd(); self.BoardType(invocation, aIndex, out aBoardNumber); } catch (ActionError e) { invocation.ReportActionError(e, "BoardType"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "BoardType" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "BoardType" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteString("aBoardNumber", aBoardNumber); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "BoardType" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoMaxBoards(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderLinnCoUkVolkano1 self = (DvProviderLinnCoUkVolkano1)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); uint aMaxBoards; try { invocation.ReadStart(); invocation.ReadEnd(); self.MaxBoards(invocation, out aMaxBoards); } catch (ActionError e) { invocation.ReportActionError(e, "MaxBoards"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "MaxBoards" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "MaxBoards" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteUint("aMaxBoards", aMaxBoards); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "MaxBoards" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoSoftwareVersion(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderLinnCoUkVolkano1 self = (DvProviderLinnCoUkVolkano1)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); string aSoftwareVersion; try { invocation.ReadStart(); invocation.ReadEnd(); self.SoftwareVersion(invocation, out aSoftwareVersion); } catch (ActionError e) { invocation.ReportActionError(e, "SoftwareVersion"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "SoftwareVersion" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "SoftwareVersion" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteString("aSoftwareVersion", aSoftwareVersion); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "SoftwareVersion" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoSoftwareUpdate(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderLinnCoUkVolkano1 self = (DvProviderLinnCoUkVolkano1)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); bool aAvailable; string aSoftwareVersion; try { invocation.ReadStart(); invocation.ReadEnd(); self.SoftwareUpdate(invocation, out aAvailable, out aSoftwareVersion); } catch (ActionError e) { invocation.ReportActionError(e, "SoftwareUpdate"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "SoftwareUpdate" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "SoftwareUpdate" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteBool("aAvailable", aAvailable); invocation.WriteString("aSoftwareVersion", aSoftwareVersion); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "SoftwareUpdate" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoDeviceInfo(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderLinnCoUkVolkano1 self = (DvProviderLinnCoUkVolkano1)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); string aDeviceInfoXml; try { invocation.ReadStart(); invocation.ReadEnd(); self.DeviceInfo(invocation, out aDeviceInfoXml); } catch (ActionError e) { invocation.ReportActionError(e, "DeviceInfo"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "DeviceInfo" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "DeviceInfo" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteString("aDeviceInfoXml", aDeviceInfoXml); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "DeviceInfo" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } /// <summary> /// Must be called for each class instance. Must be called before Core.Library.Close(). /// </summary> public virtual void Dispose() { if (DisposeProvider()) iGch.Free(); } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoadSoftDelete.Business.ERLevel { /// <summary> /// G04_SubContinent (editable child object).<br/> /// This is a generated base class of <see cref="G04_SubContinent"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="G05_CountryObjects"/> of type <see cref="G05_CountryColl"/> (1:M relation to <see cref="G06_Country"/>)<br/> /// This class is an item of <see cref="G03_SubContinentColl"/> collection. /// </remarks> [Serializable] public partial class G04_SubContinent : BusinessBase<G04_SubContinent> { #region Static Fields private static int _lastID; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="SubContinent_ID"/> property. /// </summary> public static readonly PropertyInfo<int> SubContinent_IDProperty = RegisterProperty<int>(p => p.SubContinent_ID, "SubContinents ID"); /// <summary> /// Gets the SubContinents ID. /// </summary> /// <value>The SubContinents ID.</value> public int SubContinent_ID { get { return GetProperty(SubContinent_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="SubContinent_Name"/> property. /// </summary> public static readonly PropertyInfo<string> SubContinent_NameProperty = RegisterProperty<string>(p => p.SubContinent_Name, "SubContinents Name"); /// <summary> /// Gets or sets the SubContinents Name. /// </summary> /// <value>The SubContinents Name.</value> public string SubContinent_Name { get { return GetProperty(SubContinent_NameProperty); } set { SetProperty(SubContinent_NameProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="G05_SubContinent_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<G05_SubContinent_Child> G05_SubContinent_SingleObjectProperty = RegisterProperty<G05_SubContinent_Child>(p => p.G05_SubContinent_SingleObject, "G05 SubContinent Single Object", RelationshipTypes.Child); /// <summary> /// Gets the G05 Sub Continent Single Object ("self load" child property). /// </summary> /// <value>The G05 Sub Continent Single Object.</value> public G05_SubContinent_Child G05_SubContinent_SingleObject { get { return GetProperty(G05_SubContinent_SingleObjectProperty); } private set { LoadProperty(G05_SubContinent_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="G05_SubContinent_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<G05_SubContinent_ReChild> G05_SubContinent_ASingleObjectProperty = RegisterProperty<G05_SubContinent_ReChild>(p => p.G05_SubContinent_ASingleObject, "G05 SubContinent ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the G05 Sub Continent ASingle Object ("self load" child property). /// </summary> /// <value>The G05 Sub Continent ASingle Object.</value> public G05_SubContinent_ReChild G05_SubContinent_ASingleObject { get { return GetProperty(G05_SubContinent_ASingleObjectProperty); } private set { LoadProperty(G05_SubContinent_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="G05_CountryObjects"/> property. /// </summary> public static readonly PropertyInfo<G05_CountryColl> G05_CountryObjectsProperty = RegisterProperty<G05_CountryColl>(p => p.G05_CountryObjects, "G05 Country Objects", RelationshipTypes.Child); /// <summary> /// Gets the G05 Country Objects ("self load" child property). /// </summary> /// <value>The G05 Country Objects.</value> public G05_CountryColl G05_CountryObjects { get { return GetProperty(G05_CountryObjectsProperty); } private set { LoadProperty(G05_CountryObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="G04_SubContinent"/> object. /// </summary> /// <returns>A reference to the created <see cref="G04_SubContinent"/> object.</returns> internal static G04_SubContinent NewG04_SubContinent() { return DataPortal.CreateChild<G04_SubContinent>(); } /// <summary> /// Factory method. Loads a <see cref="G04_SubContinent"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="G04_SubContinent"/> object.</returns> internal static G04_SubContinent GetG04_SubContinent(SafeDataReader dr) { G04_SubContinent obj = new G04_SubContinent(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="G04_SubContinent"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public G04_SubContinent() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="G04_SubContinent"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(SubContinent_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(G05_SubContinent_SingleObjectProperty, DataPortal.CreateChild<G05_SubContinent_Child>()); LoadProperty(G05_SubContinent_ASingleObjectProperty, DataPortal.CreateChild<G05_SubContinent_ReChild>()); LoadProperty(G05_CountryObjectsProperty, DataPortal.CreateChild<G05_CountryColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="G04_SubContinent"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(SubContinent_IDProperty, dr.GetInt32("SubContinent_ID")); LoadProperty(SubContinent_NameProperty, dr.GetString("SubContinent_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects. /// </summary> internal void FetchChildren() { LoadProperty(G05_SubContinent_SingleObjectProperty, G05_SubContinent_Child.GetG05_SubContinent_Child(SubContinent_ID)); LoadProperty(G05_SubContinent_ASingleObjectProperty, G05_SubContinent_ReChild.GetG05_SubContinent_ReChild(SubContinent_ID)); LoadProperty(G05_CountryObjectsProperty, G05_CountryColl.GetG05_CountryColl(SubContinent_ID)); } /// <summary> /// Inserts a new <see cref="G04_SubContinent"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(G02_Continent parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddG04_SubContinent", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Parent_Continent_ID", parent.Continent_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@SubContinent_ID", ReadProperty(SubContinent_IDProperty)).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@SubContinent_Name", ReadProperty(SubContinent_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); LoadProperty(SubContinent_IDProperty, (int) cmd.Parameters["@SubContinent_ID"].Value); } // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="G04_SubContinent"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateG04_SubContinent", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@SubContinent_ID", ReadProperty(SubContinent_IDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@SubContinent_Name", ReadProperty(SubContinent_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="G04_SubContinent"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { // flushes all pending data operations FieldManager.UpdateChildren(this); using (var cmd = new SqlCommand("DeleteG04_SubContinent", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@SubContinent_ID", ReadProperty(SubContinent_IDProperty)).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } // removes all previous references to children LoadProperty(G05_SubContinent_SingleObjectProperty, DataPortal.CreateChild<G05_SubContinent_Child>()); LoadProperty(G05_SubContinent_ASingleObjectProperty, DataPortal.CreateChild<G05_SubContinent_ReChild>()); LoadProperty(G05_CountryObjectsProperty, DataPortal.CreateChild<G05_CountryColl>()); } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
/* 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 *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 Microsoft.Research.DryadLinq; using Microsoft.Research.Peloponnese.Storage; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text.RegularExpressions; namespace DryadLinqTests { public class TypesInQueryTests { public static void Run(DryadLinqContext context, string matchPattern) { TestLog.Message(" **********************"); TestLog.Message(" TypesInQueryTests "); TestLog.Message(" **********************"); var tests = new Dictionary<string, Action>() { {"NonSealedTypeRecords", () => NonSealedTypeRecords(context) }, {"DerivedTypeRecords", () => DerivedTypeRecords(context) }, {"ObjectRecords", () => ObjectRecords(context) }, {"BadRecordsNotSerialized", () => BadRecordsNotSerialized(context) }, {"GroupByWithAnonymousTypes_Bug15675", () => GroupByWithAnonymousTypes_Bug15675(context) }, {"GroupByWithAnonymousTypes_Pipeline", () => GroupByWithAnonymousTypes_Pipeline(context) }, {"GroupByWithAnonymousTypes_MultipleAnonymousTypes", () => GroupByWithAnonymousTypes_MultipleAnonymousTypes(context) }, {"GroupByWithAnonymousTypes_GenericWithAnonTypeParam", () => GroupByWithAnonymousTypes_GenericWithAnonTypeParam(context) }, {"GroupByWithAnonymousTypes_ArrayOfAnon", () => GroupByWithAnonymousTypes_ArrayOfAnon(context) }, {"GroupByWithAnonymousTypes_NestedAnonTypes", () => GroupByWithAnonymousTypes_NestedAnonTypes(context) }, }; foreach (var test in tests) { if (Regex.IsMatch(test.Key, matchPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase)) { test.Value.Invoke(); } } } public static bool NonSealedTypeRecords(DryadLinqContext context) { string testName = "NonSealedTypeRecords"; TestLog.TestStart(testName); bool passed = true; try { IEnumerable<NonSealedClass>[] result = new IEnumerable<NonSealedClass>[2]; // cluster { context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); var output = pt1.Select(x => new NonSealedClass()).ToArray(); result[0] = output; } // local { context.LocalDebug = true; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); var output = pt1.Select(x => new NonSealedClass()).ToArray(); result[1] = output; } // compare result try { Validate.Check(result); } catch (Exception ex) { TestLog.Message("Error: " + ex.Message); passed &= false; } } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } public static bool DerivedTypeRecords(DryadLinqContext context) { string testName = "DerivedTypeRecords"; TestLog.TestStart(testName); bool passed = true; try { IEnumerable<ParentClass>[] result1 = new IEnumerable<ParentClass>[2]; IEnumerable<ChildClass>[] result2 = new IEnumerable<ChildClass>[2]; // cluster { context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); var output1 = pt1.Select(x => new ParentClass()).ToArray(); var output2 = pt1.Select(x => new ChildClass()).ToArray(); result1[0] = output1; result2[0] = output2; } // local { context.LocalDebug = true; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); var output1 = pt1.Select(x => new ParentClass()).ToArray(); var output2 = pt1.Select(x => new ChildClass()).ToArray(); result1[1] = output1; result2[1] = output2; } // compare result try { Validate.Check(result1); Validate.Check(result2); } catch (Exception ex) { TestLog.Message("Error: " + ex.Message); passed &= false; } } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } public static bool ObjectRecords(DryadLinqContext context) { string testName = "ObjectRecords"; TestLog.TestStart(testName); bool passed = true; try { IEnumerable<object>[] result = new IEnumerable<object>[2]; // cluster { context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); var output = pt1.Select(x => new object()).ToArray(); result[0] = output; } // local { context.LocalDebug = true; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); var output = pt1.Select(x => new object()).ToArray(); result[1] = output; } // compare result try { Validate.Check(result); } catch (Exception ex) { TestLog.Message("Error: " + ex.Message); passed &= false; } } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } public static bool BadRecordsNotSerialized(DryadLinqContext context) { string testName = "BadRecordsNotSerialized"; TestLog.TestStart(testName); bool passed = true; try { IEnumerable<string>[] result = new IEnumerable<string>[2]; // cluster { context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); var output = pt1.Select(x => (x % 2 == 0 ? new ChildClass() : new ParentClass())).Select(x => x is ChildClass ? "child" : "parent").ToArray(); result[0] = output; } // local { context.LocalDebug = true; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); var output = pt1.Select(x => (x % 2 == 0 ? new ChildClass() : new ParentClass())).Select(x => x is ChildClass ? "child" : "parent").ToArray(); result[1] = output; } // compare result try { Validate.Check(result); } catch (Exception ex) { TestLog.Message("Error: " + ex.Message); passed &= false; } } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } //Bug 15675 -- GroupBy creates a DryadOrderByNode which is confused by the anonymous type. // specifically, the call to DryadSort incorrectly referenced both the anonymous type and the code-gen proxy for the anonymous type. // -- the fix was to clean up how & when we process the types involved in the query so that only the proxy would be referenced. public static bool GroupByWithAnonymousTypes_Bug15675(DryadLinqContext context) { string testName = "GroupByWithAnonymousTypes_Bug15675"; TestLog.TestStart(testName); bool passed = true; try { // cluster context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); var result1 = pt1.Select(i => new { Num = i % 10 }) .GroupBy(x => x.Num, x => x.Num) .ToArray(); // local context.LocalDebug = true; IQueryable<int> pt2 = DataGenerator.GetSimpleFileSets(context); var result2 = pt2.Select(i => new { Num = i % 10 }) .GroupBy(x => x.Num, x => x.Num) .ToArray(); passed &= (result1.Count() == result2.Count()); passed &= (result1.Where(g => g.Key == 1).SelectMany(g => g).Count() == result2.Where(g => g.Key == 1).SelectMany(g => g).Count()); } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } public static bool GroupByWithAnonymousTypes_Pipeline(DryadLinqContext context) { string testName = "GroupByWithAnonymousTypes_Pipeline"; TestLog.TestStart(testName); bool passed = true; try { // cluster context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); var result1 = pt1.Select(i => new { Num = i % 10 }) .Where(x => true) .GroupBy(x => x.Num, x => x.Num) .ToArray(); // local context.LocalDebug = true; IQueryable<int> pt2 = DataGenerator.GetSimpleFileSets(context); var result2 = pt2.Select(i => new { Num = i % 10 }) .Where(x => true) .GroupBy(x => x.Num, x => x.Num) .ToArray(); passed &= (result1.Count() == result2.Count()); passed &= (result1.Where(g => g.Key == 1).SelectMany(g => g).Count() == result2.Where(g => g.Key == 1).SelectMany(g => g).Count()); } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } public static bool GroupByWithAnonymousTypes_MultipleAnonymousTypes(DryadLinqContext context) { string testName = "GroupByWithAnonymousTypes_MultipleAnonymousTypes"; TestLog.TestStart(testName); bool passed = true; try { // cluster context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); var result1 = pt1.Select(i => new { Num = i % 10 }) .Where(x => true) .Select(i => new { Num2 = i.Num }) .GroupBy(x => x.Num2, x => x.Num2) .ToArray(); // local context.LocalDebug = true; IQueryable<int> pt2 = DataGenerator.GetSimpleFileSets(context); var result2 = pt2.Select(i => new { Num = i % 10 }) .Where(x => true) .Select(i => new { Num2 = i.Num }) .GroupBy(x => x.Num2, x => x.Num2) .ToArray(); passed &= (result1.Count() == result2.Count()); passed &= (result1.Where(g => g.Key == 1).SelectMany(g => g).Count() == result2.Where(g => g.Key == 1).SelectMany(g => g).Count()); } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } public static bool GroupByWithAnonymousTypes_GenericWithAnonTypeParam(DryadLinqContext context) { string testName = "GroupByWithAnonymousTypes_GenericWithAnonTypeParam"; TestLog.TestStart(testName); bool passed = true; try { // cluster { context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); var result1 = pt1.Select(i => MakeNewMyGenericType(new { Num = i % 10 })) .GroupBy(x => x.Field.Num, x => x.Field.Num) .ToArray(); // local context.LocalDebug = true; IQueryable<int> pt2 = DataGenerator.GetSimpleFileSets(context); var result2 = pt2.Select(i => MakeNewMyGenericType(new { Num = i % 10 })) .GroupBy(x => x.Field.Num, x => x.Field.Num) .ToArray(); passed &= (result1.Count() == result2.Count()); passed &= (result1.Where(g => g.Key == 1).SelectMany(g => g).Count() == result2.Where(g => g.Key == 1).SelectMany(g => g).Count()); } } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } public static bool GroupByWithAnonymousTypes_ArrayOfAnon(DryadLinqContext context) { string testName = "GroupByWithAnonymousTypes_ArrayOfAnon"; TestLog.TestStart(testName); bool passed = true; try { // cluster context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); var result1 = pt1.Select(i => new[] { new { Num = i % 10 } }) .GroupBy(x => x[0].Num, x => x[0].Num) .ToArray(); // local context.LocalDebug = true; IQueryable<int> pt2 = DataGenerator.GetSimpleFileSets(context); var result2 = pt2.Select(i => new[] { new { Num = i % 10 } }) .GroupBy(x => x[0].Num, x => x[0].Num) .ToArray(); passed &= (result1.Count() == result2.Count()); passed &= (result1.Where(g => g.Key == 1).SelectMany(g => g).Count() == result2.Where(g => g.Key == 1).SelectMany(g => g).Count()); } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } public static bool GroupByWithAnonymousTypes_NestedAnonTypes(DryadLinqContext context) { string testName = "GroupByWithAnonymousTypes_NestedAnonTypes"; TestLog.TestStart(testName); bool passed = true; try { // cluster context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); var result1 = pt1.Select(i => new { Num = new { NumInner = new int?(i % 10) } }) // nullable-fields present particular challenge. .GroupBy(x => x.Num.NumInner, x => x.Num.NumInner) .ToArray(); // local context.LocalDebug = true; IQueryable<int> pt2 = DataGenerator.GetSimpleFileSets(context); var result2 = pt2.Select(i => new { Num = new { NumInner = new int?(i % 10) } }) // nullable-fields present particular challenge. .GroupBy(x => x.Num.NumInner, x => x.Num.NumInner) .ToArray(); passed &= (result1.Count() == result2.Count()); passed &= (result1.Where(g => g.Key == 1).SelectMany(g => g).Count() == result2.Where(g => g.Key == 1).SelectMany(g => g).Count()); } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } // This is a helper method to allow 'naming the anonymous type' // -- there is no name to give 'anonymous' inline to the original query, // but a generic-method only has to call it by pseudonym T, which is a useful workaround. public static MyGenericType<T> MakeNewMyGenericType<T>(T item) { return new MyGenericType<T>(item); } } [Serializable] public class MyGenericType<T> { public T Field; public MyGenericType(T data) { Field = data; } } [Serializable] public class NonSealedClass { public int X; } [Serializable] public class ParentClass { public int X; } [Serializable] public class ChildClass : ParentClass { public int Y; } }
// 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.Diagnostics; using System.IO; using System.Net.NetworkInformation; using System.Text; // Relevant cookie specs: // // PERSISTENT CLIENT STATE HTTP COOKIES (1996) // From <http:// web.archive.org/web/20020803110822/http://wp.netscape.com/newsref/std/cookie_spec.html> // // RFC2109 HTTP State Management Mechanism (February 1997) // From <http:// tools.ietf.org/html/rfc2109> // // RFC2965 HTTP State Management Mechanism (October 2000) // From <http:// tools.ietf.org/html/rfc2965> // // RFC6265 HTTP State Management Mechanism (April 2011) // From <http:// tools.ietf.org/html/rfc6265> // // The Version attribute of the cookie header is defined and used only in RFC2109 and RFC2965 cookie // specs and specifies Version=1. The Version attribute is not used in the Netscape cookie spec // (considered as Version=0). Nor is it used in the most recent cookie spec, RFC6265, introduced in 2011. // RFC6265 deprecates all previous cookie specs including the Version attribute. // // Cookies without an explicit Domain attribute will only match a potential uri that matches the original // uri from where the cookie came from. // // For explicit Domain attribute in the cookie, the following rules apply: // // Version=0 (Netscape, RFC6265) allows the Domain attribute of the cookie to match any tail substring // of the host uri. // // Version=1 related cookie specs only allows the Domain attribute to match the host uri based on a // more restricted set of rules. // // According to RFC2109/RFC2965, the cookie will be rejected for matching if: // * The value for the Domain attribute contains no embedded dots or does not start with a dot. // * The value for the request-host does not domain-match the Domain attribute. // " The request-host is a FQDN (not IP address) and has the form HD, where D is the value of the Domain // attribute, and H is a string that contains one or more dots. // // Examples: // * A cookie from request-host y.x.foo.com for Domain=.foo.com would be rejected, because H is y.x // and contains a dot. // // * A cookie from request-host x.foo.com for Domain=.foo.com would be accepted. // // * A cookie with Domain=.com or Domain=.com., will always be rejected, because there is no embedded dot. // // * A cookie with Domain=ajax.com will be rejected because the value for Domain does not begin with a dot. namespace System.Net { internal struct HeaderVariantInfo { private readonly string _name; private readonly CookieVariant _variant; internal HeaderVariantInfo(string name, CookieVariant variant) { _name = name; _variant = variant; } internal string Name { get { return _name; } } internal CookieVariant Variant { get { return _variant; } } } // CookieContainer // // Manage cookies for a user (implicit). Based on RFC 2965. [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class CookieContainer { public const int DefaultCookieLimit = 300; public const int DefaultPerDomainCookieLimit = 20; public const int DefaultCookieLengthLimit = 4096; private static readonly HeaderVariantInfo[] s_headerInfo = { new HeaderVariantInfo(HttpKnownHeaderNames.SetCookie, CookieVariant.Rfc2109), new HeaderVariantInfo(HttpKnownHeaderNames.SetCookie2, CookieVariant.Rfc2965) }; private readonly Hashtable m_domainTable = new Hashtable(); // Do not rename (binary serialization) private int m_maxCookieSize = DefaultCookieLengthLimit; // Do not rename (binary serialization) private int m_maxCookies = DefaultCookieLimit; // Do not rename (binary serialization) private int m_maxCookiesPerDomain = DefaultPerDomainCookieLimit; // Do not rename (binary serialization) private int m_count = 0; // Do not rename (binary serialization) private string m_fqdnMyDomain = string.Empty; // Do not rename (binary serialization) public CookieContainer() { string domain = HostInformation.DomainName; if (domain != null && domain.Length > 1) { m_fqdnMyDomain = '.' + domain; } // Otherwise it will remain string.Empty. } public CookieContainer(int capacity) : this() { if (capacity <= 0) { throw new ArgumentException(SR.net_toosmall, "Capacity"); } m_maxCookies = capacity; } public CookieContainer(int capacity, int perDomainCapacity, int maxCookieSize) : this(capacity) { if (perDomainCapacity != Int32.MaxValue && (perDomainCapacity <= 0 || perDomainCapacity > capacity)) { throw new ArgumentOutOfRangeException(nameof(perDomainCapacity), SR.Format(SR.net_cookie_capacity_range, "PerDomainCapacity", 0, capacity)); } m_maxCookiesPerDomain = perDomainCapacity; if (maxCookieSize <= 0) { throw new ArgumentException(SR.net_toosmall, "MaxCookieSize"); } m_maxCookieSize = maxCookieSize; } // NOTE: after shrinking the capacity, Count can become greater than Capacity. public int Capacity { get { return m_maxCookies; } set { if (value <= 0 || (value < m_maxCookiesPerDomain && m_maxCookiesPerDomain != Int32.MaxValue)) { throw new ArgumentOutOfRangeException(nameof(value), SR.Format(SR.net_cookie_capacity_range, "Capacity", 0, m_maxCookiesPerDomain)); } if (value < m_maxCookies) { m_maxCookies = value; AgeCookies(null); } m_maxCookies = value; } } /// <devdoc> /// <para>Returns the total number of cookies in the container.</para> /// </devdoc> public int Count { get { return m_count; } } public int MaxCookieSize { get { return m_maxCookieSize; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value)); } m_maxCookieSize = value; } } /// <devdoc> /// <para>After shrinking domain capacity, each domain will less hold than new domain capacity.</para> /// </devdoc> public int PerDomainCapacity { get { return m_maxCookiesPerDomain; } set { if (value <= 0 || (value > m_maxCookies && value != Int32.MaxValue)) { throw new ArgumentOutOfRangeException(nameof(value)); } if (value < m_maxCookiesPerDomain) { m_maxCookiesPerDomain = value; AgeCookies(null); } m_maxCookiesPerDomain = value; } } // This method will construct a faked URI: the Domain property is required for param. public void Add(Cookie cookie) { if (cookie == null) { throw new ArgumentNullException(nameof(cookie)); } if (cookie.Domain.Length == 0) { throw new ArgumentException( SR.Format(SR.net_emptystringcall, nameof(cookie) + "." + nameof(cookie.Domain)), nameof(cookie) + "." + nameof(cookie.Domain)); } Uri uri; var uriSb = new StringBuilder(); // We cannot add an invalid cookie into the container. // Trying to prepare Uri for the cookie verification. uriSb.Append(cookie.Secure ? UriScheme.Https : UriScheme.Http).Append(UriScheme.SchemeDelimiter); // If the original cookie has an explicitly set domain, copy it over to the new cookie. if (!cookie.DomainImplicit) { if (cookie.Domain[0] == '.') { uriSb.Append("0"); // URI cctor should consume this faked host. } } uriSb.Append(cookie.Domain); // Either keep Port as implicit or set it according to original cookie. if (cookie.PortList != null) { uriSb.Append(":").Append(cookie.PortList[0]); } // Path must be present, set to root by default. uriSb.Append(cookie.Path); if (!Uri.TryCreate(uriSb.ToString(), UriKind.Absolute, out uri)) throw new CookieException(SR.Format(SR.net_cookie_attribute, "Domain", cookie.Domain)); // We don't know cookie verification status, so re-create the cookie and verify it. Cookie new_cookie = cookie.Clone(); new_cookie.VerifySetDefaults(new_cookie.Variant, uri, IsLocalDomain(uri.Host), m_fqdnMyDomain, true, true); Add(new_cookie, true); } // This method is called *only* when cookie verification is done, so unlike with public // Add(Cookie cookie) the cookie is in a reasonable condition. internal void Add(Cookie cookie, bool throwOnError) { PathList pathList; if (cookie.Value.Length > m_maxCookieSize) { if (throwOnError) { throw new CookieException(SR.Format(SR.net_cookie_size, cookie.ToString(), m_maxCookieSize)); } return; } try { lock (m_domainTable.SyncRoot) { pathList = (PathList)m_domainTable[cookie.DomainKey]; if (pathList == null) { m_domainTable[cookie.DomainKey] = (pathList = new PathList()); } } int domain_count = pathList.GetCookiesCount(); CookieCollection cookies; lock (pathList.SyncRoot) { cookies = (CookieCollection)pathList[cookie.Path]; if (cookies == null) { cookies = new CookieCollection(); pathList[cookie.Path] = cookies; } } if (cookie.Expired) { // Explicit removal command (Max-Age == 0) lock (cookies) { int idx = cookies.IndexOf(cookie); if (idx != -1) { cookies.RemoveAt(idx); --m_count; } } } else { // This is about real cookie adding, check Capacity first if (domain_count >= m_maxCookiesPerDomain && !AgeCookies(cookie.DomainKey)) { return; // Cannot age: reject new cookie } else if (m_count >= m_maxCookies && !AgeCookies(null)) { return; // Cannot age: reject new cookie } // About to change the collection lock (cookies) { m_count += cookies.InternalAdd(cookie, true); } } } catch (OutOfMemoryException) { throw; } catch (Exception e) { if (throwOnError) { throw new CookieException(SR.net_container_add_cookie, e); } } } // This function, when called, must delete at least one cookie. // If there are expired cookies in given scope they are cleaned up. // If nothing is found the least used Collection will be found and removed // from the container. // // Also note that expired cookies are also removed during request preparation // (this.GetCookies method). // // Param. 'domain' == null means to age in the whole container. private bool AgeCookies(string domain) { Debug.Assert(m_maxCookies != 0); Debug.Assert(m_maxCookiesPerDomain != 0); int removed = 0; DateTime oldUsed = DateTime.MaxValue; DateTime tempUsed; CookieCollection lruCc = null; string lruDomain = null; string tempDomain = null; PathList pathList; int domain_count = 0; int itemp = 0; float remainingFraction = 1.0F; // The container was shrunk, might need additional cleanup for each domain if (m_count > m_maxCookies) { // Means the fraction of the container to be left. // Each domain will be cut accordingly. remainingFraction = (float)m_maxCookies / (float)m_count; } lock (m_domainTable.SyncRoot) { foreach (DictionaryEntry entry in m_domainTable) { if (domain == null) { tempDomain = (string)entry.Key; pathList = (PathList)entry.Value; // Aliasing to trick foreach } else { tempDomain = domain; pathList = (PathList)m_domainTable[domain]; } domain_count = 0; // Cookies in the domain lock (pathList.SyncRoot) { foreach (CookieCollection cc in pathList.Values) { itemp = ExpireCollection(cc); removed += itemp; m_count -= itemp; // Update this container's count domain_count += cc.Count; // We also find the least used cookie collection in ENTIRE container. // We count the collection as LRU only if it holds 1+ elements. if (cc.Count > 0 && (tempUsed = cc.TimeStamp(CookieCollection.Stamp.Check)) < oldUsed) { lruDomain = tempDomain; lruCc = cc; oldUsed = tempUsed; } } } // Check if we have reduced to the limit of the domain by expiration only. int min_count = Math.Min((int)(domain_count * remainingFraction), Math.Min(m_maxCookiesPerDomain, m_maxCookies) - 1); if (domain_count > min_count) { // This case requires sorting all domain collections by timestamp. Array cookies; Array stamps; lock (pathList.SyncRoot) { cookies = Array.CreateInstance(typeof(CookieCollection), pathList.Count); stamps = Array.CreateInstance(typeof(DateTime), pathList.Count); foreach (CookieCollection cc in pathList.Values) { stamps.SetValue(cc.TimeStamp(CookieCollection.Stamp.Check), itemp); cookies.SetValue(cc, itemp); ++itemp; } } Array.Sort(stamps, cookies); itemp = 0; for (int i = 0; i < cookies.Length; ++i) { CookieCollection cc = (CookieCollection)cookies.GetValue(i); lock (cc) { while (domain_count > min_count && cc.Count > 0) { cc.RemoveAt(0); --domain_count; --m_count; ++removed; } } if (domain_count <= min_count) { break; } } if (domain_count > min_count && domain != null) { // Cannot complete aging of explicit domain (no cookie adding allowed). return false; } } } } // We have completed aging of the specified domain. if (domain != null) { return true; } // The rest is for entire container aging. // We must get at least one free slot. // Don't need to apply LRU if we already cleaned something. if (removed != 0) { return true; } if (oldUsed == DateTime.MaxValue) { // Something strange. Either capacity is 0 or all collections are locked with cc.Used. return false; } // Remove oldest cookies from the least used collection. lock (lruCc) { while (m_count >= m_maxCookies && lruCc.Count > 0) { lruCc.RemoveAt(0); --m_count; } } return true; } // Return number of cookies removed from the collection. private int ExpireCollection(CookieCollection cc) { lock (cc) { int oldCount = cc.Count; int idx = oldCount - 1; // Cannot use enumerator as we are going to alter collection. while (idx >= 0) { Cookie cookie = cc[idx]; if (cookie.Expired) { cc.RemoveAt(idx); } --idx; } return oldCount - cc.Count; } } public void Add(CookieCollection cookies) { if (cookies == null) { throw new ArgumentNullException(nameof(cookies)); } foreach (Cookie c in cookies) { Add(c); } } // This will try (if needed) get the full domain name of the host given the Uri. // NEVER call this function from internal methods with 'fqdnRemote' == null. // Since this method counts security issue for DNS and hence will slow // the performance. internal bool IsLocalDomain(string host) { int dot = host.IndexOf('.'); if (dot == -1) { // No choice but to treat it as a host on the local domain. // This also covers 'localhost' and 'loopback'. return true; } // Quick test for typical cases: loopback addresses for IPv4 and IPv6. if ((host == "127.0.0.1") || (host == "::1") || (host == "0:0:0:0:0:0:0:1")) { return true; } // Test domain membership. if (string.Compare(m_fqdnMyDomain, 0, host, dot, m_fqdnMyDomain.Length, StringComparison.OrdinalIgnoreCase) == 0) { return true; } // Test for "127.###.###.###" without using regex. string[] ipParts = host.Split('.'); if (ipParts != null && ipParts.Length == 4 && ipParts[0] == "127") { int i; for (i = 1; i < ipParts.Length; i++) { string part = ipParts[i]; switch (part.Length) { case 3: if (part[2] < '0' || part[2] > '9') { break; } goto case 2; case 2: if (part[1] < '0' || part[1] > '9') { break; } goto case 1; case 1: if (part[0] < '0' || part[0] > '9') { break; } continue; } break; } if (i == 4) { return true; } } return false; } public void Add(Uri uri, Cookie cookie) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (cookie == null) { throw new ArgumentNullException(nameof(cookie)); } Cookie new_cookie = cookie.Clone(); new_cookie.VerifySetDefaults(new_cookie.Variant, uri, IsLocalDomain(uri.Host), m_fqdnMyDomain, true, true); Add(new_cookie, true); } public void Add(Uri uri, CookieCollection cookies) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (cookies == null) { throw new ArgumentNullException(nameof(cookies)); } bool isLocalDomain = IsLocalDomain(uri.Host); foreach (Cookie c in cookies) { Cookie new_cookie = c.Clone(); new_cookie.VerifySetDefaults(new_cookie.Variant, uri, isLocalDomain, m_fqdnMyDomain, true, true); Add(new_cookie, true); } } internal CookieCollection CookieCutter(Uri uri, string headerName, string setCookieHeader, bool isThrow) { if (NetEventSource.IsEnabled) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"uri:{uri} headerName:{headerName} setCookieHeader:{setCookieHeader} isThrow:{isThrow}"); } CookieCollection cookies = new CookieCollection(); CookieVariant variant = CookieVariant.Unknown; if (headerName == null) { variant = CookieVariant.Default; } else { for (int i = 0; i < s_headerInfo.Length; ++i) { if ((String.Compare(headerName, s_headerInfo[i].Name, StringComparison.OrdinalIgnoreCase) == 0)) { variant = s_headerInfo[i].Variant; } } } bool isLocalDomain = IsLocalDomain(uri.Host); try { CookieParser parser = new CookieParser(setCookieHeader); do { Cookie cookie = parser.Get(); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"CookieParser returned cookie:{cookie}"); if (cookie == null) { break; } // Parser marks invalid cookies this way if (String.IsNullOrEmpty(cookie.Name)) { if (isThrow) { throw new CookieException(SR.net_cookie_format); } // Otherwise, ignore (reject) cookie continue; } // This will set the default values from the response URI // AND will check for cookie validity if (!cookie.VerifySetDefaults(variant, uri, isLocalDomain, m_fqdnMyDomain, true, isThrow)) { continue; } // If many same cookies arrive we collapse them into just one, hence setting // parameter isStrict = true below cookies.InternalAdd(cookie, true); } while (true); } catch (OutOfMemoryException) { throw; } catch (Exception e) { if (isThrow) { throw new CookieException(SR.Format(SR.net_cookie_parse_header, uri.AbsoluteUri), e); } } foreach (Cookie c in cookies) { Add(c, isThrow); } return cookies; } public CookieCollection GetCookies(Uri uri) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } return InternalGetCookies(uri) ?? new CookieCollection(); } internal CookieCollection InternalGetCookies(Uri uri) { if (m_count == 0) { return null; } bool isSecure = (uri.Scheme == UriScheme.Https || uri.Scheme == UriScheme.Wss); int port = uri.Port; CookieCollection cookies = null; var domainAttributeMatchAnyCookieVariant = new System.Collections.Generic.List<string>(); System.Collections.Generic.List<string> domainAttributeMatchOnlyCookieVariantPlain = null; string fqdnRemote = uri.Host; // Add initial candidates to match Domain attribute of possible cookies. // For these Domains, cookie can have any CookieVariant enum value. domainAttributeMatchAnyCookieVariant.Add(fqdnRemote); domainAttributeMatchAnyCookieVariant.Add("." + fqdnRemote); int dot = fqdnRemote.IndexOf('.'); if (dot == -1) { // DNS.resolve may return short names even for other inet domains ;-( // We _don't_ know what the exact domain is, so try also grab short hostname cookies. // Grab long name from the local domain if (m_fqdnMyDomain != null && m_fqdnMyDomain.Length != 0) { domainAttributeMatchAnyCookieVariant.Add(fqdnRemote + m_fqdnMyDomain); // Grab the local domain itself domainAttributeMatchAnyCookieVariant.Add(m_fqdnMyDomain); } } else { // Grab the host domain domainAttributeMatchAnyCookieVariant.Add(fqdnRemote.Substring(dot)); // The following block is only for compatibility with Version0 spec. // Still, we'll add only Plain-Variant cookies if found under below keys if (fqdnRemote.Length > 2) { // We ignore the '.' at the end on the name int last = fqdnRemote.LastIndexOf('.', fqdnRemote.Length - 2); // AND keys with <2 dots inside. if (last > 0) { last = fqdnRemote.LastIndexOf('.', last - 1); } if (last != -1) { while ((dot < last) && (dot = fqdnRemote.IndexOf('.', dot + 1)) != -1) { if (domainAttributeMatchOnlyCookieVariantPlain == null) { domainAttributeMatchOnlyCookieVariantPlain = new System.Collections.Generic.List<string>(); } // These candidates can only match CookieVariant.Plain cookies. domainAttributeMatchOnlyCookieVariantPlain.Add(fqdnRemote.Substring(dot)); } } } } BuildCookieCollectionFromDomainMatches(uri, isSecure, port, ref cookies, domainAttributeMatchAnyCookieVariant, false); if (domainAttributeMatchOnlyCookieVariantPlain != null) { BuildCookieCollectionFromDomainMatches(uri, isSecure, port, ref cookies, domainAttributeMatchOnlyCookieVariantPlain, true); } return cookies; } private void BuildCookieCollectionFromDomainMatches(Uri uri, bool isSecure, int port, ref CookieCollection cookies, System.Collections.Generic.List<string> domainAttribute, bool matchOnlyPlainCookie) { for (int i = 0; i < domainAttribute.Count; i++) { bool found = false; bool defaultAdded = false; PathList pathList; lock (m_domainTable.SyncRoot) { pathList = (PathList)m_domainTable[domainAttribute[i]]; if (pathList == null) { continue; } } lock (pathList.SyncRoot) { // Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations. IDictionaryEnumerator e = pathList.GetEnumerator(); while (e.MoveNext()) { string path = (string)e.Key; if (uri.AbsolutePath.StartsWith(CookieParser.CheckQuoted(path))) { found = true; CookieCollection cc = (CookieCollection)e.Value; cc.TimeStamp(CookieCollection.Stamp.Set); MergeUpdateCollections(ref cookies, cc, port, isSecure, matchOnlyPlainCookie); if (path == "/") { defaultAdded = true; } } else if (found) { break; } } } if (!defaultAdded) { CookieCollection cc = (CookieCollection)pathList["/"]; if (cc != null) { cc.TimeStamp(CookieCollection.Stamp.Set); MergeUpdateCollections(ref cookies, cc, port, isSecure, matchOnlyPlainCookie); } } // Remove unused domain // (This is the only place that does domain removal) if (pathList.Count == 0) { lock (m_domainTable.SyncRoot) { m_domainTable.Remove(domainAttribute[i]); } } } } private void MergeUpdateCollections(ref CookieCollection destination, CookieCollection source, int port, bool isSecure, bool isPlainOnly) { lock (source) { // Cannot use foreach as we are going to update 'source' for (int idx = 0; idx < source.Count; ++idx) { bool to_add = false; Cookie cookie = source[idx]; if (cookie.Expired) { // If expired, remove from container and don't add to the destination source.RemoveAt(idx); --m_count; --idx; } else { // Add only if port does match to this request URI // or was not present in the original response. if (isPlainOnly && cookie.Variant != CookieVariant.Plain) { ; // Don't add } else if (cookie.PortList != null) { foreach (int p in cookie.PortList) { if (p == port) { to_add = true; break; } } } else { // It was implicit Port, always OK to add. to_add = true; } // Refuse to add a secure cookie into an 'unsecure' destination if (cookie.Secure && !isSecure) { to_add = false; } if (to_add) { // In 'source' are already ordered. // If two same cookies come from different 'source' then they // will follow (not replace) each other. if (destination == null) { destination = new CookieCollection(); } destination.InternalAdd(cookie, false); } } } } } public string GetCookieHeader(Uri uri) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } string dummy; return GetCookieHeader(uri, out dummy); } internal string GetCookieHeader(Uri uri, out string optCookie2) { CookieCollection cookies = InternalGetCookies(uri); if (cookies == null) { optCookie2 = string.Empty; return string.Empty; } string delimiter = string.Empty; StringBuilder builder = StringBuilderCache.Acquire(); for (int i = 0; i < cookies.Count; i++) { builder.Append(delimiter); cookies[i].ToString(builder); delimiter = "; "; } optCookie2 = cookies.IsOtherVersionSeen ? (Cookie.SpecialAttributeLiteral + CookieFields.VersionAttributeName + Cookie.EqualsLiteral + Cookie.MaxSupportedVersionString) : string.Empty; return StringBuilderCache.GetStringAndRelease(builder); } public void SetCookies(Uri uri, string cookieHeader) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (cookieHeader == null) { throw new ArgumentNullException(nameof(cookieHeader)); } CookieCutter(uri, null, cookieHeader, true); // Will throw on error } } // PathList needs to be public in order to maintain binary serialization compatibility as the System shim // needs to have access to type-forward it. [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class PathList { // Usage of PathList depends on it being shallowly immutable; // adding any mutable fields to it would result in breaks. private readonly SortedList m_list = SortedList.Synchronized(new SortedList(PathListComparer.StaticInstance)); // Do not rename (binary serialization) internal int Count => m_list.Count; internal int GetCookiesCount() { int count = 0; lock (SyncRoot) { foreach (CookieCollection cc in m_list.Values) { count += cc.Count; } } return count; } internal ICollection Values { get { return m_list.Values; } } internal object this[string s] { get { lock (SyncRoot) { return m_list[s]; } } set { lock (SyncRoot) { Debug.Assert(value != null); m_list[s] = value; } } } internal IDictionaryEnumerator GetEnumerator() { lock (SyncRoot) { return m_list.GetEnumerator(); } } internal object SyncRoot => m_list.SyncRoot; [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] private sealed class PathListComparer : IComparer { internal static readonly PathListComparer StaticInstance = new PathListComparer(); int IComparer.Compare(object ol, object or) { string pathLeft = CookieParser.CheckQuoted((string)ol); string pathRight = CookieParser.CheckQuoted((string)or); int ll = pathLeft.Length; int lr = pathRight.Length; int length = Math.Min(ll, lr); for (int i = 0; i < length; ++i) { if (pathLeft[i] != pathRight[i]) { return pathLeft[i] - pathRight[i]; } } return lr - ll; } } } }
// // Authors: // Ben Motmans <ben.motmans@gmail.com> // // Copyright (c) 2007 Ben Motmans // // 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 Gtk; using System; using System.Collections.Generic; using MonoDevelop.Database.Sql; namespace MonoDevelop.Database.Components { public class SortedColumnListStore { public event EventHandler ColumnToggled; protected ColumnSchemaCollection columns; protected ListStore store; public const int ColSelectIndex = 0; public const int ColNameIndex = 1; public const int ColObjIndex = 2; protected bool singleCheck; public SortedColumnListStore (ColumnSchemaCollection columns) { if (columns == null) throw new ArgumentNullException ("columns"); this.columns = columns; store = new ListStore (typeof (bool), typeof (string), typeof (ColumnSchema)); store.SetSortColumnId (ColNameIndex, SortType.Ascending); store.SetSortFunc (ColNameIndex, new TreeIterCompareFunc (SortName)); foreach (ColumnSchema col in columns) AddColumn (col); columns.ItemAdded += new SortedCollectionItemEventHandler<ColumnSchema> (OnColumnAdded); columns.ItemRemoved += new SortedCollectionItemEventHandler<ColumnSchema> (OnColumnRemoved); } public ListStore Store { get { return store; } } public virtual void Clear () { if (store != null) store.Clear (); } public virtual bool SingleCheck { get { return singleCheck; } set { if (value != singleCheck) { singleCheck = value; if (value) DeselectAll (); } } } public virtual ColumnSchema GetColumnSchema (TreeIter iter) { if (!iter.Equals (TreeIter.Zero)) return store.GetValue (iter, ColObjIndex) as ColumnSchema; return null; } public virtual IEnumerable<ColumnSchema> CheckedColumns { get { TreeIter iter; if (store.GetIterFirst (out iter)) { do { bool chk = (bool)store.GetValue (iter, ColSelectIndex); if (chk) yield return store.GetValue (iter, ColObjIndex) as ColumnSchema; } while (store.IterNext (ref iter)); } } } public virtual bool IsColumnChecked { get { TreeIter iter; if (store.GetIterFirst (out iter)) { do { bool chk = (bool)store.GetValue (iter, ColSelectIndex); if (chk) return true; } while (store.IterNext (ref iter)); } return false; } } public virtual void SelectAll () { SetSelectState (true); } public virtual void DeselectAll () { SetSelectState (false); } public virtual void Select (string name) { if (name == null) throw new ArgumentNullException ("name"); ColumnSchema col = columns.Search (name); // FIXME: This is a workaround, last item on the list isn't find by columns.Search. // SortedCollectionBase.BinarySearchIndex Isn't working. if (col == null) if (columns[columns.Count -1].Name.IndexOf (name, StringComparison.OrdinalIgnoreCase) > -1) Select (columns[columns.Count -1]); if (col != null) Select (col); } public virtual void Select (ColumnSchema column) { if (column == null) throw new ArgumentNullException ("column"); TreeIter iter = GetTreeIter (column); if (!iter.Equals (TreeIter.Zero)) { if (singleCheck) SetSelectState (false); store.SetValue (iter, ColSelectIndex, true); OnColumnToggled (); } } public virtual void ToggleSelect (TreeIter iter) { bool val = (bool) store.GetValue (iter, ColSelectIndex); bool newVal = !val; if (newVal && singleCheck) SetSelectState (false); store.SetValue (iter, ColSelectIndex, !val); OnColumnToggled (); } protected virtual void SetSelectState (bool state) { TreeIter iter; if (store.GetIterFirst (out iter)) { do { store.SetValue (iter, ColSelectIndex, state); } while (store.IterNext (ref iter)); } } protected virtual TreeIter GetTreeIter (ColumnSchema column) { TreeIter iter; if (store.GetIterFirst (out iter)) { do { object obj = store.GetValue (iter, ColObjIndex); if (obj == column) return iter; } while (store.IterNext (ref iter)); } return TreeIter.Zero; } protected virtual void OnColumnAdded (object sender, SortedCollectionItemEventArgs<ColumnSchema> args) { AddColumn (args.Item); } protected virtual void AddColumn (ColumnSchema column) { store.AppendValues (false, column.Name, column); column.Changed += delegate (object sender, EventArgs args) { TreeIter iter = GetTreeIter (sender as ColumnSchema); if (!iter.Equals (TreeIter.Zero)) store.SetValue (iter, ColNameIndex, column.Name); }; } protected virtual void OnColumnRemoved (object sender, SortedCollectionItemEventArgs<ColumnSchema> args) { TreeIter iter = GetTreeIter (args.Item); if (!iter.Equals (TreeIter.Zero)) store.Remove (ref iter); } protected virtual int SortName (TreeModel model, TreeIter iter1, TreeIter iter2) { string name1 = model.GetValue (iter1, ColNameIndex) as string; string name2 = model.GetValue (iter2, ColNameIndex) as string; if (name1 == null && name2 == null) return 0; else if (name1 == null) return -1; else if (name2 == null) return 1; return name1.CompareTo (name2); } protected virtual void OnColumnToggled () { if (ColumnToggled != null) ColumnToggled (this, EventArgs.Empty); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO.PortsTests; using System.Text; using System.Threading; using System.Threading.Tasks; using Legacy.Support; using Xunit; using ThreadState = System.Threading.ThreadState; namespace System.IO.Ports.Tests { public class SerialStream_WriteByte_Generic : PortsTest { // Set bounds fore random timeout values. // If the min is to low write will not timeout accurately and the testcase will fail private const int minRandomTimeout = 250; // If the max is to large then the testcase will take forever to run private const int maxRandomTimeout = 2000; // If the percentage difference between the expected timeout and the actual timeout // found through Stopwatch is greater then 10% then the timeout value was not correctly // to the write method and the testcase fails. private const double maxPercentageDifference = .15; private const int NUM_TRYS = 5; private const byte DEFAULT_BYTE = 0; #region Test Cases [ConditionalFact(nameof(HasOneSerialPort))] public void WriteAfterClose() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying write method throws exception after a call to Cloes()"); com.Open(); Stream serialStream = com.BaseStream; com.Close(); VerifyWriteException(serialStream, typeof(ObjectDisposedException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void WriteAfterBaseStreamClose() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying write method throws exception after a call to BaseStream.Close()"); com.Open(); Stream serialStream = com.BaseStream; com.BaseStream.Close(); VerifyWriteException(serialStream, typeof(ObjectDisposedException)); } } [ConditionalFact(nameof(HasNullModem))] public void Timeout() { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { var rndGen = new Random(-55); com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com1.Handshake = Handshake.XOnXOff; Debug.WriteLine("Verifying WriteTimeout={0}", com1.WriteTimeout); com1.Open(); com2.Open(); com2.BaseStream.WriteByte(XOnOff.XOFF); Thread.Sleep(250); com2.Close(); VerifyTimeout(com1); } } [OuterLoop("Slow test")] [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void SuccessiveReadTimeout() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { var rndGen = new Random(-55); com.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com.Handshake = Handshake.RequestToSendXOnXOff; // com.Encoding = new System.Text.UTF7Encoding(); com.Encoding = Encoding.Unicode; Debug.WriteLine("Verifying WriteTimeout={0} with successive call to write method", com.WriteTimeout); com.Open(); try { com.BaseStream.WriteByte(DEFAULT_BYTE); } catch (TimeoutException) { } VerifyTimeout(com); } } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void SuccessiveReadTimeoutWithWriteSucceeding() { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { var rndGen = new Random(-55); var asyncEnableRts = new AsyncEnableRts(); var t = new Thread(asyncEnableRts.EnableRTS); int waitTime; com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com1.Handshake = Handshake.RequestToSend; com1.Encoding = new UTF8Encoding(); Debug.WriteLine( "Verifying WriteTimeout={0} with successive call to write method with the write succeeding sometime before it's timeout", com1.WriteTimeout); com1.Open(); // Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed // before the timeout is reached t.Start(); waitTime = 0; while (t.ThreadState == ThreadState.Unstarted && waitTime < 2000) { // Wait for the thread to start Thread.Sleep(50); waitTime += 50; } try { com1.BaseStream.WriteByte(DEFAULT_BYTE); } catch (TimeoutException) { } asyncEnableRts.Stop(); while (t.IsAlive) Thread.Sleep(100); VerifyTimeout(com1); } } [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void BytesToWrite() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying BytesToWrite with one call to Write"); com.Handshake = Handshake.RequestToSend; com.Open(); com.WriteTimeout = 200; // Write a random byte[] asynchronously so we can verify some things while the write call is blocking Task task = Task.Run(() => WriteRandomDataBlock(com, TCSupport.MinimumBlockingByteCount)); TCSupport.WaitForTaskToStart(task); TCSupport.WaitForWriteBufferToLoad(com, TCSupport.MinimumBlockingByteCount); // Wait for write method to timeout and complete the task TCSupport.WaitForTaskCompletion(task); } } [OuterLoop("Slow Test")] [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void BytesToWriteSuccessive() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying BytesToWrite with successive calls to Write"); com.Handshake = Handshake.RequestToSend; com.Open(); com.WriteTimeout = 4000; int blockLength = TCSupport.MinimumBlockingByteCount; // Write a random byte[] asynchronously so we can verify some things while the write call is blocking Task t1 = Task.Run(() => WriteRandomDataBlock(com, blockLength)); TCSupport.WaitForTaskToStart(t1); TCSupport.WaitForWriteBufferToLoad(com, blockLength); // Write a random byte[] asynchronously so we can verify some things while the write call is blocking Task t2 = Task.Run(() => WriteRandomDataBlock(com, blockLength)); TCSupport.WaitForTaskToStart(t2); TCSupport.WaitForWriteBufferToLoad(com, blockLength * 2); // Wait for both write methods to timeout TCSupport.WaitForTaskCompletion(t1); TCSupport.WaitForTaskCompletion(t2); } } [ConditionalFact(nameof(HasOneSerialPort))] public void Handshake_None() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying Handshake=None"); com.Open(); // Write a random byte[] asynchronously so we can verify some things while the write call is blocking Task task = Task.Run(() => WriteRandomDataBlock(com, TCSupport.MinimumBlockingByteCount)); TCSupport.WaitForTaskToStart(task); // Wait for write methods to complete TCSupport.WaitForTaskCompletion(task); Assert.Equal(0, com.BytesToWrite); } } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void Handshake_RequestToSend() { Verify_Handshake(Handshake.RequestToSend); } [ConditionalFact(nameof(HasNullModem))] public void Handshake_XOnXOff() { Verify_Handshake(Handshake.XOnXOff); } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void Handshake_RequestToSendXOnXOff() { Verify_Handshake(Handshake.RequestToSendXOnXOff); } private class AsyncEnableRts { private bool _stop; public void EnableRTS() { lock (this) { using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { var rndGen = new Random(-55); int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); // Sleep some random period with of a maximum duration of half the largest possible timeout value for a write method on COM1 Thread.Sleep(sleepPeriod); com2.Open(); com2.RtsEnable = true; while (!_stop) Monitor.Wait(this); com2.RtsEnable = false; } } } public void Stop() { lock (this) { _stop = true; Monitor.Pulse(this); } } } #endregion #region Verification for Test Cases private static void VerifyWriteException(Stream serialStream, Type expectedException) { Assert.Throws(expectedException, () => serialStream.WriteByte(DEFAULT_BYTE)); } private void VerifyTimeout(SerialPort com) { var timer = new Stopwatch(); int expectedTime = com.WriteTimeout; var actualTime = 0; double percentageDifference; try { com.BaseStream.WriteByte(DEFAULT_BYTE); // Warm up write method } catch (TimeoutException) { } Thread.CurrentThread.Priority = ThreadPriority.Highest; for (var i = 0; i < NUM_TRYS; i++) { timer.Start(); try { com.BaseStream.WriteByte(DEFAULT_BYTE); } catch (TimeoutException) { } timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; timer.Reset(); } Thread.CurrentThread.Priority = ThreadPriority.Normal; actualTime /= NUM_TRYS; percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); // Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxPercentageDifference < percentageDifference) { Fail("ERROR!!!: The write method timed-out in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); } } private void Verify_Handshake(Handshake handshake) { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Debug.WriteLine("Verifying Handshake={0}", handshake); com1.Handshake = handshake; com1.Open(); com2.Open(); // Setup to ensure write will bock with type of handshake method being used if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.RtsEnable = false; } if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.BaseStream.WriteByte(XOnOff.XOFF); Thread.Sleep(250); } // Write a block of random data asynchronously so we can verify some things while the write call is blocking Task task = Task.Run(() => WriteRandomDataBlock(com1, TCSupport.MinimumBlockingByteCount)); TCSupport.WaitForTaskToStart(task); TCSupport.WaitForWriteBufferToLoad(com1, TCSupport.MinimumBlockingByteCount); // Verify that CtsHolding is false if the RequestToSend or RequestToSendXOnXOff handshake method is used if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && com1.CtsHolding) { Fail("ERROR!!! Expected CtsHolding={0} actual {1}", false, com1.CtsHolding); } // Setup to ensure write will succeed if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.RtsEnable = true; } if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.BaseStream.WriteByte(XOnOff.XON); } // Wait till write finishes TCSupport.WaitForTaskCompletion(task); // Verify that the correct number of bytes are in the buffer // (There should be nothing because it's all been transmitted after the flow control was released) Assert.Equal(0, com1.BytesToWrite); // Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && !com1.CtsHolding) { Fail("ERROR!!! Expected CtsHolding={0} actual {1}", true, com1.CtsHolding); } } } private static void WriteRandomDataBlock(SerialPort com, int blockLength) { var rndGen = new Random(-55); byte[] randomData = new byte[blockLength]; rndGen.NextBytes(randomData); try { com.BaseStream.Write(randomData, 0, randomData.Length); } catch (TimeoutException) { } } #endregion } }
// (c) Copyright Esri, 2010 - 2013 // This source is subject to the Apache 2.0 License. // Please see http://www.apache.org/licenses/LICENSE-2.0.html for details. // All other rights reserved. using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Resources; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.Geoprocessing; using ESRI.ArcGIS.esriSystem; using System.Xml; using System.Xml.Serialization; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.DataSourcesGDB; using System.IO; using System.Reflection; using ESRI.ArcGIS.DataSourcesFile; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Display; namespace ESRI.ArcGIS.OSM.GeoProcessing { [Guid("d43c5053-1a03-46f3-b746-b7a92a9c46a1")] [ClassInterface(ClassInterfaceType.None)] [ProgId("OSMEditor.OSMGPSymbolizer")] [ComVisible(false)] public class OSMGPSymbolizer : ESRI.ArcGIS.Geoprocessing.IGPFunction2 { string m_DisplayName = String.Empty; int in_osmFeatureDatasetNumber, in_osmPointLayerNumber, in_osmLineLayerNumber, in_osmPolygonLayerNumber, out_osmPointLayerNumber, out_osmLineLayerNumber, out_osmPolygonLayerNumber; ResourceManager resourceManager = null; OSMGPFactory osmGPFactory = null; public OSMGPSymbolizer() { resourceManager = new ResourceManager("ESRI.ArcGIS.OSM.GeoProcessing.OSMGPToolsStrings", this.GetType().Assembly); osmGPFactory = new OSMGPFactory(); } #region "IGPFunction2 Implementations" public ESRI.ArcGIS.esriSystem.UID DialogCLSID { get { return null; } } public string DisplayName { get { if (String.IsNullOrEmpty(m_DisplayName)) { m_DisplayName = osmGPFactory.GetFunctionName(OSMGPFactory.m_FeatureSymbolizerName).DisplayName; } return m_DisplayName; } } public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { try { IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } // find feature class inside the given feature dataset IGPParameter osmFeatureDatasetParameter = paramvalues.get_Element(in_osmFeatureDatasetNumber) as IGPParameter; IDEFeatureDataset osmFeatureDataset = gpUtilities3.UnpackGPValue(osmFeatureDatasetParameter) as IDEFeatureDataset; string osmPointFeatureClassString = ((IDataElement)osmFeatureDataset).Name + "_osm_pt"; string osmLineFeatureClassString = ((IDataElement)osmFeatureDataset).Name + "_osm_ln"; string osmPolygonFeatureClassString = ((IDataElement)osmFeatureDataset).Name + "_osm_ply"; IFeatureClass osmPointFeatureClass = gpUtilities3.OpenFeatureClassFromString(((IDataElement)osmFeatureDataset).CatalogPath + "/" + osmPointFeatureClassString); IFeatureClass osmLineFeatureClass = gpUtilities3.OpenFeatureClassFromString(((IDataElement)osmFeatureDataset).CatalogPath + "/" + osmLineFeatureClassString); IFeatureClass osmPoylgonFeatureClass = gpUtilities3.OpenFeatureClassFromString(((IDataElement)osmFeatureDataset).CatalogPath + "/" + osmPolygonFeatureClassString); // open the specified layers holding the symbology and editing templates IGPParameter osmPointSymbolTemplateParameter = paramvalues.get_Element(in_osmPointLayerNumber) as IGPParameter; IGPValue osmGPPointLayerValue = gpUtilities3.UnpackGPValue(osmPointSymbolTemplateParameter); IGPParameter outputPointGPParameter = paramvalues.get_Element(out_osmPointLayerNumber) as IGPParameter; IGPValue outputPointLayerGPValue = gpUtilities3.UnpackGPValue(outputPointGPParameter); bool isLayerOnDisk = false; // create a clone of the source layer // we will then go ahead and adjust the data source (dataset) of the cloned layer IObjectCopy objectCopy = new ObjectCopyClass(); ICompositeLayer adjustedPointTemplateLayer = objectCopy.Copy(osmGPPointLayerValue) as ICompositeLayer; IGPGroupLayer osmPointGroupTemplateLayer = adjustedPointTemplateLayer as IGPGroupLayer; ICompositeLayer compositeLayer = gpUtilities3.Open((IGPValue)osmPointGroupTemplateLayer) as ICompositeLayer; //ICompositeLayer adjustedPointTemplateLayer = osmGPPointLayerValue as ICompositeLayer; //IGPGroupLayer osmPointGroupTemplateLayer = osmGPPointLayerValue as IGPGroupLayer; //IClone cloneSource = osmPointGroupTemplateLayer as IClone; //ICompositeLayer compositeLayer = m_gpUtilities3.Open((IGPValue)cloneSource.Clone()) as ICompositeLayer; if (compositeLayer == null) { ILayerFactoryHelper layerFactoryHelper = new LayerFactoryHelperClass(); IFileName layerFileName = new FileNameClass(); layerFileName.Path = osmGPPointLayerValue.GetAsText(); IEnumLayer enumLayer = layerFactoryHelper.CreateLayersFromName((IName)layerFileName); enumLayer.Reset(); compositeLayer = enumLayer.Next() as ICompositeLayer; isLayerOnDisk = true; } IFeatureLayerDefinition2 featureLayerDefinition2 = null; ISQLSyntax sqlSyntax = null; IGPLayer adjustedPointGPLayer = null; if (compositeLayer != null) { for (int layerIndex = 0; layerIndex < compositeLayer.Count; layerIndex++) { IFeatureLayer2 geoFeatureLayer = compositeLayer.get_Layer(layerIndex) as IFeatureLayer2; if (geoFeatureLayer != null) { if (geoFeatureLayer.ShapeType == osmPointFeatureClass.ShapeType) { try { ((IDataLayer2)geoFeatureLayer).Disconnect(); } catch { } ((IDataLayer2)geoFeatureLayer).DataSourceName = ((IDataset)osmPointFeatureClass).FullName; ((IDataLayer2)geoFeatureLayer).Connect(((IDataset)osmPointFeatureClass).FullName); featureLayerDefinition2 = geoFeatureLayer as IFeatureLayerDefinition2; if (featureLayerDefinition2 != null) { string queryDefinition = featureLayerDefinition2.DefinitionExpression; sqlSyntax = ((IDataset)osmPointFeatureClass).Workspace as ISQLSyntax; string delimiterIdentifier = sqlSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); if (String.IsNullOrEmpty(queryDefinition) == false) { string stringToReplace = queryDefinition.Substring(0, 1); queryDefinition = queryDefinition.Replace(stringToReplace, delimiterIdentifier); } featureLayerDefinition2.DefinitionExpression = queryDefinition; } } } } adjustedPointGPLayer = gpUtilities3.MakeGPLayerFromLayer((ILayer)compositeLayer); // save the newly adjusted layer information to disk if (isLayerOnDisk == true) { ILayerFile pointLayerFile = new LayerFileClass(); if (pointLayerFile.get_IsPresent(outputPointLayerGPValue.GetAsText())) { try { File.Delete(outputPointLayerGPValue.GetAsText()); } catch (Exception ex) { message.AddError(120041,ex.Message); return; } } pointLayerFile.New(outputPointLayerGPValue.GetAsText()); pointLayerFile.ReplaceContents((ILayer)compositeLayer); pointLayerFile.Save(); adjustedPointGPLayer = gpUtilities3.MakeGPLayerFromLayer((ILayer)pointLayerFile.Layer); } // IGPLayer adjustedPointGPLayer = gpUtilities3.MakeGPLayerFromLayer((ILayer)compositeLayer); gpUtilities3.AddInternalLayer2((ILayer)compositeLayer, adjustedPointGPLayer); gpUtilities3.PackGPValue((IGPValue)adjustedPointGPLayer, outputPointGPParameter); } isLayerOnDisk = false; IGPParameter osmLineSymbolTemplateParameter = paramvalues.get_Element(in_osmLineLayerNumber) as IGPParameter; IGPValue osmGPLineLayerValue = gpUtilities3.UnpackGPValue(osmLineSymbolTemplateParameter) as IGPValue; IGPParameter outputLineGPParameter = paramvalues.get_Element(out_osmLineLayerNumber) as IGPParameter; IGPValue outputLineLayerGPValue = gpUtilities3.UnpackGPValue(outputLineGPParameter); IGPValue adjustedLineTemplateLayer = objectCopy.Copy(osmGPLineLayerValue) as IGPValue; IGPGroupLayer osmLineGroupTemplateLayer = adjustedLineTemplateLayer as IGPGroupLayer; compositeLayer = gpUtilities3.Open((IGPValue)osmLineGroupTemplateLayer) as ICompositeLayer; if (compositeLayer == null) { ILayerFactoryHelper layerFactoryHelper = new LayerFactoryHelperClass(); IFileName layerFileName = new FileNameClass(); layerFileName.Path = osmGPLineLayerValue.GetAsText(); IEnumLayer enumLayer = layerFactoryHelper.CreateLayersFromName((IName)layerFileName); enumLayer.Reset(); compositeLayer = enumLayer.Next() as ICompositeLayer; isLayerOnDisk = true; } if (compositeLayer != null) { for (int layerIndex = 0; layerIndex < compositeLayer.Count; layerIndex++) { IFeatureLayer2 geoFeatureLayer = compositeLayer.get_Layer(layerIndex) as IFeatureLayer2; if (geoFeatureLayer.ShapeType == osmLineFeatureClass.ShapeType) { try { ((IDataLayer2)geoFeatureLayer).Disconnect(); } catch { } ((IDataLayer2)geoFeatureLayer).DataSourceName = ((IDataset)osmLineFeatureClass).FullName; ((IDataLayer2)geoFeatureLayer).Connect(((IDataset)osmLineFeatureClass).FullName); featureLayerDefinition2 = geoFeatureLayer as IFeatureLayerDefinition2; if (featureLayerDefinition2 != null) { string queryDefinition = featureLayerDefinition2.DefinitionExpression; sqlSyntax = ((IDataset)osmLineFeatureClass).Workspace as ISQLSyntax; string delimiterIdentifier = sqlSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); if (string.IsNullOrEmpty(queryDefinition) == false) { string stringToReplace = queryDefinition.Substring(0, 1); queryDefinition = queryDefinition.Replace(stringToReplace, delimiterIdentifier); } featureLayerDefinition2.DefinitionExpression = queryDefinition; } } } // save the newly adjusted layer information to disk if (isLayerOnDisk == true) { ILayerFile lineLayerFile = new LayerFileClass(); if (lineLayerFile.get_IsPresent(outputLineLayerGPValue.GetAsText())) { try { File.Delete(outputLineLayerGPValue.GetAsText()); } catch (Exception ex) { message.AddError(120042, ex.Message); return; } } lineLayerFile.New(outputLineLayerGPValue.GetAsText()); lineLayerFile.ReplaceContents((ILayer)compositeLayer); lineLayerFile.Save(); } IGPLayer adjustLineGPLayer = gpUtilities3.MakeGPLayerFromLayer((ILayer)compositeLayer); gpUtilities3.AddInternalLayer2((ILayer)compositeLayer, adjustLineGPLayer); gpUtilities3.PackGPValue((IGPValue)adjustLineGPLayer, outputLineGPParameter); } isLayerOnDisk = false; IGPParameter osmPolygonSymbolTemplateParameter = paramvalues.get_Element(in_osmPolygonLayerNumber) as IGPParameter; IGPValue osmGPPolygonLayerValue = gpUtilities3.UnpackGPValue(osmPolygonSymbolTemplateParameter); IGPParameter outputPolygonGPParameter = paramvalues.get_Element(out_osmPolygonLayerNumber) as IGPParameter; IGPValue outputPolygonLayerGPValue = gpUtilities3.UnpackGPValue(outputPolygonGPParameter); IGPValue adjustedPolygonTemplateLayer = objectCopy.Copy(osmGPPolygonLayerValue) as IGPValue; IGPGroupLayer osmPolygonGroupTemplateLayer = adjustedPolygonTemplateLayer as IGPGroupLayer; compositeLayer = gpUtilities3.Open((IGPValue)osmPolygonGroupTemplateLayer) as ICompositeLayer; if (compositeLayer == null) { ILayerFactoryHelper layerFactoryHelper = new LayerFactoryHelperClass(); IFileName layerFileName = new FileNameClass(); layerFileName.Path = osmGPPolygonLayerValue.GetAsText(); IEnumLayer enumLayer = layerFactoryHelper.CreateLayersFromName((IName)layerFileName); enumLayer.Reset(); compositeLayer = enumLayer.Next() as ICompositeLayer; isLayerOnDisk = true; } if (compositeLayer != null) { for (int layerIndex = 0; layerIndex < compositeLayer.Count; layerIndex++) { IFeatureLayer2 geoFeatureLayer = compositeLayer.get_Layer(layerIndex) as IFeatureLayer2; if (geoFeatureLayer.ShapeType == osmPoylgonFeatureClass.ShapeType) { try { ((IDataLayer2)geoFeatureLayer).Disconnect(); } catch { } ((IDataLayer2)geoFeatureLayer).DataSourceName = ((IDataset)osmPoylgonFeatureClass).FullName; ((IDataLayer2)geoFeatureLayer).Connect(((IDataset)osmPoylgonFeatureClass).FullName); featureLayerDefinition2 = geoFeatureLayer as IFeatureLayerDefinition2; if (featureLayerDefinition2 != null) { string queryDefinition = featureLayerDefinition2.DefinitionExpression; sqlSyntax = ((IDataset)osmPoylgonFeatureClass).Workspace as ISQLSyntax; string delimiterIdentifier = sqlSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); if (String.IsNullOrEmpty(queryDefinition) == false) { string stringToReplace = queryDefinition.Substring(0, 1); queryDefinition = queryDefinition.Replace(stringToReplace, delimiterIdentifier); } featureLayerDefinition2.DefinitionExpression = queryDefinition; } } } // save the newly adjusted layer information to disk if (isLayerOnDisk == true) { ILayerFile polygonLayerFile = new LayerFileClass(); if (polygonLayerFile.get_IsPresent(outputPolygonLayerGPValue.GetAsText())) { try { File.Delete(outputPolygonLayerGPValue.GetAsText()); } catch (Exception ex) { message.AddError(120043, ex.Message); return; } } polygonLayerFile.New(outputPolygonLayerGPValue.GetAsText()); polygonLayerFile.ReplaceContents((ILayer)compositeLayer); polygonLayerFile.Save(); } IGPLayer adjustedPolygonGPLayer = gpUtilities3.MakeGPLayerFromLayer((ILayer)compositeLayer); gpUtilities3.AddInternalLayer2((ILayer)compositeLayer, adjustedPolygonGPLayer); gpUtilities3.PackGPValue((IGPValue)adjustedPolygonGPLayer, outputPolygonGPParameter); } } catch (Exception ex) { message.AddError(-10,ex.Message); } } public ESRI.ArcGIS.esriSystem.IName FullName { get { IName fullName = null; if (osmGPFactory != null) { fullName = osmGPFactory.GetFunctionName(OSMGPFactory.m_FeatureSymbolizerName) as IName; } return fullName; } } public object GetRenderer(ESRI.ArcGIS.Geoprocessing.IGPParameter pParam) { return null; } public int HelpContext { get { return 0; } } public string HelpFile { get { return ""; } } public bool IsLicensed() { return true; } public string MetadataFile { get { string metadafile = "osmgpsymbolizer.xml"; try { string[] languageid = System.Threading.Thread.CurrentThread.CurrentUICulture.Name.Split("-".ToCharArray()); string ArcGISInstallationLocation = OSMGPFactory.GetArcGIS10InstallLocation(); string localizedMetaDataFileShort = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "osmgpsymbolizer_" + languageid[0] + ".xml"; string localizedMetaDataFileLong = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "osmgpsymbolizer_" + System.Threading.Thread.CurrentThread.CurrentUICulture.Name + ".xml"; if (System.IO.File.Exists(localizedMetaDataFileShort)) { metadafile = localizedMetaDataFileShort; } else if (System.IO.File.Exists(localizedMetaDataFileLong)) { metadafile = localizedMetaDataFileLong; } } catch { } return metadafile; } } public string Name { get { return OSMGPFactory.m_FeatureSymbolizerName; } } public ESRI.ArcGIS.esriSystem.IArray ParameterInfo { get { IArray parameterArray = new ArrayClass(); string path = Assembly.GetExecutingAssembly().Location; FileInfo executingAssembly = new FileInfo(path); string dataDirectory = executingAssembly.Directory.Parent.FullName + System.IO.Path.DirectorySeparatorChar + "data"; // input feature dataset IGPParameterEdit3 inputFeatureDataset = new GPParameterClass() as IGPParameterEdit3; inputFeatureDataset.ParameterType = esriGPParameterType.esriGPParameterTypeRequired; inputFeatureDataset.Direction = esriGPParameterDirection.esriGPParameterDirectionInput; inputFeatureDataset.DataType = new DEFeatureDatasetTypeClass(); inputFeatureDataset.DisplayName = resourceManager.GetString("GPTools_OSMGPSymbolizer_inosmds_displayName"); inputFeatureDataset.Name = "in_osmfeaturedataset"; in_osmFeatureDatasetNumber = 0; parameterArray.Add((IGPParameter)inputFeatureDataset); // input point feature layer (group layer) IGPParameterEdit3 inputPointLayer = new GPParameterClass() as IGPParameterEdit3; inputPointLayer.ParameterType = esriGPParameterType.esriGPParameterTypeRequired; inputPointLayer.Direction = esriGPParameterDirection.esriGPParameterDirectionInput; inputPointLayer.DataType = new GPLayerTypeClass(); inputPointLayer.DisplayName = resourceManager.GetString("GPTools_OSMGPSymbolizer_inptlayer_displayName"); inputPointLayer.Name = "in_osmpoints_layer"; // if a file exists then populate the corresponding GP value if (File.Exists(dataDirectory + System.IO.Path.DirectorySeparatorChar + "Points.lyr")) { IDELayer deLayer = new DELayerClass(); ((IGPValue)deLayer).SetAsText(dataDirectory + System.IO.Path.DirectorySeparatorChar + "Points.lyr"); inputPointLayer.Value = (IGPValue)deLayer; } in_osmPointLayerNumber = 1; parameterArray.Add((IGPParameter)inputPointLayer); // input line feature layer (group layer) IGPParameterEdit3 inputLineLayer = new GPParameterClass() as IGPParameterEdit3; inputLineLayer.ParameterType = esriGPParameterType.esriGPParameterTypeRequired; inputLineLayer.Direction = esriGPParameterDirection.esriGPParameterDirectionInput; inputLineLayer.DataType = new GPLayerTypeClass(); inputLineLayer.DisplayName = resourceManager.GetString("GPTools_OSMGPSymbolizer_inlnlayer_displayName"); inputLineLayer.Name = "in_osmlines_layer"; // if a file exists then populate the corresponding GP value if (File.Exists(dataDirectory + System.IO.Path.DirectorySeparatorChar + "Lines.lyr")) { IDELayer deLayer = new DELayerClass(); ((IGPValue)deLayer).SetAsText(dataDirectory + System.IO.Path.DirectorySeparatorChar + "Lines.lyr"); inputLineLayer.Value = (IGPValue)deLayer; } in_osmLineLayerNumber = 2; parameterArray.Add((IGPParameter)inputLineLayer); // input polygon feature layer (group layer) IGPParameterEdit3 inputPolygonLayer = new GPParameterClass() as IGPParameterEdit3; inputPolygonLayer.ParameterType = esriGPParameterType.esriGPParameterTypeRequired; inputPolygonLayer.Direction = esriGPParameterDirection.esriGPParameterDirectionInput; inputPolygonLayer.DataType = new GPLayerTypeClass(); inputPolygonLayer.DisplayName = resourceManager.GetString("GPTools_OSMGPSymbolizer_inplylayer_displayName"); inputPolygonLayer.Name = "in_osmpolygons_layer"; // if a file exists then populate the corresponding GP value if (File.Exists(dataDirectory + System.IO.Path.DirectorySeparatorChar + "Polygons.lyr")) { IDELayer deLayer = new DELayerClass(); ((IGPValue)deLayer).SetAsText(dataDirectory + System.IO.Path.DirectorySeparatorChar + "Polygons.lyr"); inputPolygonLayer.Value = (IGPValue)deLayer; } in_osmPolygonLayerNumber = 3; parameterArray.Add((IGPParameter)inputPolygonLayer); // output adjusted point feature layer (group layer) IGPParameterEdit3 outputPointLayer = new GPParameterClass() as IGPParameterEdit3; outputPointLayer.ParameterType = esriGPParameterType.esriGPParameterTypeRequired; outputPointLayer.Direction = esriGPParameterDirection.esriGPParameterDirectionOutput; outputPointLayer.DataType = new GPLayerTypeClass(); outputPointLayer.DisplayName = resourceManager.GetString("GPTools_OSMGPSymbolizer_outptlayer_displayName"); outputPointLayer.Name = "out_osmpoints_layer"; outputPointLayer.AddDependency("in_osmpoints_layer"); out_osmPointLayerNumber = 4; parameterArray.Add((IGPParameter)outputPointLayer); // output adjusted line feature layer (group layer) IGPParameterEdit3 outputLineLayer = new GPParameterClass() as IGPParameterEdit3; outputLineLayer.ParameterType = esriGPParameterType.esriGPParameterTypeRequired; outputLineLayer.Direction = esriGPParameterDirection.esriGPParameterDirectionOutput; outputLineLayer.DataType = new GPLayerTypeClass(); outputLineLayer.DisplayName = resourceManager.GetString("GPTools_OSMGPSymbolizer_outlnlayer_displayName"); outputLineLayer.Name = "out_osmlines_layer"; outputLineLayer.AddDependency("in_osmlines_layer"); out_osmLineLayerNumber = 5; parameterArray.Add((IGPParameter)outputLineLayer); // output adjusted polygon feature layer (group layer) IGPParameterEdit3 outputPolygonLayer = new GPParameterClass() as IGPParameterEdit3; outputPolygonLayer.ParameterType = esriGPParameterType.esriGPParameterTypeRequired; outputPolygonLayer.Direction = esriGPParameterDirection.esriGPParameterDirectionOutput; outputPolygonLayer.DataType = new GPLayerTypeClass(); outputPolygonLayer.DisplayName = resourceManager.GetString("GPTools_OSMGPSymbolizer_outplylayer_displayName"); outputPolygonLayer.Name = "out_osmpolygons_layer"; outputPolygonLayer.AddDependency("in_osmpolygons_layer"); out_osmPolygonLayerNumber = 6; parameterArray.Add((IGPParameter)outputPolygonLayer); return parameterArray; } } public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages) { } public void UpdateParameters(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr) { IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); #region update the output point parameter based on the input of template point layer IGPParameter inputPointLayerParameter = paramvalues.get_Element(in_osmPointLayerNumber) as IGPParameter; IGPValue inputPointLayer = gpUtilities3.UnpackGPValue(inputPointLayerParameter); IGPParameter3 outputPointLayerParameter = paramvalues.get_Element(out_osmPointLayerNumber) as IGPParameter3; if (((inputPointLayer).IsEmpty() == false) && (outputPointLayerParameter.Altered == false)) { IGPValue outputPointGPValue = gpUtilities3.UnpackGPValue(outputPointLayerParameter); if (outputPointGPValue.IsEmpty()) { IClone clonedObject = inputPointLayer as IClone; IGPValue clonedGPValue = clonedObject.Clone() as IGPValue; // if it is an internal group layer IGPGroupLayer inputPointGroupLayer = clonedObject as IGPGroupLayer; if (inputPointGroupLayer != null) { string proposedLayerName = "Points"; string tempLayerName = proposedLayerName; int index = 1; ILayer currentMapLayer = gpUtilities3.FindMapLayer(proposedLayerName); while (currentMapLayer != null) { tempLayerName = proposedLayerName + "_" + index.ToString(); currentMapLayer = gpUtilities3.FindMapLayer(tempLayerName); index = index + 1; } clonedGPValue.SetAsText(tempLayerName); gpUtilities3.PackGPValue(clonedGPValue, outputPointLayerParameter); } else { IDELayer deLayer = clonedGPValue as IDELayer; if (deLayer != null) { FileInfo sourceLyrFileInfo = new FileInfo(clonedGPValue.GetAsText()); // check the output location of the file with respect to the gp environment settings sourceLyrFileInfo = new FileInfo(DetermineLyrLocation(pEnvMgr.GetEnvironments(), sourceLyrFileInfo)); if (sourceLyrFileInfo.Exists) { int layerFileIndex = 1; string tempFileLyrName = sourceLyrFileInfo.DirectoryName + System.IO.Path.DirectorySeparatorChar + sourceLyrFileInfo.Name.Substring(0, sourceLyrFileInfo.Name.Length - sourceLyrFileInfo.Extension.Length) + "_" + layerFileIndex.ToString() + sourceLyrFileInfo.Extension; while (File.Exists(tempFileLyrName)) { tempFileLyrName = sourceLyrFileInfo.DirectoryName + System.IO.Path.DirectorySeparatorChar + sourceLyrFileInfo.Name.Substring(0, sourceLyrFileInfo.Name.Length - sourceLyrFileInfo.Extension.Length) + "_" + layerFileIndex.ToString() + sourceLyrFileInfo.Extension; layerFileIndex = layerFileIndex + 1; } clonedGPValue.SetAsText(tempFileLyrName); gpUtilities3.PackGPValue(clonedGPValue, outputPointLayerParameter); } else { clonedGPValue.SetAsText(sourceLyrFileInfo.FullName); gpUtilities3.PackGPValue(clonedGPValue, outputPointLayerParameter); } } } } } #endregion #region update the output line parameter based on the input of template line layer IGPParameter inputLineLayerParameter = paramvalues.get_Element(in_osmLineLayerNumber) as IGPParameter; IGPValue inputLineLayer = gpUtilities3.UnpackGPValue(inputLineLayerParameter); IGPParameter3 outputLineLayerParameter = paramvalues.get_Element(out_osmLineLayerNumber) as IGPParameter3; if (((inputLineLayer).IsEmpty() == false) && (outputLineLayerParameter.Altered == false)) { IGPValue outputLineGPValue = gpUtilities3.UnpackGPValue(outputLineLayerParameter); if (outputLineGPValue.IsEmpty()) { IClone clonedObject = inputLineLayer as IClone; IGPValue clonedGPValue = clonedObject.Clone() as IGPValue; // if it is an internal group layer IGPGroupLayer inputLineGroupLayer = clonedObject as IGPGroupLayer; if (inputLineGroupLayer != null) { string proposedLayerName = "Lines"; string tempLayerName = proposedLayerName; int index = 1; ILayer currentMapLayer = gpUtilities3.FindMapLayer(proposedLayerName); while (currentMapLayer != null) { tempLayerName = proposedLayerName + "_" + index.ToString(); currentMapLayer = gpUtilities3.FindMapLayer(tempLayerName); index = index + 1; } clonedGPValue.SetAsText(tempLayerName); gpUtilities3.PackGPValue(clonedGPValue, outputLineLayerParameter); } else { IDELayer deLayer = clonedGPValue as IDELayer; if (deLayer != null) { FileInfo sourceLyrFileInfo = new FileInfo(clonedGPValue.GetAsText()); // check the output location of the file with respect to the gp environment settings sourceLyrFileInfo = new FileInfo(DetermineLyrLocation(pEnvMgr.GetEnvironments(), sourceLyrFileInfo)); if (sourceLyrFileInfo.Exists) { int layerFileIndex = 1; string tempFileLyrName = sourceLyrFileInfo.DirectoryName + System.IO.Path.DirectorySeparatorChar + sourceLyrFileInfo.Name.Substring(0, sourceLyrFileInfo.Name.Length - sourceLyrFileInfo.Extension.Length) + "_" + layerFileIndex.ToString() + sourceLyrFileInfo.Extension; while (File.Exists(tempFileLyrName)) { tempFileLyrName = sourceLyrFileInfo.DirectoryName + System.IO.Path.DirectorySeparatorChar + sourceLyrFileInfo.Name.Substring(0, sourceLyrFileInfo.Name.Length - sourceLyrFileInfo.Extension.Length) + "_" + layerFileIndex.ToString() + sourceLyrFileInfo.Extension; layerFileIndex = layerFileIndex + 1; } clonedGPValue.SetAsText(tempFileLyrName); gpUtilities3.PackGPValue(clonedGPValue, outputLineLayerParameter); } else { clonedGPValue.SetAsText(sourceLyrFileInfo.FullName); gpUtilities3.PackGPValue(clonedGPValue, outputLineLayerParameter); } } } } } #endregion #region update the output polygon parameter based on the input of template polygon layer IGPParameter inputPolygonLayerParameter = paramvalues.get_Element(in_osmPolygonLayerNumber) as IGPParameter; IGPValue inputPolygonLayer = gpUtilities3.UnpackGPValue(inputPolygonLayerParameter); IGPParameter3 outputPolygonLayerParameter = paramvalues.get_Element(out_osmPolygonLayerNumber) as IGPParameter3; if (((inputPolygonLayer).IsEmpty() == false) && (outputPolygonLayerParameter.Altered == false)) { IGPValue outputPolygonGPValue = gpUtilities3.UnpackGPValue(outputPolygonLayerParameter); if (outputPolygonGPValue.IsEmpty()) { IClone clonedObject = inputPolygonLayer as IClone; IGPValue clonedGPValue = clonedObject.Clone() as IGPValue; // if it is an internal group layer IGPGroupLayer inputPolygonGroupLayer = clonedObject as IGPGroupLayer; if (inputPolygonGroupLayer != null) { string proposedLayerName = "Polygons"; string tempLayerName = proposedLayerName; int index = 1; ILayer currentMapLayer = gpUtilities3.FindMapLayer(proposedLayerName); while (currentMapLayer != null) { tempLayerName = proposedLayerName + "_" + index.ToString(); currentMapLayer = gpUtilities3.FindMapLayer(tempLayerName); index = index + 1; } clonedGPValue.SetAsText(tempLayerName); gpUtilities3.PackGPValue(clonedGPValue, outputPolygonLayerParameter); } else { IDELayer deLayer = clonedGPValue as IDELayer; if (deLayer != null) { FileInfo sourceLyrFileInfo = new FileInfo(clonedGPValue.GetAsText()); // check the output location of the file with respect to the gp environment settings sourceLyrFileInfo = new FileInfo(DetermineLyrLocation(pEnvMgr.GetEnvironments(), sourceLyrFileInfo)); if (sourceLyrFileInfo.Exists) { int layerFileIndex = 1; string tempFileLyrName = sourceLyrFileInfo.DirectoryName + System.IO.Path.DirectorySeparatorChar + sourceLyrFileInfo.Name.Substring(0, sourceLyrFileInfo.Name.Length - sourceLyrFileInfo.Extension.Length) + "_" + layerFileIndex.ToString() + sourceLyrFileInfo.Extension; while (File.Exists(tempFileLyrName)) { tempFileLyrName = sourceLyrFileInfo.DirectoryName + System.IO.Path.DirectorySeparatorChar + sourceLyrFileInfo.Name.Substring(0, sourceLyrFileInfo.Name.Length - sourceLyrFileInfo.Extension.Length) + "_" + layerFileIndex.ToString() + sourceLyrFileInfo.Extension; layerFileIndex = layerFileIndex + 1; } clonedGPValue.SetAsText(tempFileLyrName); gpUtilities3.PackGPValue(clonedGPValue, outputPolygonLayerParameter); } else { clonedGPValue.SetAsText(sourceLyrFileInfo.FullName); gpUtilities3.PackGPValue(clonedGPValue, outputPolygonLayerParameter); } } } } } #endregion } private string DetermineLyrLocation(IArray environments, FileInfo initialLyrLocation) { string outputLyrLocation = initialLyrLocation.FullName; try { IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); // first check for the scratch workspace // next for the current workspace // and as a last resort pick the user's temp workspace IGPEnvironment scratchworkspaceGPEnvironment = gpUtilities3.GetEnvironment(environments, "scratchworkspace"); if (scratchworkspaceGPEnvironment != null) { IDEWorkspace scratchworkspace = scratchworkspaceGPEnvironment.Value as IDEWorkspace; if (scratchworkspace != null) { if (scratchworkspace.WorkspaceType == esriWorkspaceType.esriFileSystemWorkspace) { if (((IGPValue)scratchworkspace).IsEmpty() == false) { outputLyrLocation = ((IGPValue)scratchworkspace).GetAsText() + System.IO.Path.DirectorySeparatorChar + initialLyrLocation.Name; return outputLyrLocation; } } else if (scratchworkspace.WorkspaceType == esriWorkspaceType.esriLocalDatabaseWorkspace) { if (((IGPValue)scratchworkspace).IsEmpty() == false) { int slashIndexPosition = ((IGPValue)scratchworkspace).GetAsText().LastIndexOf("\\"); string potentialFolderLocation = ((IGPValue)scratchworkspace).GetAsText().Substring(0, slashIndexPosition); if (Directory.Exists(potentialFolderLocation)) { outputLyrLocation = potentialFolderLocation + System.IO.Path.DirectorySeparatorChar + initialLyrLocation.Name; return outputLyrLocation; } } } else { string localTempPath = System.IO.Path.GetTempPath(); outputLyrLocation = localTempPath + initialLyrLocation.Name; return outputLyrLocation; } } } IGPEnvironment currentworkspaceGPEnvironment = gpUtilities3.GetEnvironment(environments, "workspace"); if (currentworkspaceGPEnvironment != null) { IDEWorkspace currentWorkspace = currentworkspaceGPEnvironment.Value as IDEWorkspace; if (currentWorkspace != null) { if (currentWorkspace.WorkspaceType == esriWorkspaceType.esriFileSystemWorkspace) { if (((IGPValue)currentWorkspace).IsEmpty() == false) { outputLyrLocation = ((IGPValue)currentWorkspace).GetAsText() + System.IO.Path.DirectorySeparatorChar + initialLyrLocation.Name; return outputLyrLocation; } } } } // combine temp directory path with the name of the incoming lyr file string tempPath = System.IO.Path.GetTempPath(); outputLyrLocation = tempPath + initialLyrLocation.Name; } catch { } return outputLyrLocation; } public ESRI.ArcGIS.Geodatabase.IGPMessages Validate(ESRI.ArcGIS.esriSystem.IArray paramvalues, bool updateValues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr) { return default(ESRI.ArcGIS.Geodatabase.IGPMessages); } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Dexel.Model.DataTypes; using Dexel.Model.Manager; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editing; using Roslyn.Parser; using Dexel.Library; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Analyser; using Roslyn.Exceptions; using Roslyn.Generators; namespace Roslyn { public static class IntegrationGenerator { public static SyntaxNode[] GenerateIntegrationBody(SyntaxGenerator generator, MainModel mainModel, FunctionUnit integration, Action<IntegrationBody> getIntegrationBody = null) { // integrationbody object for storing analysed and generated information var integrationBody = IntegrationAnalyser.CreateNewIntegrationBody(mainModel.Connections, integration); AddIntegrationInputParameterToLocalScope(integrationBody, integration); // analyse data flow before generation IntegrationAnalyser.AnalyseParameterDependencies(integrationBody); IntegrationAnalyser.AnalyseLambdaBodies(integrationBody, mainModel); IntegrationAnalyser.AnalyseMatchingOutputOfIntegration(integrationBody, mainModel); IntegrationAnalyser.AnalyseReturnToLocalReturnVariable(integrationBody, mainModel); // generation var result = new List<SyntaxNode>(); integrationBody.Generator = generator; GenerateBody(integrationBody, result.Add); // when generating integration signature, some information from the body is needed: is returning local variable nullable type getIntegrationBody?.Invoke(integrationBody); return result.ToArray(); } public static void AddIntegrationInputParameterToLocalScope(IntegrationBody integrationBody, FunctionUnit integration) { var nametypes = DataStreamParser.GetInputPart(integration.InputStreams.First().DataNames); nametypes.ToList().ForEach(nametype => { var name = Names.ParameterName(nametype); integrationBody.LocalVariables.Add(new GeneratedLocalVariable { VariableName = name, Source = integration.InputStreams.First(), NameTypes = new[] { nametype } }); }); nametypes = DataStreamParser.GetOutputPart(integration.OutputStreams.First().DataNames); nametypes.ToList().ForEach(nametype => { var name = Names.ParameterName(nametype); integrationBody.LocalVariables.Add(new GeneratedLocalVariable { VariableName = name, Source = integration.InputStreams.First(), NameTypes = new[] { nametype } }); }); } private static void GenerateBody(IntegrationBody integrationBody, Action<SyntaxNode> onSyntaxNode) { IntegrationAnalyser.NeedsLocalReturnVariable(integrationBody, () => GenerateReturnLocalVariable(integrationBody, onSyntaxNode)); var toplevelCalls = integrationBody.LambdaBodies.Where(x => x.InsideLambdaOf == null).ToList(); toplevelCalls.ForEach(c => { var syntaxnode = CreateMethodCall(c.FunctionUnit, integrationBody); onSyntaxNode(syntaxnode); }); IntegrationAnalyser.NeedsLocalReturnVariable(integrationBody, () => ReturnLocalReturnVariable(integrationBody, onSyntaxNode)); } private static void ReturnLocalReturnVariable(IntegrationBody integrationBody, Action<SyntaxNode> onSyntaxNode) { var returnVar = integrationBody.Generator.IdentifierName("@return"); onSyntaxNode(integrationBody.Generator.ReturnStatement(returnVar)); } private static void GenerateReturnLocalVariable(IntegrationBody integrationBody, Action<SyntaxNode> onSyntaxNode) { var returnType = integrationBody.ReturnToLocalReturnVariable.First(); var nametypes = DataStreamParser.GetOutputPart(returnType.DataNames); var nullabletype = TypeConverter.ConvertToType(integrationBody.Generator, nametypes, isNullable:true); var nullLiteral = integrationBody.Generator.NullLiteralExpression(); onSyntaxNode(integrationBody.Generator.LocalDeclarationStatement(nullabletype, "@return", nullLiteral)); } private static SyntaxNode CreateMethodCall(FunctionUnit functionUnit, IntegrationBody integrationBody) { SyntaxNode @return = null; var parameter = new List<SyntaxNode>(); var methodname = Names.MethodName(functionUnit); AssignmentParameter_IncludingLambdaBodiesRecursive(integrationBody, functionUnit, parameter.Add); FunctionUnitAnalyser.GetDsdThatReturns(functionUnit, returndsd => { IntegrationAnalyser.IsOutputOfIntegration(integrationBody, returndsd, matchingOutputDsdOfIntegration => { var methodcall = GenerateLocalMethodCall(integrationBody.Generator, methodname, parameter.ToArray(), null); IntegrationAnalyser.IntegrationOutput(integrationBody, matchingOutputDsdOfIntegration, implementByAction: sig => { var nameofAction = Names.NewAction(sig.DSD); @return = CallAction(integrationBody.Generator, nameofAction, methodcall); }, implementByReturn: () => { IntegrationAnalyser.NeedsLocalReturnVariable( integrationBody, onNeeded: () => @return = CallAndAssignToReturnVariable(integrationBody.Generator, methodcall), onNotNeeded: () => @return = CallAndReturn(integrationBody.Generator, methodcall)); }); }, onNotFound: () => // if method returns but is not output for integration -> save returned value in local variable { var output = DataStreamParser.GetOutputPart(returndsd?.DataNames); string localvariablename = Names.NewLocalVariable(output); RegisterLocalVariable(integrationBody, returndsd, localvariablename, output); @return = GenerateLocalMethodCall(integrationBody.Generator, methodname, parameter.ToArray(), localvariablename); }); }, onNoReturn: () => @return = GenerateLocalMethodCall(integrationBody.Generator, methodname, parameter.ToArray(), null)); return @return; } private static SyntaxNode CallAndAssignToReturnVariable(SyntaxGenerator generator, SyntaxNode methodcall) { return SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, (ExpressionSyntax)generator.IdentifierName("@return"), (ExpressionSyntax)methodcall); } private static SyntaxNode CallAndReturn(SyntaxGenerator generator, SyntaxNode methodcall) { return generator.ReturnStatement(methodcall); } private static SyntaxNode CallAction(SyntaxGenerator generator, string nameofAction, SyntaxNode methodcall) { return generator.InvocationExpression( generator.IdentifierName(nameofAction), methodcall); } private static SyntaxNode[] GenerateAllLambdaParameter(IntegrationBody integrationBody, DataStreamDefinition streamingOutput, Action<List<string>> getNames = null) { var inputs = DataStreamParser.GetOutputPart(streamingOutput.DataNames); var lambdaNames = new List<string>(); inputs.ForEach(nt => { var localvar = new GeneratedLocalVariable { NameTypes = new List<NameType> { nt }, Source = streamingOutput, VariableName = GetUniqueLocalVariableName(integrationBody.LocalVariables, nt) }; integrationBody.LocalVariables.Add(localvar); lambdaNames.Add(localvar.VariableName); }); if (lambdaNames.Any()) getNames?.Invoke(lambdaNames); return lambdaNames.Select(name => integrationBody.Generator.LambdaParameter(name)).ToArray(); } private static void GenerateLambdaExpression(SyntaxGenerator generator, SyntaxNode[] lambdaParameter, SyntaxNode[] lambdaBody, Action<SyntaxNode> onCreated) { //integrationBody.Generator.MethodDeclaration() onCreated(generator.VoidReturningLambdaExpression(lambdaParameter, lambdaBody)); } public static string GetUniqueLocalVariableName(List<GeneratedLocalVariable> generated, NameType nt) { var defaultname = nt.Name ?? nt.Type.ToLower(); var result = defaultname; var i = 1; while (generated.Any(x => x.VariableName == result)) { i++; result = defaultname + i; } return result; } private static void RegisterLocalVariable(IntegrationBody integrationBody, DataStreamDefinition dsd, string localname, List<NameType> nametypes) { integrationBody.LocalVariables.Add(new GeneratedLocalVariable { VariableName = localname, Source = dsd, NameTypes = nametypes }); } public static void AssignmentParameter_IncludingLambdaBodiesRecursive(IntegrationBody integrationBody, FunctionUnit functionUnit, Action<SyntaxNode> onParameterGenerated) { GenereteArgumentsFromInput(integrationBody, functionUnit, onParameterGenerated); FunctionUnitAnalyser.GetAllActionOutputs(functionUnit, onUnconnected: sig => IntegrationAnalyser.IsOutputOfIntegration(integrationBody, sig.DSD, integrationDsd => IntegrationAnalyser.IntegrationOutput(integrationBody, integrationDsd, implementByAction: s => AssignActionNameToParameter(integrationBody, sig, onParameterGenerated), implementByReturn: () => LambdaThatAssignsToLocalReturnVariable(integrationBody, sig.DSD, integrationDsd, onParameterGenerated))), onConnected: sig => { var lambdaparameter = GenerateAllLambdaParameter(integrationBody, sig.DSD); var lambdabody = new List<SyntaxNode>(); IntegrationAnalyser.GetAllFunctionUnitsThatAreInsideThisLambda(integrationBody, sig, fu => { var mc = CreateMethodCall(fu, integrationBody); lambdabody.Add(mc); }); SyntaxNode lambdaExpression = null; GenerateLambdaExpression(integrationBody.Generator, lambdaparameter, lambdabody.ToArray(), node => lambdaExpression = node); SyntaxNode arg = null; // Minor design decision here: // When action name is provided use "named arguments" when calling this method // if not provided but output needs to be implemented with action don't use named arguments OutputAnalyser.IsActionNameDefined(sig.DSD, onDefined: () => { var argumentName = Names.NewAction(sig.DSD); arg = GenerateArgument(integrationBody.Generator, argumentName, lambdaExpression); }, onUndefined: () => arg = GenerateArgument(integrationBody.Generator, null, lambdaExpression)); onParameterGenerated(arg); }); } private static void LambdaThatAssignsToLocalReturnVariable(IntegrationBody integrationBody, DataStreamDefinition subDsd, DataStreamDefinition integrationDsd, Action<SyntaxNode> onParameterGenerated) { SyntaxNode body = null; var lambdaparameter = GenerateAllLambdaParameter(integrationBody, subDsd, getNames: names => body = FromLambdaParameterToReturnVariable(integrationBody, names)); SyntaxNode lambdaExpression = null; GenerateLambdaExpression(integrationBody.Generator, lambdaparameter, new [] {body}, node => lambdaExpression = node); onParameterGenerated(GenerateArgument(integrationBody.Generator, null, lambdaExpression)); } private static SyntaxNode FromLambdaParameterToReturnVariable(IntegrationBody integrationBody, List<string> names) { if (names.Count > 1) return integrationBody.Generator.IdentifierName("@return = // TODO "); return integrationBody.Generator.IdentifierName("@return = "+names.First()); } private static SyntaxNode GenerateArgument(SyntaxGenerator generator, string argumentname, SyntaxNode expression) { return string.IsNullOrWhiteSpace(argumentname) ? generator.Argument(expression) : generator.Argument(argumentname, RefKind.None, expression); } private static void AssignActionNameToParameter(IntegrationBody integrationBody, MethodSignaturePart sig, Action<SyntaxNode> onParameterGenerated) { var integrationActionOutput = IntegrationAnalyser.GetMatchingActionFromIntegration(integrationBody, sig, onError: () => { throw new UnnconnectedOutputException(sig.DSD); }); var actionname = Names.NewAction(integrationActionOutput); onParameterGenerated(integrationBody.Generator.IdentifierName(actionname)); } public static void GenereteArgumentsFromInput(IntegrationBody integrationBody, FunctionUnit functionUnit, Action<SyntaxNode> onParameterGenerated) { var inputsDsd = functionUnit.InputStreams.First(); var inputs = DataStreamParser.GetInputPart(inputsDsd.DataNames); var dependecies = integrationBody.CallDependecies.First(x => x.OfFunctionUnit == functionUnit); inputs.ToList().ForEach(neededNt => { var varname = GetLocalVariable(integrationBody, dependecies, neededNt, inputsDsd); var arg = integrationBody.Generator.Argument(integrationBody.Generator.IdentifierName(varname)); onParameterGenerated(arg); }); } private static string GetLocalVariable(IntegrationBody integrationBody, MethodWithParameterDependencies dependecies, NameType neededNt, DataStreamDefinition inputsDsd) { var parameter = dependecies.Parameters.FirstOrDefault(x => IsMatchingNameType(x.NeededNameType, neededNt)); var varname = GetLocalVariable(integrationBody, parameter, neededNt, inputsDsd)?.VariableName; return varname; } private static GeneratedLocalVariable GetLocalVariable(IntegrationBody integrationBody, Parameter parameter, NameType needed, DataStreamDefinition inputDsd) { if (parameter == null) throw new MissingInputDataException(inputDsd, needed); var found = integrationBody.LocalVariables.FirstOrDefault(y => y.Source == parameter.Source && y.NameTypes.First().Type == needed.Type && y.NameTypes.First().Name == needed.Name); if (found == null) throw new MissingInputDataException(inputDsd, needed); return found; } public static bool IsMatchingNameType(NameType nt1, NameType nt2) { return (nt2.Type == nt1.Type) && (nt2.IsArray == nt1.IsArray) && (nt2.IsList == nt1.IsList) && (nt2.Name == nt1.Name); } public static SyntaxNode GenerateLocalMethodCall(SyntaxGenerator generator, string name, SyntaxNode[] parameter, string localname) { var invocationExpression = generator.InvocationExpression( generator.IdentifierName(name), parameter ?? new SyntaxNode[] { }); // When no type then it is void method and no assignemnt to local variable is needed if (localname == null) return invocationExpression; return generator.LocalDeclarationStatement(localname, invocationExpression); } } }
// Copyright (c) Dapplo and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Dapplo.Windows.Input.Enums { /// <summary> /// Symbolic constant names, hexadecimal values, and mouse or keyboard equivalents for the virtual-key codes used by /// the system. /// The codes are listed in numeric order. /// See <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731.aspx">Virtual-Key Codes</a> /// </summary> public enum VirtualKeyCode : ushort { /// <summary> /// Not a key /// </summary> None = 0x00, /// <summary> /// Left mouse button /// </summary> Lbutton = 0x01, /// <summary> /// Right mouse button /// </summary> Rbutton = 0x02, /// <summary> /// Control-break processing /// </summary> Cancel = 0x03, /// <summary> /// Middle mouse button (three-button mouse) /// </summary> Mbutton = 0x04, /// <summary> /// Windows 2000/XP: X1 mouse button /// </summary> Xbutton1 = 0x05, /// <summary> /// Windows 2000/XP: X2 mouse button /// </summary> Xbutton2 = 0x06, /// <summary> /// BACKSPACE key /// </summary> Back = 0x08, /// <summary> /// TAB key /// </summary> Tab = 0x09, /// <summary> /// CLEAR key /// </summary> Clear = 0x0C, /// <summary> /// ENTER key /// </summary> Return = 0x0D, /// <summary> /// SHIFT key /// </summary> Shift = 0x10, /// <summary> /// CTRL key /// </summary> Control = 0x11, /// <summary> /// ALT key /// </summary> Menu = 0x12, /// <summary> /// PAUSE key /// </summary> Pause = 0x13, /// <summary> /// CAPS LOCK key /// </summary> Capital = 0x14, /// <summary> /// Input Method Editor (IME) Kana mode /// </summary> Kana = 0x15, /// <summary> /// IME Hangul mode /// </summary> Hangul = 0x15, /// <summary> /// IME Junja mode /// </summary> Junja = 0x17, /// <summary> /// IME final mode /// </summary> Final = 0x18, /// <summary> /// IME Hanja mode /// </summary> Hanja = 0x19, /// <summary> /// IME Kanji mode /// </summary> Kanji = 0x19, /// <summary> /// ESC key /// </summary> Escape = 0x1B, /// <summary> /// IME convert /// </summary> Convert = 0x1C, /// <summary> /// IME nonconvert /// </summary> Nonconvert = 0x1D, /// <summary> /// IME accept /// </summary> Accept = 0x1E, /// <summary> /// IME mode change request /// </summary> Modechange = 0x1F, /// <summary> /// SPACEBAR /// </summary> Space = 0x20, /// <summary> /// PAGE UP key /// </summary> Prior = 0x21, /// <summary> /// PAGE DOWN key /// </summary> Next = 0x22, /// <summary> /// END key /// </summary> End = 0x23, /// <summary> /// HOME key /// </summary> Home = 0x24, /// <summary> /// LEFT ARROW key /// </summary> Left = 0x25, /// <summary> /// UP ARROW key /// </summary> Up = 0x26, /// <summary> /// RIGHT ARROW key /// </summary> Right = 0x27, /// <summary> /// DOWN ARROW key /// </summary> Down = 0x28, /// <summary> /// SELECT key /// </summary> Select = 0x29, /// <summary> /// PRINT key /// </summary> Print = 0x2A, /// <summary> /// EXECUTE key /// </summary> Execute = 0x2B, /// <summary> /// This is the PrintScreen key, which is also called Snapshot /// </summary> PrintScreen = 0x2C, /// <summary> /// This is the PrintScreen key, which is also called Snapshot /// </summary> Snapshot = 0x2C, /// <summary> /// INS key /// </summary> Insert = 0x2D, /// <summary> /// DEL key /// </summary> Delete = 0x2E, /// <summary> /// HELP key /// </summary> Help = 0x2F, /// <summary> /// 0 key /// </summary> Key0 = 0x30, /// <summary> /// 1 key /// </summary> Key1 = 0x31, /// <summary> /// 2 key /// </summary> Key2 = 0x32, /// <summary> /// 3 key /// </summary> Key3 = 0x33, /// <summary> /// 4 key /// </summary> Key4 = 0x34, /// <summary> /// 5 key /// </summary> Key5 = 0x35, /// <summary> /// 6 key /// </summary> Key6 = 0x36, /// <summary> /// 7 key /// </summary> Key7 = 0x37, /// <summary> /// 8 key /// </summary> Key8 = 0x38, /// <summary> /// 9 key /// </summary> Key9 = 0x39, /// <summary> /// A key /// </summary> KeyA = 0x41, /// <summary> /// B key /// </summary> KeyB = 0x42, /// <summary> /// C key /// </summary> KeyC = 0x43, /// <summary> /// D key /// </summary> KeyD = 0x44, /// <summary> /// E key /// </summary> KeyE = 0x45, /// <summary> /// F key /// </summary> KeyF = 0x46, /// <summary> /// G key /// </summary> KeyG = 0x47, /// <summary> /// H key /// </summary> KeyH = 0x48, /// <summary> /// I key /// </summary> KeyI = 0x49, /// <summary> /// J key /// </summary> KeyJ = 0x4A, /// <summary> /// K key /// </summary> KeyK = 0x4B, /// <summary> /// L key /// </summary> KeyL = 0x4C, /// <summary> /// M key /// </summary> KeyM = 0x4D, /// <summary> /// N key /// </summary> KeyN = 0x4E, /// <summary> /// O key /// </summary> KeyO = 0x4F, /// <summary> /// P key /// </summary> KeyP = 0x50, /// <summary> /// Q key /// </summary> KeyQ = 0x51, /// <summary> /// R key /// </summary> KeyR = 0x52, /// <summary> /// S key /// </summary> KeyS = 0x53, /// <summary> /// T key /// </summary> KeyT = 0x54, /// <summary> /// U key /// </summary> KeyU = 0x55, /// <summary> /// V key /// </summary> KeyV = 0x56, /// <summary> /// W key /// </summary> KeyW = 0x57, /// <summary> /// X key /// </summary> KeyX = 0x58, /// <summary> /// Y key /// </summary> KeyY = 0x59, /// <summary> /// Z key /// </summary> KeyZ = 0x5A, /// <summary> /// Left Windows key (Microsoft Natural keyboard) /// </summary> LeftWin = 0x5B, /// <summary> /// Right Windows key (Natural keyboard) /// </summary> RightWin = 0x5C, /// <summary> /// Applications key (Natural keyboard) /// </summary> Apps = 0x5D, /// <summary> /// Computer Sleep key /// </summary> Sleep = 0x5F, /// <summary> /// Numeric keypad 0 key /// </summary> Numpad0 = 0x60, /// <summary> /// Numeric keypad 1 key /// </summary> Numpad1 = 0x61, /// <summary> /// Numeric keypad 2 key /// </summary> Numpad2 = 0x62, /// <summary> /// Numeric keypad 3 key /// </summary> Numpad3 = 0x63, /// <summary> /// Numeric keypad 4 key /// </summary> Numpad4 = 0x64, /// <summary> /// Numeric keypad 5 key /// </summary> Numpad5 = 0x65, /// <summary> /// Numeric keypad 6 key /// </summary> Numpad6 = 0x66, /// <summary> /// Numeric keypad 7 key /// </summary> Numpad7 = 0x67, /// <summary> /// Numeric keypad 8 key /// </summary> Numpad8 = 0x68, /// <summary> /// Numeric keypad 9 key /// </summary> Numpad9 = 0x69, /// <summary> /// Multiply key /// </summary> Multiply = 0x6A, /// <summary> /// Add key /// </summary> Add = 0x6B, /// <summary> /// Separator key /// </summary> Separator = 0x6C, /// <summary> /// Subtract key /// </summary> Subtract = 0x6D, /// <summary> /// Decimal key /// </summary> Decimal = 0x6E, /// <summary> /// Divide key /// </summary> Divide = 0x6F, /// <summary> /// F1 key /// </summary> F1 = 0x70, /// <summary> /// F2 key /// </summary> F2 = 0x71, /// <summary> /// F3 key /// </summary> F3 = 0x72, /// <summary> /// F4 key /// </summary> F4 = 0x73, /// <summary> /// F5 key /// </summary> F5 = 0x74, /// <summary> /// F6 key /// </summary> F6 = 0x75, /// <summary> /// F7 key /// </summary> F7 = 0x76, /// <summary> /// F8 key /// </summary> F8 = 0x77, /// <summary> /// F9 key /// </summary> F9 = 0x78, /// <summary> /// F10 key /// </summary> F10 = 0x79, /// <summary> /// F11 key /// </summary> F11 = 0x7A, /// <summary> /// F12 key /// </summary> F12 = 0x7B, /// <summary> /// F13 key /// </summary> F13 = 0x7C, /// <summary> /// F14 key /// </summary> F14 = 0x7D, /// <summary> /// F15 key /// </summary> F15 = 0x7E, /// <summary> /// F16 key /// </summary> F16 = 0x7F, /// <summary> /// F17 key /// </summary> F17 = 0x80, /// <summary> /// F18 key /// </summary> F18 = 0x81, /// <summary> /// F19 key /// </summary> F19 = 0x82, /// <summary> /// F20 key /// </summary> F20 = 0x83, /// <summary> /// F21 key /// </summary> F21 = 0x84, /// <summary> /// F22 key, (PPC only) Key used to lock device. /// </summary> F22 = 0x85, /// <summary> /// F23 key /// </summary> F23 = 0x86, /// <summary> /// F24 key /// </summary> F24 = 0x87, /// <summary> /// NUM LOCK key /// </summary> NumLock = 0x90, /// <summary> /// SCROLL LOCK key /// </summary> Scroll = 0x91, /// <summary> /// Left SHIFT key /// </summary> LeftShift = 0xA0, /// <summary> /// Right SHIFT key /// </summary> RightShift = 0xA1, /// <summary> /// Left CONTROL key /// </summary> LeftControl = 0xA2, /// <summary> /// Right CONTROL key /// </summary> RightControl = 0xA3, /// <summary> /// Left MENU key /// </summary> LeftMenu = 0xA4, /// <summary> /// Right MENU key /// </summary> RightMenu = 0xA5, /// <summary> /// Windows 2000/XP: Browser Back key /// </summary> BrowserBack = 0xA6, /// <summary> /// Windows 2000/XP: Browser Forward key /// </summary> BrowserForward = 0xA7, /// <summary> /// Windows 2000/XP: Browser Refresh key /// </summary> BrowserRefresh = 0xA8, /// <summary> /// Windows 2000/XP: Browser Stop key /// </summary> BrowserStop = 0xA9, /// <summary> /// Windows 2000/XP: Browser Search key /// </summary> BrowserSearch = 0xAA, /// <summary> /// Windows 2000/XP: Browser Favorites key /// </summary> BrowserFavorites = 0xAB, /// <summary> /// Windows 2000/XP: Browser Start and Home key /// </summary> BrowserHome = 0xAC, /// <summary> /// Windows 2000/XP: Volume Mute key /// </summary> VolumeMute = 0xAD, /// <summary> /// Windows 2000/XP: Volume Down key /// </summary> VolumeDown = 0xAE, /// <summary> /// Windows 2000/XP: Volume Up key /// </summary> VolumeUp = 0xAF, /// <summary> /// Windows 2000/XP: Next Track key /// </summary> MediaNextTrack = 0xB0, /// <summary> /// Windows 2000/XP: Previous Track key /// </summary> MediaPrevTrack = 0xB1, /// <summary> /// Windows 2000/XP: Stop Media key /// </summary> MediaStop = 0xB2, /// <summary> /// Windows 2000/XP: Play/Pause Media key /// </summary> MediaPlayPause = 0xB3, /// <summary> /// Windows 2000/XP: Start Mail key /// </summary> LaunchMail = 0xB4, /// <summary> /// Windows 2000/XP: Select Media key /// </summary> LaunchMediaSelect = 0xB5, /// <summary> /// Windows 2000/XP: Start Application 1 key /// </summary> LaunchApp1 = 0xB6, /// <summary> /// Windows 2000/XP: Start Application 2 key /// </summary> LaunchApp2 = 0xB7, /// <summary> /// Used for miscellaneous characters; it can vary by keyboard. /// </summary> Oem1 = 0xBA, /// <summary> /// Windows 2000/XP: For any country/region, the '+' key /// </summary> OemPlus = 0xBB, /// <summary> /// Windows 2000/XP: For any country/region, the ',' key /// </summary> OemComma = 0xBC, /// <summary> /// Windows 2000/XP: For any country/region, the '-' key /// </summary> OemMinus = 0xBD, /// <summary> /// Windows 2000/XP: For any country/region, the '.' key /// </summary> OemPeriod = 0xBE, /// <summary> /// Used for miscellaneous characters; it can vary by keyboard. /// </summary> Oem2 = 0xBF, /// <summary> /// Used for miscellaneous characters; it can vary by keyboard. /// </summary> Oem3 = 0xC0, /// <summary> /// Used for miscellaneous characters; it can vary by keyboard. /// </summary> Oem4 = 0xDB, /// <summary> /// Used for miscellaneous characters; it can vary by keyboard. /// </summary> Oem5 = 0xDC, /// <summary> /// Used for miscellaneous characters; it can vary by keyboard. /// </summary> Oem6 = 0xDD, /// <summary> /// Used for miscellaneous characters; it can vary by keyboard. /// </summary> Oem7 = 0xDE, /// <summary> /// Used for miscellaneous characters; it can vary by keyboard. /// </summary> Oem8 = 0xDF, /// <summary> /// Windows 2000/XP: Either the angle bracket key or the backslash key on the RT 102-key keyboard /// </summary> Oem102 = 0xE2, /// <summary> /// Windows 95/98/Me, Windows NT 4.0, Windows 2000/XP: IME PROCESS key /// </summary> Processkey = 0xE5, /// <summary> /// Windows 2000/XP: Used to pass Unicode characters as if they were keystrokes. /// The VK_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more /// information, /// see Remark in KEYBDINPUT, SendInput, WM_KEYDOWN, and WM_KEYUP /// </summary> Packet = 0xE7, /// <summary> /// Attn key /// </summary> Attn = 0xF6, /// <summary> /// CrSel key /// </summary> Crsel = 0xF7, /// <summary> /// ExSel key /// </summary> Exsel = 0xF8, /// <summary> /// Erase EOF key /// </summary> Ereof = 0xF9, /// <summary> /// Play key /// </summary> Play = 0xFA, /// <summary> /// Zoom key /// </summary> Zoom = 0xFB, /// <summary> /// Reserved /// </summary> Noname = 0xFC, /// <summary> /// PA1 key /// </summary> Pa1 = 0xFD, /// <summary> /// Clear key /// </summary> OemClear = 0xFE } }